Unit 4 PWC
Unit 4 PWC
Structures:
Structure declaration:
Following is an example.
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Structure object creation:
1) Declaring Structure object separately
struct Student
{
char name[25];
int age;
char branch[10];
char gender; //F for female and M for male
};
struct Student S1, S2; //declaring object of struct Student
In the above code snippet, we have seen that structure is declared and as soon as after declaration
we have initialized the structure variable.
std1 = {"Pritesh",67,78.3 }
In this example, we have declared two structure variables in above code. After declaration of
variable we have initialized two variables.
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
return 0;
}
Program 1: Store a Student Information and Display it Using Structure
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;
void main()
{
printf("Enter information:\n");
printf("Displaying Information:\n");
printf("Name: ");
puts(s.name);
Output:
Enter information:
Enter name: Jack
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Jack
Roll number: 23
Marks: 34.5
Structure inside structure (Nested structure):
One structure can be declared inside other structure as we declare structure members inside a
structure.
C provides us the feature of nesting one structure within another structure by using which, complex
data types are created. For example, we may need to store the address of an entity employee in a
structure. The attribute address may also have the subparts as street number, city, state, and pin
code. Hence, to store the address of the employee, we need to store the address of the employee
into a separate structure and nest the structure address into the structure employee.
#include<stdio.h>
struct address Output
{ Enter employee information?
char city[20]; Arun
int pin; Delhi
char phone[14]; 110001
}; 1234567890
struct employee Printing the employee
{ information....
char name[20]; name: Arun
struct address add; City: Delhi
}; Pincode: 110001
void main () Phone: 1234567890
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name, emp.add.city, emp.add.
pin,emp. add.phone);
}
Array of structures:
An array of structures in C can be defined as the collection of multiple structures variables where
each variable contains information about different entities. The array of structures in C are used to
store information about multiple entities of different data types. The array of structures is also
known as the collection of structures.
Program : Store few Students information and Display the average using Array of Structure
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];
void main()
{
int i, sum=0,n;
float avg;
printf("Enter number of students:\n");
scanf(“%d”, &n);
printf("Enter information of students:\n");
Output:
for(i=0; i<n; ++i)
Enter number of students: 5
{
Enter information of students:
s[i].roll = i+1;
printf("\nFor roll number%d,\n",s[i].roll);
For roll number1,
Enter name: Tom
printf("Enter name: ");
Enter marks: 98
scanf("%s",s[i].name);
For roll number2,
printf("Enter marks: ");
Enter name: Jerry
scanf("%f",&s[i].marks);
Enter marks: 89
sum=sum+s[i].marks;
For roll number3,
printf("\n");
Enter name: Jany
}
Enter marks: 81
avg=(float)sum/n;
For roll number4,
Enter name: John
printf("Displaying Information:\n\n");
Enter marks: 85
for(i=0; i<n; ++i)
{
For roll number5,
printf("\nRoll number: %d\n",i+1);
Enter name: cathe
printf("Name: ");
Enter marks: 95
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
Displaying Information:
printf("\n");
}
Roll number: 1
printf(“The average marks of all students is:%f”, avg);
Name: Tom
}
Marks: 98
Roll number: 2
Name: Jerry
Marks: 89
Roll number: 3
Name: Jany
Marks: 81
Roll number: 4
Name: John
Marks: 85
Roll number: 5
Name: cathe
Marks: 95
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
Write your output here…
{
struct person *personPtr, person1;
personPtr = &person1;
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
struct my_structure {
char name[20];
int number; Output:
int rank;
}; NAME: Study
void main()
{ NUMBER: 35
struct my_structure variable = {"Study", 35, 1};
RANK: 1
struct my_structure *ptr;
ptr = &variable;
#include <stdio.h>
struct student
{
char name[50];
int age;
};
void main()
{
struct student s1;
Output
Enter name: Bond
Enter age: 13
Displaying information
Name: Bond
Age: 13
One more example
#include <stdio.h>
#include<conio.h>
struct Complex
{
float real;
float imag;
};
struct Complex addNumbers(struct Complex c1, struct Complex c2)
{
struct Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
int main()
{
struct Complex c1, c2, result;
clrscr();
printf("For first number,\n");
printf("Enter real part: ");
scanf("%f", &c1.real);
printf("Enter imaginary part: ");
scanf("%f", &c1.imag);
result=addNumbers(c1, c2);
printf("\nResult is %.1f+%.1fi", result.real, result.imag);
getch();
return 0;
}
type def:
The C programming language provides a keyword called typedef, which you can use to give a type a
new name. Following is an example to define a term BYTE for one-byte numbers −
typedef unsigned char BYTE;
After this type definition, the identifier BYTE can be used as an abbreviation for the type unsigned
char, for example..
BYTE b1, b2;
Example:
#include <stdio.h>
#include <string.h>
typedef struct Books {
char title[50]; Book title : C Programming
char author[50];
char subject[100]; Book author : Nuha Ali
int book_id; Book subject : C Programming Tutorial
} Book;
Book book_id : 6495407
void main( )
{
Book book;
typedef vs #define
#define is a C-directive which is also used to define the aliases for various data types
similar to typedef but with the following differences −
typedef is limited to giving symbolic names to types only where as #define can be
used to define alias for values as well, q., you can define 1 as ONE etc.
In C language, Structures provide a method for packing together data of different types. A Structure
is a helpful tool to handle a group of logically related data items. However, C structures have some
limitations.
The C structure does not allow the struct data type to be treated like built-in data types: We
cannot use operators like +,- etc. on Structure variables.
No Data Hiding: C Structures do not permit data hiding. Structure members can be accessed
by any function, anywhere in the scope of the Structure.
Functions inside Structure: C structures do not permit functions inside Structure
Static Members: C Structures cannot have static members inside their body
Union:
A union is a special data type available in C that allows storing different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −
Example;
union Data {
int i;
float f;
char str[20];
} data;
Data will occupy 20 bytes of memory space because this is the maximum space which can be
occupied by a character string.
Accessing Union Members
To access any member of a union, we use the member access operator (.)
Enumeration is a user defined datatype in C language. It is used to assign names to the integral
constants, which makes a program easy to read and maintain.
Syntax
Example;
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
void main()
{
printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur,
Fri, Sat, Sun);
printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn,
Thurs, Frid, Satu, Sund);
}
Output
The value of enum week: 10 11 12 13 10 16 17
The default value of enum day: 0 1 2 3 18 11 12
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
void main()
{
Output:
enum day d = thursday;
printf("The day number stored in d is %d", d); The day number stored in d is 4
}
3. We can assign values to some name in any order. All unassigned names get value as value of
previous name plus one.
#include <stdio.h> Output:
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday}; 1 2 5 6 10 11 12
void main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday, thursday, friday,
saturday);
}
4. The value assigned to enum names must be some integeral constant, i.e., the value must be in
range from minimum possible integer value to maximum possible integer value.
5. All enum constants must be unique in their scope. For example, the following program fails in
compilation.
enum state {working, failed}; Output:
enum result {failed, passed};
int main() Compile Error: 'failed' has a
{ previous declaration as 'state failed'
return 0;
}
Enum vs Macro
We can also use macros to define names constants. For example we can define ‘Working’ and Failed’
using following macro.
#define Working 0
#define Failed 1
#define Freezed 2
There are multiple advantages of using enum over macro when many related named constants have
integral values.
a) Enums follow scope rules.
b) Enum variables are automatically assigned values. Following is simpler
enum state {Working, Failed, Freezed};
Bit fields:
In C, we can specify size (in bits) of structure and union members. The idea is to use memory
efficiently when we know that the value of a field or group of fields will never exceed a limit or is
within a small range.
#include <stdio.h>
struct date { Output:
unsigned int d;
Size of date is 12 bytes
unsigned int m;
unsigned int y; Date is 31/12/2014
};
void main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2020 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
The above representation of ‘date’ takes 12 bytes on a compiler where an unsigned int takes 4
bytes. Since we know that the value of d is always from 1 to 31, the value of m is from 1 to 12, we
can optimize the space using bit fields.
#include <stdio.h>
struct date {
// d has value between 1 and 31, so 5 bits are sufficient Output:
unsigned int d : 5;
Size of date is 8 bytes
// m has value between 1 and 12, so 4 are sufficient Date is 31/12/2014
unsigned int m : 4;
unsigned int y;
};
void main()
{
printf("Size of date is %lu bytes\n", sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
}
Advantages of Bit Fields:
1) When storage is less, many true/false variables can be stored in one byte.
2) Some algorithms need to access the bits within a byte.
3) Some devices transmit status info encoded in bits.
4) It adds efficiency to the program.
5) For analyzing input from a hardware.
Limitations of Bit Fields:
1) Address of a bit field cannot be taken in to account.
2) We can’t have an array of bit fields.
3) A bit field can’t be declared as static.
4) A bit filed is dependent on a machine.
Examples from previous ESE:
Program: Create a structure Student that consist of the following members: name, marks in three
subjects (Physics, Chemistry and Mathematics), cutoff and rank. Write a program that does the
following:
i) To read the details of ‘n’ students and calculate the cutoff mark scored by each student.
ii) To find and display the list of students based on their ranks.
struct student
{
char name[10] ;
int p,c,m, cutoff, rank ;
};
void main()
{
struct student s[10],temp;
scanf(“%d”,&n) ;
for(i = 0 ; i < n ; i++)
{
printf("\nEnter the name : ") ;
scanf("%s", s[i].name) ;
scanf(“%d%d%d”,&s[i].p, &s[i].c, &s[i].m);
s[i].cutoff=(s[i].p/4) + (s[i].c/4) + (s[i].m/2);
for(i=0;i<=n-1;i++)
{
for(j=0;j<=n-1;j++)
{
if(s[j].cutoff<s[j+1].cutoff)
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
}
}
}
for(i = 0 ; i < n ; i++)
{
printf("Rank: %d \t %s \t %.2f \n", i, s[i].name, s[i].cutoff);
}}