Code Snippets C/C++ Code Snippets

C Nested Structure Exercise - Read and print class details with multiple students records.

By: IncludeHelp, On 18 OCT 2016


In this program we will learn how to read and print class detains with multiple students records in c programming language?

In this example there are two structures student and class, in student structure there are two members to read roll number and name of the student. In class structure there are two members to read class name and student structure.

Inside class structure we are declaring maximum array of structure of student structure with maximum of 100 records.

In program we will read total number of students and read according to entered number of students records.

C program (Code Snippet) - Nested Structure Exercise

Let’s consider the following example:

/*C Nested Structure Exercise - 
Read and print class details with multiple 
students records*/

#include <stdio.h>

//student structure declaration
struct student{
	char name[50];
	int roll;
};

//class structure declaration
struct class{
	char className[50];
	struct student std[100]; //maximum
};

int main(){
	int i,n;
	char temp;
	struct class cls;
	
	printf("Enter class name: ");
	fgets(cls.className, 50, stdin);
	
	
	printf("Enter total number of students in a class: ");
	scanf("%d",&n);
	
	for(i=0;i<n;i++){
		printf("Enter student [%d] roll no.: ",i+1);
		scanf("%d",&cls.std[i].roll);
		printf("Enter student [%d] name: ",i+1);
		scanf("%c",&temp); //read last CR (new line) character and ignore
		fgets(cls.std[i].name,50,stdin);
		
	}
	
	//print details
	printf("\nDetails are:\n");
	printf("CLASS NAME: %s\n",cls.className);
	for(i=0;i<n;i++)
		printf("student[%d]: %05d\t%s\n",i+1,cls.std[i].roll,cls.std[i].name);

	return 0;
	
}

Output

    Enter class name: High School 
    Enter total number of students in a class: 3
    Enter student [1] roll no.: 101 
    Enter student [1] name: Alvin Thomas
    Enter student [2] roll no.: 102 
    Enter student [2] name: Mike Thomas 
    Enter student [3] roll no.: 103 
    Enter student [3] name: Princy

    Details are:
    CLASS NAME: High School 

    student[1]: 00101 	Alvin Thomas

    student[2]: 00102 	Mike Thomas 

    student[3]: 00103 	Princy




Copyright © 2024 www.includehelp.com. All rights reserved.