C Programming and Data Structures: Unit II: C Programming – Advanced Features

Structures

Definition, Syntax, Initializing, Example C programs

Definition: A structure is a group of items in which each item is defined by some identifier. These items are called members of the structure. Thus structure is a collection of various data items which can be of different data types.

Structures

AU May-17, Dec.-18,19, Marks 16

 

1. Definition

Definition: A structure is a group of items in which each item is defined by some identifier. These items are called members of the structure. Thus structure is a collection of various data items which can be of different data types.

The Syntax of declaring structure in C is as follows -

struct name {

member 1;

member 2;

member n;

};


Example :

struct stud {

int roll_no;

char name[10];

float marks;

};

struct stud stud1,stud2;

Using typedef

An alternative to using a structure tag is to use the structure tag is to use the typed definition in C. For example

typedef struct {

int roll_no;

char name[10];

float marks;

} stud;

The word stud represents the complete structure now. So whenever the word stud will appear there ever you can assume the complete structure. The stud will act like a data type which will represent the above mentioned structure. So we can declare the various structure variables using the tag stud like this-

stud stud1,stud2;

 

2. Comparison between Arrays and Structures


 

3. Initializing Structure

There are three different ways by which structure can be defined.

First Way Writing structure variable after structure template

struct student {

int roll_no;

char name[10];

float marks;

}s1;

Second Way: Declare structure variable using struct keyword

struct student {

int roll_no;

char name[10];

float marks;

};

struct student s1;

Third Way: Declaring structure variables using typedef

typedef struct student {

int roll_no;

char name[10];

float marks;

}S;

S, s1;

 

Ex. 2.1.1 Write a C program to initialize a structure and retrieve the values.

Sol. :

 /***********************************************

This Program is for assigning the values to the structure variable. Also for retrieving the values.

**************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct student {

int roll_no;

char name[10];

float marks;


void main(void)

{

clrscr();

printf("\n Enter the roll number");


printf("\n Enter the name ");

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

printf("\n Enter the marks");

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

printf("\n The record of the student is");

printf("\n\n Roll_no Name Marks");

printf("\n-------");


Enter the roll number 1

Enter the name Shrinath

Enter the marks 91.44

The record of the student is

Roll_ no     Name    Marks

1               Shrinath   91.44

 

Ex. 2.1.2 Write a C program to represent a complex number using structure and add two complex numbers.

Sol.:

#include<stdio.h>

#include<conio.h>

typedef struct Complex

{

float real;

float img;

}C;

void main()

{

C x,y,z;

clrscr();

printf("\n Enter the real part of first complex number");

scanf("%f",&x.real);

printf("\n Enter the imaginary part of first complex number");

toute lebegy

scanf("%f",&x.img);

printf("\n Enter the real part of second complex number");

scanf("%f",&y.real);

printf("\n Enter the imaginary part of second complex number");

scanf("%f",&y.img);

printf("\n\t The First complex number is %3.2f+ %3.2fi",x.real,x.img);

printf("\n\t The second complex number is %3.2f+%.2fi",y.real,y.img);

z.real=x.real+ y.real;

z.img=x.img+ y.img;

printf("\n The Addition is %3.2f+%3.2fi\n",z.real,z.img);

getch( );

}

 

4.  Array of Structures

Definition: Structure is used to store information of one particular object and if one has to store large number of such objects then array of structure is used.

For example - If there are 10 students in a class then the record of each student is in structure and 10 such records can be stored in array of structure.


Let us see a sample 'C' program for array of structure.

The program is for storing the record of all the students in a particular class.

/*************************************

Program for maintaining the students' database using structure. The program shows the use of typedef for a structure variable

************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

 

typedef struct student {

int roll_no;

char name[20];

int marks;

} stud;


}

printf("\n Each student's record is");

printf("\n------------");

printf("\n roll_no name marks");

printf("\n-------------");

for(i=0;i<n;i++){

printf("\n%d %s %d",s[i].roll_no,s[i].name,s[i].marks);}

printf("\n--------------“);

getch( );

}

Output

Enter the total number of students 5

Enter Each student's record


 

Ex. 2.1.3 Database of 100 students is required to be stored. Each student record contains fields such as roll no, name of student, total marks. Write a program in 'C' to input the database of 100 students with fields mentioned above using:

i) Array ii) Array of structures.

Display record of student who scores maximum marks.

Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct student

{

Int roll_no

char sname[20];

int Total_Marks;

}s[100];

int r[100],m[100];

char n[100][20];

void main( )

{

int i,j,choice;

clrscr( );

printf("\n 1. Array \n 2.Array of structure ");

printf("\n Enter your choice: ");

scanf("%d", &choice);

switch(choice)

{

case 1:for(i=0;i< 100;i++)

{

printf("\n Enter Roll No.: ");

scanf("%d", &r[i]);

printf("\n Enter name of student: ");

scanf("%s",n[i]);

printf("\n Enter Marks: ");

scanf("%d",&m[i]);

}

j=0;

for(i=0;i<100;i++)

{

if(m[i]>m[j])/*data with maximum mark is

obtained*/

