0% found this document useful (0 votes)
57 views21 pages

Unit 4 PWC

1. A structure allows us to combine data of different types together into a single unit called a structure variable. 2. Structures are declared using the struct keyword and defined with member names and types. Structure variables can then be defined to allocate memory for each member. 3. Structure members can be accessed using the dot (.) operator and the member name after specifying a structure variable name.

Uploaded by

Guru Rockzz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views21 pages

Unit 4 PWC

1. A structure allows us to combine data of different types together into a single unit called a structure variable. 2. Structures are declared using the struct keyword and defined with member names and types. Structure variables can then be defined to allocate memory for each member. 3. Structure members can be accessed using the dot (.) operator and the member name after specifying a structure variable name.

Uploaded by

Guru Rockzz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Syllabus:

Structures:

Structure is a user-defined datatype in which allows us to combine data of different types


(heterogeneous) together. Structure helps to construct a complex data type which is more
meaningful.

Structure declaration:

‘struct’ keyword is used to create a structure.

The format of the struct statement is as follows −

struct [structure tag] {


member definition;
member definition;
...
member definition;
} [one or more structure variables];

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

2) Declaring Structure object with structure definition


struct Student
{
char name[25];
int age;
char branch[10];
char gender; //F for female and M for male
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much
recommended.
Structure Initialization
When we declare a structure, memory is not allocated for un-initialized variable

Way 1: Declare and Initialize


struct student
{
char name[20];
int roll;
float marks;
}std1 = { "Pritesh",67,78.3 };

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 }

Way 2: Declaring and Initializing Multiple Variables


struct student
{
char name[20];
int roll;
float marks;
}std1 = {"Pritesh",67,78.3}, std2 = {"Don",62,71.3};

In this example, we have declared two structure variables in above code. After declaration of
variable we have initialized two variables.

Way 3: Initializing Single member


struct student
{
int mark1;
int mark2;
int mark3;
} sub1={67};
Though there are three members of structure, only one is initialized , Then remaining two members
are initialized with Zero.

Way 4: Initializing inside main


struct student
{
int mark1;
int mark2;
int mark3;
};
void main()
{
struct student s1 = {89,54,65};
- - - - -- - - -- - - - --};
Output:

Accessing Structure Members Book 1 title : C Programming

Book 1 author : Nuha Ali


#include <stdio.h>
#include <string.h> Book 1 subject : C Programming Tutorial

struct Books { Book 1 book_id : 6495407


char title[50];
char author[50]; Book 2 title : Telecom Billing
char subject[100]; Book 2 author : Zara Ali
int book_id;
}; Book 2 subject : Telecom Billing Tutorial

int main( ) { Book 2 book_id : 6495700

struct Books Book1; /* Declare Book1 of type Book */


struct Books Book2; /* Declare Book2 of type Book */

/* 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;

/* print Book1 info */


printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);

/* print Book2 info */


printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);

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("Enter name: ");


scanf("%s", s.name);

printf("Enter roll number: ");


scanf("%d", &s.roll);

printf("Enter marks: ");


scanf("%f", &s.marks);

printf("Displaying Information:\n");

printf("Name: ");
puts(s.name);

printf("Roll number: %d\n",s.roll);

printf("Marks: %.1f\n", s.marks);


}

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);
}

The structure can be nested in the following ways.


1. By separate structure
2. By Embedded structure

1) Separate structure 2) Embedded structure


struct Date struct Employee
{ {
int dd; int id;
int mm; char name[20];
int yyyy; struct Date
}; {
struct Employee int dd;
{ int mm;
int id; int yyyy;
char name[20]; }doj;
struct Date doj;
}emp1;
}emp1;
Accessing Nested Structure
We can access the member of the nested structure by
Outer_Structure.Nested_Structure.member as given below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy

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

The average marks of all students


is: 89.600000
Pointer to structure:

To access members of a structure using pointers, we use the -> operator.

#include <stdio.h>
struct person
{
int age;
float weight;
};

int main()
Write your output here…
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}

Another simple example:


#include <stdio.h>

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;

printf("NAME: %s\n", ptr->name);


printf("NUMBER: %d\n", ptr->number);
printf("RANK: %d", ptr->rank);
}
Structure and functions:
Here's how you can pass structures to a function

#include <stdio.h>
struct student
{
char name[50];
int age;
};

void display(struct student s);

void main()
{
struct student s1;

printf("Enter name: ");


scanf("%[^\n]%*c", s1.name);

printf("Enter age: ");


scanf("%d", &s1.age);

display(s1); // passing struct as an argument


}

