Code Snippets C/C++ Code Snippets

C++ - program for Array of Structure.

By: IncludeHelp, On 30 SEP 2016

In this example we will learn about Array of Structures.

What is Array of Structures?

As we know "Array is the collection of variables of similar data types" same as "Array of Structures is the collection of structure variables".

When we declare an array of structure variables it is called Array of Structures.

In this example there is a structure named student with two variables name and rollNumber, we will read number of students.

We will declare array of structure with MAX number of students, here MAX is defined as 100; hence in this program we can read maximum 100 records.

Declaration of Array of Structure

By following this syntax, we can declare an array of structure

struct structure_name structure_variable[<MAX>];

for example, if you have a structure named student and want to declare 10 structure variables, syntax will be like this

struct student std[10];

here, std is array of structure variable.

Let’s consider the following example with output.

C++ program - Demonstrate Example of Array of Structures

/*C++ - program for Array of Structure.*/

#include <iostream>
#include <iomanip>

using namespace std;

#define MAX 100
struct student{
	char name[30];
	int rollNumber;
};

int main(){
	struct student std[MAX];
	int n,loop;

	cout<<"Enter total number of students: ";
	cin>>n;

	for(loop=0; loop<n; loop++){
		cout<<"Enter name:";
		cin.ignore(1);
		cin.getline(std[loop].name,30);
		cout<<"Enter roll number:";
		cin>>std[loop].rollNumber;
	}

	cout<<"Entered records are:"<<endl;
	cout<<setw(30)<<"Name"<<setw(20)<<"Roll Number"<<endl;

	for(loop=0; loop<n; loop++){
		cout<<setw(30)<<std[loop].name<<setw(10)<<std[loop].rollNumber<<endl;
	}
	
	return 0;
}
Enter total number of students: 2
Enter name:Mike
Enter roll number:101
Enter name:Monty            
Enter roll number:102
Entered records are:
                     Name         Roll Number
                          Mike       101
                         Monty       102   



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