j=i;/*mark that record by index j*/

}

printf("\n Student with maximum marks is...");

printf("\n Roll. No.\t Name \t Total Marks ");

printf("\n %d %s %d",r[j],n[j],m[j]);

break;

case 2:for(i=0; i< 100;i++)

{

printf("\nEnter Roll No: ");

scanf("%d", &s[i].roll no);

printf("\nEnter name of student: ");

scanf("%s",s[i].sname);

printf("\nEnter marks: ");

scanf("%d", &s[i].Total_Marks);

}

j=0;

{

for(i=0;i<100;i++)

{

if(s[i].Total Marks>s[j].Total_Marks)

{

j=i;

}

}

printf("\n Student with maximum marks is...");

printf("\n Roll.No.\t Name \t Total Marks ");

printf("\n %d %S %d",s[j].roll_no,s[j].sname,s[j].Total_Marks);

break;

}

}

 

Ex. 2.1.4 Write down only declaration in 'C' for : A database of 100 students each with information as roll no, name, address and marks using: i) Only arrays ii) Array of structures.

Sol. : i) Only arrays:

int roll no [100];

char name [100] [100];

char address [100] [30];

float marks [100];

ii) Array of structures :

struct student

{

int roll no;

char name [20];

char address [50];

float marks;

}s[100];

 

Ex. 2.1.5 Develop a structure to represent planet in the solar system. Each planet has fields for the planet's name, its distance from the sun in miles and the number of moons it has. Write a program to read the data for each planet and store. Also print the name of the planet that has less distance from the sun.

Sol.

Following table shows planets in the solar system, their distances from sun in miles and number of moons.


C Program

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct SolarSystem {

char name[20];

int distance;

int no_of_moons;

}Solar;

Solar Planet[10];

void main(void)

{

int n, i, min dist, position;

//clrscr( );

n = 9;//number of planets

printf("\n Enter Each Planet's record"); for (i = 0; i<n; i++)

{

printf("\n Enter Name of the Planet");

scanf("%s", Planet[i].name);

printf("\n Enter Distance of Planet from sun(in million miles)");

scanf("%d", &Planet[i].distance);

printf("\n Enter Number of Moons");

scanf("%d", &Planet[i].no_of_moons);

}

printf("\n Each student's record is");

printf("\n----------");

printf("\n Name Distance No_Of_Moons");

printf("\n----------------");

for (i=0; i<n; i++)

{

printf("\n%s\t%d\t%d", Planet[i].name, Planet[i].distance, Planet[i].no_of_moons);

}

printf("\n-----");

min_dist Planet[0].distance;

position = 0;//finding the minimum distant planet from Sun

for (i = 0; i < n;i++)

{

if (min_dist > Planet[i].distance)

{

min_dist position = Planet[i].distance;

position = i

}

}

printf("\n The planet having less distance from the Sun is %s", Planet [position].name);

}

Output

Enter Each Planet's record

Enter Name of the Planet Mercury

Enter Distance of Planet from sun(in million miles)36

Enter Number of Moons 0

Enter Name of the Planet Venus

Enter Distance of Planet from sun(in million miles)67

Enter Number of Moons 0

Enter Name of the Planet Earth

Enter Distance of Planet from sun(in million miles)93

Enter Number of Moons 1

Enter Name of the Planet Mars

Enter Distance of Planet from sun(in million miles) 142

Enter Number of Moons 2

Enter Name of the Planet Jupiter

Enter Distance of Planet from sun(in million miles)483

Enter Number of Moons 62

Enter Name of the Planet Saturn

Enter Distance of Planet from sun(in million miles)888

Enter Number of Moons 53

Enter Name of the Planet Uranus

Enter Distance of Planet from sun(in million miles)1784

Enter Number of Moons 21

Enter Name of the Planet Neptune

Enter Distance of Planet from sun(in million miles)2794

Enter Number of Moons 13

Enter Name of the Planet Pluto

Enter Distance of Planet from sun(in million miles)2647

Enter Number of Moons 3

Each student's record is


The planet having less distance from the Sun is Mercury

 