void display(struct student s)


{
printf("\nDisplaying information\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}

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);

printf("For second number, \n");


printf("Enter real part: ");
scanf("%f", &c2.real);
printf("Enter imaginary part: ");
scanf("%f", &c2.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;

strcpy( book.title, "C Programming");


strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;

printf( "Book title : %s\n", book.title);


printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}

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.

 typedef interpretation is performed by the compiler whereas #define statements


are processed by the pre-processor.
Limitations of C Structures

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 −

union [union tag] {


member definition;
member definition;
...
member definition;
} [one or more union variables];

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 (.)

#include <stdio.h> #include <stdio.h>


#include <string.h> #include <string.h>

union Data { union Data {


int i; int i;
float f; float f;
char str[20]; char str[20];
}; };

int main( ) { int main( ) {

union Data data; union Data data;

data.i = 10; data.i = 10;


data.f = 220.5; printf( "data.i : %d\n", data.i);
strcpy(data.str, "C Programming");
data.f = 220.5;
printf( "data.i : %d\n", data.i); printf( "data.f : %f\n", data.f);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str); strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
return 0;
} return 0;
}
Output: Output:
data.i : 1917853763 data.i : 10
data.f: 4122360779489994368.000000 data.f : 220.500000
data.str : C Programming data.str : C Programming

Enumerated data type:

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.

The keyword “enum” is used to declare an enumeration.

Syntax

enum enumname{const1, const2, ....... };

Example;

enum week{sunday, monday, tuesday, wednesday, thursday,


friday, saturday};

enum week day;


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

Another example program


#include<stdio.h>
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
void main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
}
Output:
0 1 2 3 4 5 6 7 8 9 10 11

Interesting facts about initialization of enum:


1. Two enum names can have same value. For example, in the following C program both ‘Failed’ and
‘Freezed’ have same value 0.
#include <stdio.h> Output:
enum State {Working = 1, Failed = 0, Freezed = 0};
1, 0, 0
void main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
}
2. If we do not explicitly assign values to enum names, the compiler by default assigns values
starting from 0. For example, in the following C program, sunday gets value 0, monday gets 1, and
so on.

#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);
}}

Write your output here.


Program: Define a structure called cricket that will describe the following information player name,
team name, batting average. Using the structure, declare an array player with 50 elements and
write a C program to read the information about all players and print the team wise list containing
the names of the players with their batting average.
Sample code:
struct cricket
{
char nm[15];
char tnm[10];
int btavg;
};
void main()
{
struct cricket player[50];
printf("No of players\n");
scanf("%d",&n);
for (i=0;i<n;i++) // get details
{
printf("\ninput the name of player : ");
scanf("%s",player[i].nm);
printf("\ninput the team name of player");
scanf("%s",player[i].tnm);
printf("\ninput the batting average of player");
scanf("%d",&player[i].btavg);
}
printf("\nInput for which team you want to list : "); // display teamwise details
scanf("%s",team);
printf(“ %s",team);
for (i=0; i<=n; i++)
if (strcmp(team,player[i].tnm)==0)
printf(" %s %d\n",player[i].nm,player[i].btavg);
getch();
}

Write your output here.


Program: Write a C program to create a structure ‘student’, containing name, rollno, an integer
array of marks, total and average. Get name, rollno and mark values for three students and calculate
the total and average. Display the student details.
struct student
{
char name[10] ;
int rollno, mark[3], tot ;
float avg ;
};
void main()
{
struct student s[3];
int i, n ;
for(i = 0 ; i < 3 ; i++)
{
printf("\nEnter the rollno : ") ;
scanf("%d", &s[i].rollno) ;
printf("\nEnter the name : ") ;
scanf("%s", s[i].name) ;
printf("\nEnter the marks in 3 subjects : ") ;
for(j=0;j<3;j++){
scanf(“%d”,&s[i].mark[j]);
s[i].tot+=s[i].mark[j]; }
s[i].avg = s[i].tot / 3.0 ;
}printf("\nRoll No. Name \t Total\t Average\n\n") ;
for(i = 0 ; i < 3 ; i++)
{
printf("%d \t %s \t\t %d \t %d \t %d\t %d \t %.2f \n", s[i].rollno, s[i].name, s[i].tot, s[i].avg);
}
}
Write your output here.

Program: Pointer to structure example


#include <stdio.h>
struct student
{
int id;
char name[30];
float percentage;
};
void main()
{
int i;
struct student record1 = {1, "Raju", 90.5}; //or get the details from the user with scanf
struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000

You might also like