You are on page 1of 13

TM's

Lecture Notes in C Programming (LNCP)


Unit 2 Part 3
Structures
Ver. 1.5
TM’s C Programming Lecture Notes Ver. 1.5 Structures

Table of Contents
1. Introduction 3

2. Defining a structure 4
2.1 Array vs. Structure 4

3. Declaring structure variables 5

4. Accessing structure members 5

5. Structure Initialization 6
Rules for Initializing structure variables 6

6. Copying & Comparing Structures Variable 8

7. Array of Structures 9

8. Application program: Rank-wise sorting of student records: 11

9. Operation on Individual members (SLE) 12

2 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

​1. Introduction
❑ Arrays support packing the same type data together.
❑ Many times, packing of different types of data is necessary in programming.
❑ E.g. A Student record may contain a name which is a string, id an integer, cgpa a float, etc.
❑ How to store and process details of 60 students in a class?? (e.g: name,id,cgpa)
❑ One possible solution is:
char names[60][25];
int id[60];
float cgpa[60];
❑ This is not an elegant solution as processing of the data is tedious and code size will become large.
❑ Structures in C: Provides a better way to deal with such situations.
❑ Structures enable us to create new data types of our own..!!
❑ Such data types are known as ‘User Defined Data types’.
❑ Structures can combine different built-in data types to define new data types.

Defining student structure (Creating a new data type)

❑ For our student problem:


struct Student
{
char name[20];
int id;
float cgpa;
};

❑ Now Student data type behaves similar to built-in data types like int, char etc.
Size of a Structure type or structure variable
❑ Normally, Size of a structure is the total size of the members in that structure.
❑ For Student structure above, the size is 20 + 4 + 4 = 28 bytes, assuming character size 1 byte, size of int and
float are 4 bytes each.
❑ There are some exceptions to this. If size of structure is not a multiple of the word size** (in bytes) of the
system, some extra bytes will be added to the size to make it a proper multiple of the word size.

3 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

❑ E.g. For a 32-bit machine word size is 4 bytes(32 bits). If structure is as below:
struct Student
{
char name[25];
int id;
float cgpa;
};
We expect the size to be 25+4+4 = 33, but most of the systems add 3 more bytes to make it 36, a multiple of 4.
These additional 3 bytes will be unused.
** Word size of computer system refers to the size of the data processed by a computer's CPU in one go (these days,
typically 4 bytes(32 bit) or 8 bytes(64 bits).

​2. Defining a structure


❑ General format:
struct type-name
{
data-type1 name1;
data-type2 name2;
------------- ---------
------------- ---------
};

​2.1 Array vs. Structure


❑ Array
❑ Array is derived data type
❑ Collection of related data of the same type.
❑ A derived data type from existing data types(e.g int int[ ])
❑ Data type is often available, just declare an array.
❑ General syntax of array declaration:
Data-type array-name[size]
❑ Structure
❑ Structure is a user defined data type.
❑ Collection of different data types.
❑ Structure is a programmer/user defined data type.
❑ Need to define data type first, then declare variables/arrays of the new type.
❑ General Syntax of structure definition: Shown above

4 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

​3. Declaring structure variables


❑ Assume the structure is defined as:
struct mytype
{
int n;
char c;
float f;
};
❑ Declaring variable of type mytype.
struct mytype s1,s2;
sounds similar to int a1,a2; ????
You are right..!!
Instead of int 🡺 struct mytype
Instead a1,a2 🡺 s1,s2
❑ A structure type variable declaration is similar to any basic type variable declaration
Declaring structure variables - other ways
struct mytype
{
int n;
char c;
float f;
}s1,s2;

❑ mytype is the new data type and s1,s2 are variables(a.k.a. instances) of that type!!

​4. Accessing structure members


Accessing structure members & initialization. Members of a structure variable is accessed using dot(.) operator.
Dot(.) operator is also referred as member operator. See the example.
struct mytype
{
int n;
char c;
float f;
}s1;