Ex. 2.1.6 Define a structure to store details of 10 bank customers with customer name,account no, balance, and city. Write a C program to store the details of customers in the bank, access and print the customer details for a specified account no.

Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct Customer {

int account _ no;

char name[20];

int balance;

char city[20];

}cust;

cust c[10];

int main( )

{

int n,i;

printf("\n Enter the total number of Customers");

scanf("%d", &n);

printf("\n Enter Each customer's record");

printf("\n Acc_no  Name   Balance City\n");

for(i=0;i<n;i++)

{

scanf("%d", &c[i].account_no);

scanf("%s",c[i].name);

scanf("%d", &c[i].balance);

scanf("%s",c[i].city);

}

printf("\n Each record is");

printf("\n--------");

printf("\n Acc_no Name Balance City");

printf("\n-------------");

for(i=0;i<n;i++)

{

printf("\n %d\t%s \t%d \t       %s",c[i].account_no,c[i].name,c[i].balance,

c[i].city);

}

return 0;

}

Output

Enter the total number of Customers 2

Enter Each customer's record


 

Ex. 2.1.7: Write a C program to get 10 student details using structures from the user and display these details on the screen.

AU: Dec.-18, Marks 6

Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct Student {

int roll_no;

char name[20];

int std;

char address [20];

}cust;

cust c[10];

int main()

{

int i;

printf("\n Enter Each student's record");

printf("\n Roll_no  Name   Std Address\n”);

for(i=0;i<10;i++)

{

scanf("%d",&c[i].roll_no);

scanf("%s",c[i].name);

scanf("%d", &c[i].std);

scanf("%s",c[i].address);

}

printf("\n Each record is");

printf("\n---------------“)

printf("\n Roll_no Name Std Address");

printf("\n-------");

for(i=0;i<10;i++)

{

printf("\n %d\t%s \t%d \t %s",c[i].roll_no,c[i].name,c[i].std,c[i].address);

}

return 0;

}

 

Ex. 2.1.8: Explain structures and write a C program using structures to store roll_num, name, marks in 10 subjects of 100 students. Calculate the grade of each student and print the student information. The grades are calculated as follows -


Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct student

{

int roll_no;

char sname[20];

int Marks[10];

char *grade;

}s[100];

void main( )

{

int i,j;

for(i=0; i<100;i++)

{

printf("\nEnter Roll No: ");

scanf("%d", &s[i].roll_no);

printf("\nEnter name of student: ");

scanf("%s",s[i].sname);

for(j=0;j<10;j++)

{

printf("\nEnter marks: ");

scanf("%d", &s[i].Marks[j]);

}

for(j=0;j<10;j++)

}

int total_marks = 0;

total_marks = total_marks+s[i].Marks [j];

if(total_marks>91 && total_marks <=100)

s[i].grade = "O";

else if(total_marks>81 && total_marks <=90)

s[i].grade = "A+";

else if(total_marks>71 && total_marks < = 80)

s[i].grade ="A";

else if(total_marks>61 && total_marks <=70)

s[i].grade = "B+";

else if(total_marks>50 && total_marks < = 60)

s[i].grade = "B";

else

s[i].grade = "RA";

}

}

printf("\n Roll.No.\tName\tGrade ");

for(i-0;i<100;i++)

{

printf("\n %d\t%s\t%s",s[i].roll_no,s[i].sname,s[i].grade);

}

}

 

5. Structure within a Structure

When a structure is declared in a structure then it is called as nested structure.

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct bdate {

int day;

int month;

int year;

}dt;

struct address {

char street[10];

char city[10];

}add;

struct student {

int roll_no;

char name[10];

struct bdate dt;

struct address add;

} std;

void main(void)

