Structures Session 2
Structures Session 2
STRUCTURES
Definition, Declaration, accessing structures, initialization, operations on structures, structures containing
arrays, structures containing pointers, nested structures, self-referential structures, arrays of structures,
structures and functions, structures and pointers.
Sample Program:
Define a structure for student which include roll number ,name,age and marks . Write a program to
read and display the information of 3 students.
#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
{
//assigning values to structure variable s1 using initialization
s2.rno=5;
s2.marks=90;
s2.age=18;
strcpy(s2.name,"Ram ");
Output :
enter rno,name,marks,age of student:1
Raju
92
18
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18
Details of student 2:
roll number: 5
name :Ram
marks :90
age: 18
Details of student 3:
roll number: 1
name :Raju
marks :92
age: 18
#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
{
//assigning values to structure variable s1 using initalization struct student
s1={2,"Gandhi",89,18};
struct student s2; s2=s1;
printf("\nDetails of student 1:\n");
printf("\n roll number: %d",s1.rno);
printf("\n name :%s",s1.name);
printf("\n marks: %d",s1.marks);
printf("\n age: %d",s1.age);
printf("\n\n");
printf("Details of student 2:\n");
printf("\n roll number: %d",s2.rno);
printf("\n name :%s",s2.name);
printf("\n marks: %d",s2.marks);
printf("\n age: %d",s2.age);
}
output:
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18
Details of student 2:
roll number: 2
name :Gandhi
marks :89
age: 18
#include<stdio.h>
#include<string.h>
struct student
{
m=((s1.rno==s2.rno)&&(s1.marks==s2.marks))?1:0;
if(m==1)
printf("\n both the details are same");
else
printf("\n both the details are not same");
}
Output:
Details of student 1:
roll number: 2
name :Gandhi
marks :89
age: 18
Details of student 2:
roll number: 2
name :Gandhi
marks :89
age: 18
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
struct struct-name obj;
Example for array within structure
#include<stdio.h>
struct Student
{
int Roll;
char Name[10];
int Marks[3]; //array of marks
int Total;
float Avg;
};
void main()
{
int i;
struct Student S;
printf("\n\nEnter Student Roll : ");
scanf("%d",&S.Roll);
printf("\n\nEnter Student Name : ");
scanf("%s",&S.Name);
S.Total = 0;
for(i=0;i<3;i++)
{
printf("\n\nEnter Marks %d : ",i+1);
scanf("%d",&S.Marks[i]);
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3;
printf("\nRoll : %d",S.Roll); printf("\nName
: %s",S.Name); printf("\nTotal :
%d",S.Total); printf("\nAverage :
%f",S.Avg);
}
Output :