C Program to Store Information of a Student Using Structure

1. Introduction

Structures in C provide a method to group different types of variables under a single name for more efficient storage, manipulation, and readability. In this tutorial, we will demonstrate how to use a structure to store and display the information of a student.

2. Program Overview

1. Define a structure named Student to store the name, roll number, and three subject marks.

2. Declare an instance of the structure.

3. Ask the user to input student details.

4. Display the entered details.

3. Code Program

#include <stdio.h>
#include <string.h>

// Defining the structure
struct Student {
    char name[50];
    int roll_no;
    float marks1, marks2, marks3;

int main() {
    // Declare an instance of the structure
    struct Student s;

    // Input student details
    printf("Enter student's name: ");
    fgets(s.name, sizeof(s.name), stdin);
    s.name[strcspn(s.name, "\n")] = 0;  // Remove newline character

    printf("Enter roll number: ");
    scanf("%d", &s.roll_no);

    printf("Enter marks for subject 1: ");
    scanf("%f", &s.marks1);

    printf("Enter marks for subject 2: ");
    scanf("%f", &s.marks2);

    printf("Enter marks for subject 3: ");
    scanf("%f", &s.marks3);

    // Display student details
    printf("\nStudent Details:\n");
    printf("Name: %s\n", s.name);
    printf("Roll Number: %d\n", s.roll_no);
    printf("Marks for Subject 1: %.2f\n", s.marks1);
    printf("Marks for Subject 2: %.2f\n", s.marks2);
    printf("Marks for Subject 3: %.2f\n", s.marks3);

    return 0;


Enter student's name: Ramesh Fadatare
Enter roll number: 23
Enter marks for subject 1: 78.5
Enter marks for subject 2: 89.6
Enter marks for subject 3: 92.5

Student Details:
Name: Ramesh Fadatare
Roll Number: 23
Marks for Subject 1: 78.50
Marks for Subject 2: 89.60
Marks for Subject 3: 92.50

4. Step By Step Explanation

1. A struct named Student is defined which contains a string name to store the student's name, an integer roll_no to store the student's roll number, and three floating-point numbers marks1, marks2, and marks3 to store marks for three subjects.

2. Inside the main() function, an instance of the Student struct named s is declared.

3. The user is prompted to enter the student's name, roll number, and marks for three subjects, which are stored in the s instance.

4. A string function strcspn is used to remove the newline character from the name that fgets adds.

5. The entered details are then displayed using the printf function.

Note: It's important to handle the newline character when using fgets after scanf to ensure proper input reading.