{

clrscr();

printf("\n Enter the student's data");

printf("\n Enter student's rollnumber");

scanf("%d", &std.roll_no);

printf("\n Enter student's name");

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

printf("\n Enter student's Birth date(mm-dd-yy))";

scanf("%d %d %d", &std.dt.month, &std.dt.day,&std.dt.year);

printf("\n Enter student's Address");

scanf("%s %s",std.add.street,std.add.city);

printf("\n\n You have entered ");

printf("\n roll_no name B'date address");

printf("\n----------");

printf("\n %d %s",std.roll_no,std.name);

printf("%d-%d-%d ",std.dt.month,std.dt.day,std.dt.year);


}

 

Ex. 2.1.9 Write a C program with appropriate structure definition and variable declaration to store information about an employee, using nested structures. Consider the following fields like ENAME, EMPID, DOJ(Date, Month, Year) and Salary (Basic, DA, HRA)

Sol. :

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

struct JoiningDate

{

int Date;

int Month;

int Year;

};

struct Amount

{

float Basic;

float DA;

float HRA;

};

struct Employee {

char ENAME [20];

int EMPID;

struct JoiningDate DOJ;

struct Amount Salary;

}Emp;

void main(void)

{

printf("\n Enter Name of Employee: ");

scanf("%s",Emp.ENAME);

printf("\n Enter Employee ID: ");

scanf("%d", &Emp.EMPID);

printf("\n Enter Date of Joining of Employee: ");

printf("\n Enter Date: ");

scanf("%d", &Emp.DOJ.Date);

printf("\n Enter Month: ");

scanf("%d", &Emp.DOJ.Month);

printf("\n Enter Year: ");

scanf("%d", &Emp.DOJ.Year);

printf("\n Enter Salary of Employee: ");

printf("\n Enter Basic: ");

scanf("%f",&Emp.Salary.Basic);

printf("\n Enter DA: ");

scanf("%f",&Emp.Salary.DA);

printf("\n Enter HRA: ");

scanf("%f",&Emp.Salary.HRA);

printf("\n Displaying the Employee Record...");

printf("\n Employee Name: %s",Emp.ENAME);

printf("\n Employee ID: %d", Emp.EMPID);

printf("\n Date of Joining (dd-mm-yyyy): %d-%d-%d",

Emp.DOJ.Date,Emp.DOJ.Month, Emp.DOJ.Year);

printf("\n Salary of Employee: %f(Basic) %f(DA)% f(HRA)",

Emp.Salary.Basic,Emp.Salary. DA,Emp.Salary.HRA);

}

Output

Enter Name of Employee: Anuradha

Enter Employee ID: 101

 

Enter Date of Joining of Employee:

Enter Date: 10

 

Enter Month: 10

 

Enter Year: 2012

 

Enter Salary of Employee:

Enter Basic: 10000

 

Enter DA: 5000

 

Enter HRA: 1000

 

Displaying the Employee Record...

Employee Name: Anuradha

Employee ID: 101

Date of Joining (dd-mm-yyyy): 10-10-2012

Salary of Employee: 10000.000000 (Basic)5000.000000(DA)

1000.000000(HRA)

 

6. Structure and Function

There are two simple ways by which the structure can communicate to the function

1. One can pass the member of the function like an ordinary variable to the function.

/*******************************************************

Program For passing the structure member as a parameter to the function

********************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct stud

{

int roll_no;

char name[20];

float marks;

}student;

student st;

void print_rec(int,char[ ],float);

void main( )

{

char ans;

clrscr( );

do

{

clrscr( );

printf("\n\t Enter The Record");

printf("\nEnter The roll Number");

scanf("%d", &st.roll_no);

printf("\nEnter The Name");

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

printf("\nEnter The marks");

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

print_rec(st.roll_no,st.name, st.marks);

printf("\n Do you Want To store more record?");

ans=getche();

}while(ans= ='y');

}

/**********************************************

This function is for printing the values assigned to structure members

Input :structure members

Output:nones

Called By:main

***********************************************/

void print_rec(int r,char n[],float m)

{

printf("\n You Have Entered Following Record");

printf("\n %d %S %f",r,n,m);

}

Output

Enter The Record

Enter The roll Number 1

Enter The Name aaa

Enter The marks 76

You Have Entered Following Record

1 aaa 76.000000

Do you Want To store more record?

 

2. The entire structure can be passed to the function.

/***********************************************

Program For passing the structure as a parameter to the function

************************************************/

#include<stdio.h>

#include<conio.h>

#include<stdlib.h>

typedef struct stud

{

int roll_no;

char name[20];

float marks;

}student;

student st;

// Passing entire structure to function

void print_rec(student st);

void main( )

{

char ans;

clrscr( );

do

{

clrscr( );

printf("\n\t Enter The Record");

printf("\nEnter The roll Number");

scanf("%d", &st.roll_no);

printf("\nEnter The Name");

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

printf("\nEnter The marks");

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

print_rec(st);

printf("\n Do you Want To store more record?");

ans=getche();

}while(ans= ='y');

}

/***************************************************

This function is for printing the values assigned to structure members

Input :structure student

Output:none

Called By:main

***************************************************/

void print_rec(student st)

{

printf("\n You Have Entered Following Record");

printf("\n %d %s %f",st.roll_no,st.name,st.marks);

}

Output

Enter The Record

Enter The roll Number 1

Enter The Name aaa

Enter The marks 76

You Have Entered Following Record

1 aaa 76.000000

Do you Want To store more record?

 

C Programming and Data Structures: Unit II: C Programming – Advanced Features : Tag: : Definition, Syntax, Initializing, Example C programs - Structures