Thursday, 13 April 2023

What is structure? Write a C program to input roll , name and age of 5 students and display them properly using structure.

What is structure? Write a C program to input roll , name and age of 5 students and display them properly using structure.

    Answer : Structure in C is a composite data type that allows you to group variables of different data types under a single name. It is used to create user-defined data types that can hold multiple values of different types.

 

Here's an example C program that uses a structure to input and display the roll, name, and age of 5 students:

#include <stdio.h>

// Define the structure for student information

struct Student

{

    int roll;

    char name[50];

    int age;

};

 

int main()

{

    // Declare an array of struct Student to hold information for 5 students

    struct Student students[5];

    // Input student information

    printf("Enter information for 5 students:\n");

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

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

        printf("Roll: ");

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

        printf("Name: ");

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

        printf("Age: ");

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

        printf("\n");

    }

    // Display student information

    printf("Student Information:\n");

    for (int i = 0; i < 5; i++)

{

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

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

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

        printf("Age: %d\n", students[i].age);

        printf("\n");

    }

 

    return 0;

}

 

In this program, a structure called Student is defined with three members: roll (integer), name (character array), and age (integer). An array of Student structs called students is declared to hold information for 5 students. The program uses a for loop to input student information and another for loop to display the information. The . operator is used to access the members of the struct for input and output.

No comments:

Post a Comment

MCQ Question Bank Microsoft PowerPoint