Problem Solving Through C (BCA) 1st Sem Previous Year Solved Question Paper 2022

Practice Mode:
15.

How to use array of structures ? Explain with the help of an example code.

Explanation

Arrays of structures are a powerful way to organize and work with multiple instances of a structure in C. Each element in the array is a structure, and you can access individual structure members using array indexing. Here's an example to illustrate the use of arrays of structures:

#include <stdio.h>


// Define a structure to represent a student

struct Student {

char name[50];

int rollNumber;

float marks;

};


int main() {

// Declare an array of structures

struct Student students[3];


 // Input data into the array of structures

for (int i = 0; i < 3; i++) {

printf("Enter student %d's name: ", i + 1);

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

printf("Enter student %d's roll number: ", i + 1);

scanf("%d", &students[i].rollNumber);

printf("Enter student %d's marks: ", i + 1);

scanf("%f", &students[i].marks);

}


 // Display the student data

printf("\nStudent Information:\n");

for (int i = 0; i < 3; i++) {

printf("Student %d:\n", i + 1);

printf("Name: %s\n", students[i].name);

printf("Roll Number: %d\n", students[i].rollNumber);

printf("Marks: %.2f\n", students[i].marks);

}

 return 0;

}

In this example:

  1. We define a structure called Student to represent student information, which includes name, rollNumber, and marks.

  2. We declare an array of structures named students, which can hold data for multiple students.

  3. We use a for loop to input data for three students into the array of structures.

  4. We then use another for loop to display the information for each student in the array.

Using arrays of structures allows you to manage and process data for multiple entities of the same type efficiently. In this example, we manage data for three students, but you can extend it to handle more students or other entities as needed.