C Structures and Pointers

Write a C program to store and print student details using a structure

Description: Take the roll number, name and marks of a student as input. Store them in a structure and print them.

Hint:

  • Make a structure with an int, a char array and a float. Use the dot operator to reach its members.

C program to store student details in a structure

#include <stdio.h>

struct Student {
    int roll;
    char name[30];
    float marks;
};

int main(void) {
    struct Student s;

    printf("Enter roll number, name and marks: ");
    scanf("%d", &s.roll);
    scanf("%29s", s.name);
    scanf("%f", &s.marks);

    printf("Roll: %d\n", s.roll);
    printf("Name: %s\n", s.name);
    printf("Marks: %.1f\n", s.marks);
    return 0;
}

Output:

Output of the above program is

Enter roll number, name and marks: 1
Robin
85.5
Roll: 1
Name: Robin
Marks: 85.5

How it works

  • The structure keeps three different types of data in one variable.
  • %29s limits the name to 29 characters, so it cannot go outside the array.

Read C Structures.