int main()
{
// accessing members & assigning values
s1.n = 10;
s1.c = 'a';

5 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

s1.f = 1.32;

// Displaying member values


printf("%d %c %f", s1.n, s1.c,s1.f);

return 0;
}

​5. Structure Initialization


Compile time initialization:
Compile time initialization is similar to array initialization.

E.g.

struct mytype s1 = {10,'a',2.57};

Rules for Initializing structure variables


There are few rules to keep in mind while initializing structure variables at compile-time.
1. We cannot initialize individual members inside the structure definition/template.
2. The order of values enclosed in braces must match the order of members in the structure definition.
3. It is permitted to have a partial initialization. We can initialize only the first few members and leave the
remaining blank. The uninitialized members should be only at the end of the list.
4. The uninitialized members will be assigned default values, i.e – Zero for integer and floating point numbers
and  ‘\0’ for characters and strings

Example 1: Declaring & compile time initialization of structure instances


// declaring structure variables
// and Initialization of members
#include<stdio.h>

struct mytype
{
int n;
char c;
float f;
};
void main()
{
struct mytype s1 = {10,'a',2.57};

printf("%d %c %f\n",s1.n,s1.c,s1.f);
}

Output:

6 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

10 a 2.570000

Example 2: Student Structure


// Student Structure
#include<stdio.h>
struct Student
{
char name[50];
int id;
float cgpa;
};
void main()
{
// Variable declaration and initialization
struct Student s = {"Amit",1014,9.35};
printf("%s %d %f\n",s.name,s.id,s.cgpa);

//Modifying one member


s.cgpa = 9.10;

// Display again
printf("%s %d %f\n",s.name,s.id,s.cgpa);

}
Output:
Amit 1014 9.350000
Amit 1014 9.100000

Run time initialization:


● Read the data directly from the user during execution & store in a
structure variable.

Example: Student Structure read from user


// Student Structure read from user
// Run time initialization of structure variables
#include<stdio.h>

struct Student
{
char name[20];
int rollno;
float cgpa;
};

int main()
{

7 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

struct Student s;

printf("Enter student details:");

scanf("%s %d %f", s.name, &s.rollno, &s.cgpa);

printf("%s %d %f\n", s.name, s.rollno,s.cgpa);

s.rollno += 100; // Modifying 1 member

printf("%s %d %f", s.name, s.rollno,s.cgpa);


}

Output:
Enter student details: Amit 1024 9.44
Amit 1024 9.440000
Amit 1124 9.440000

6. Copying & Comparing Structures Variable

- Copying a structure variable using assignment operator is possible.


- This way of copying is also called shallow copying.
- Read more about shallow copying and deep copying.
#include<stdio.h>
struct Student
{
char name[20];
int rollno;
float cgpa;
};

int main()
{
struct Student s1 = {"Amit", 1234, 9.34};
struct Student s2;

s2 = s1; // s1 contents are copied to s1.

printf("S1: %s %d %.2f\n", s1.name,s1.rollno,s1.cgpa);


printf("S2: %s %d %.2f\n", s2.name,s2.rollno,s2.cgpa);
return 0;
}
Output:
S1: Amit 1234 9.34
S2: Amit 1234 9.34

8 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

Comparing structures:
Relation operators do not support comparing user-defined data types.

So statements like if(s1 == s2) are invalid.

To compare two structure variables, its members should be individually


compared.

e.g. if(s1.rollno == s2.rollno)

​7. Array of Structures


Structure is a user-defined data type. Just like we create an array of built-in data types, we can create array of
structure types as well. Following example illustrates how to do this.
General format:
struct type-name identifier[size-value];

E.g.
struct Student students[10];

Example: Array of structure instances

#include<stdio.h>
struct Student
{
char name[20];
int rollno;
float cgpa;
};

