Professional Documents
Culture Documents
02
C Language
LECTURE 39
04
Today’s Agenda
01 Structure
02
Some Example
Structure
o we have to take a student's name, age, and percentage in our program and display
it back on the screen using the knowledge we have gained till now
Solution to the above given problem
int main()
{
int roll;
char grade;
float per;
printf("Enter roll: ");
scanf("%d", &roll); Now, suppose we take the same
fflush(stdin); details for 5 student's what will
printf("Enter grade: "); be the solution now
scanf("%c", &grade);
printf("Enter Percentage: ");
scanf("%f", &per);
printf("Roll: %d\n", roll);
printf("Grade: %c\n", grade);
printf("Percentage: %f\n", per);
return 0;
}
Solution to the above given problem
#include <stdio.h> for(i = 0; i < 5; i++)
int main() {
{ printf("Roll: %d\n", roll[i]);
int roll[5], i; printf("Grade: %c\n", grade[i]);
char grade[5]; printf("Percentage: %f\n", per[i]);
float per[5]; }
for(i = 0; i < 5; i++) return 0;
{ }
printf("Enter roll: ");
scanf("%d", &roll[i]);
fflush(stdin);
printf("Enter grade: ");
scanf("%c", &grade[i]);
printf("Enter Percentage: ");
scanf("%f", &per[i]);
}
Can we take the details in a single array?
No, Because the array is a collection of similar kinds of data types stored at a continuous
memory location
Thankfully C language provides us the concept of Structure using which we can take a
single array to manage the details of 5 different students
Structure
A Structure is also a collection of dissimilar kinds of data elements stored at
continuous memory locations
int main()
{
struct Student s;
roll = 10; Error
return 0;
}
Using a Structure
struct Student Tag
7 Bytes
{ or
Declaration int roll; Name
or char grade; s ? 10 ? ‘A’ ? 76.5
Members
Template float per;
roll grade per
};
int main() Name
Output
{
struct Student s;
s.roll = 10; Structure Roll: 10, Grade: A, Percentage: 76.500000
Data Type s.grade = 'A'; Variable
Name s.per = 76.5f;
printf("Roll: %d, Grade: %c, Percentage: %f\n", s.roll, s.grade, s.per);
return 0;
}
Three Important Points to Remember:
1. We can never initialize members of a structure inside the declaration block of the
structure.
struct Student
{
Reason:
int roll = 10;
char grade = 'A'; Error
roll, grade, and per will be stored in
float per = 76.5f;
memory when the line
};
"struct student" is executed
Three Important Points to Remember:
2. After declaring the template of the structure we must terminate it with a semicolon.
Otherwise, the compiler will generate a SYNTAX ERROR.
struct Student
{
int roll; Because we are declaring Structure
char grade; that's why they are necessary and
float per; the part of Syntax and always
}; remember declaration always
terminated by ";" in C language
Three Important Points to Remember:
3. The keyword struct must compulsorily be used whenever we write the tag/name of
the structure in our program. Otherwise, the compiler will give the error.
Student s; Error
Thank you