int main()
{

struct Student s[10]; // array of Student type with size 10


int n,i;
printf("How many students?");
scanf("%d",&n);

// Reading data from user into each array element


for(i=0;i<n;i++)
{
printf("Enter student's data %d:\n",i+1);
scanf("%s %d %f", s[i].name, &s[i].rollno,&s[i].cgpa);
}

9 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

printf("Entered details are:\n");


for(i=0;i<n;i++)
{
printf("%s %d %f \n", s[i].name, s[i].rollno,s[i].cgpa);
}
return 0;

Output:
How many students?2
Enter student's data 1:
Amit 1202 9.6
Enter student's data 2:
Rohan 1022 8.5

Entered details are:


Amit 1202 9.600000
Rohan 1022 8.500000

Creating instances along with structure definition


We can create structure instance/variable along with the definition of structure.

Example:
struct mytype
{
int n;
char c;
float f;
}s1;

Following example demonstrates the same for Student structure.

// Student Structure
// Creating variable along with structure definition
#include<stdio.h>
struct Student
{
char name[50];
int id;
float cgpa;
}s1,s[5];

// In above, s1 is a variable of Student type


// s[5] is an array of Student type
// Both can be used in main function as usual

10 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

int main()
{
// Variable declaration and initialization
printf("Enter student details(name,id,cgpa):");
scanf("%s %d %f", s1.name,&s1.id,&s1.cgpa);
printf("Name: %s \nID: %d \nCGPA: %.2f\n",s1.name,s1.id,s1.cgpa);

return 0;
}
Output:
Enter student details(name,id,cgpa):amit 2323 9.6
Name: amit
ID: 2323
CGPA:9.60

​ . Application program: Rank-wise sorting of student


8
records:
// Sorting student records
struct student
{
char name[20];
int rollno;
float cgpa;
};

#include <stdio.h>
int main()
{
struct student s[10],temp;
int n,i,j;
printf("How many students?");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("%d: Enter name name,rollno,cgpa:",i+1);
scanf("%s %d %f",s[i].name,&s[i].rollno, &s[i].cgpa);
}

// Sorting records in descending order of cgpa


for(i = 0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(s[j].cgpa < s[j+1].cgpa)

11 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

{
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}

printf("Sorted records are:\n");


for(i=0;i<n;i++)
{
printf("Rank %d:\n",i+1);
printf("%s\n%d\n%.2f\n\n",s[i].name,s[i].rollno, s[i].cgpa);
}

return 0;
}

Sample I/O:
How many students?4
1: Enter name name,rollno,cgpa:
Rahul 100 8.65
2: Enter name name,rollno,cgpa:
Amit 101 7.84
3: Enter name name,rollno,cgpa:
Haris 105 9.43
4: Enter name name,rollno,cgpa:
Lana 110 8.12

Sorted records are:


Rank 1:
Haris 105 9.43

Rank 2:
Rahul 100 8.65

Rank 3:
Lana 110 8.12

Rank 4:
Amit 101 7.84

​9. Operation on Individual members (SLE)


Once we have a structure variable(instance) created, the individual members of that instance can be accessed using
.(dot)operator.

12 (For non-commercial educational use only)


TM’s C Programming Lecture Notes Ver. 1.5 Structures

Now, the combo variablename.member_sname is just like any other independent variable(not member of any
structure) in the program. It can be used in expressions.

E.g:
struct Student
{
char name[50];
int id;
int mark1;
int mark2;
};
struct Student s1 = {"Amit",100,50};

if(s1.id == 100)
s1. mark1+=10; // Using for arithmetic operation

int total = s1. mark1 + s1. Mark2;

We can also apply increment or decrement operations as in


s1.id++;
Or
++s1.id;
Since precedence of member operator(.) is higher than all arithmetic & relational operators, parenthesis is not
required( as in (s1.id)++; )

13 (For non-commercial educational use only)

You might also like