This blog is under construction

Saturday 29 June 2013

C program for student record using structure

Write a C program to display student details using structures.


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

  struct studentdb {
        char name[100];
        int s1, s2, s3;
        float avg;
        int rollno;
        char grade;
  };

  int main() {
        struct studentdb *s;
        int i, n;

        /* enter the number of students */
        printf("Enter the number of students:");
        scanf("%d", &n);

        /* dynamically allocate memory to store student details */
        s = (struct studentdb *)malloc(sizeof (struct studentdb) * n);

        /* get the student details from the user */
        printf("Enter your inputs:\n");
        for (i = 0; i < n; i++) {
                printf("Input for student %d:\n", i + 1);
                getchar();
                printf("Name:");
                fgets(s[i].name, 100, stdin);
                s[i].name[strlen(s[i].name) - 1] = '\0';
                printf("Marks in Eng, science and Maths:");
                scanf("%d%d%d", &s[i].s1, &s[i].s2, &s[i].s3);
                printf("Rollno:");
                scanf("%d", &s[i].rollno);
        }

        /* print the student details */
        printf("RollNo    Name           s1   s2   s3   Grade  avg\n");
        printf("---------------------------------------------------\n");
        for (i = 0; i < n; i++) {
                printf("%-10d%-15s", s[i].rollno, s[i].name);
                printf("%5d%5d%5d", s[i].s1, s[i].s2, s[i].s3);
                s[i].avg = (float)(s[i].s1 + s[i].s2 + s[i].s3) / 3;
                if (s[i].avg > 80)
                        s[i].grade = 'A';
                else if(s[i].avg > 60)
                        s[i].grade = 'B';
                else
                        s[i].grade = 'C';
                printf("%4c %4.2f\n", s[i].grade, s[i].avg);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of students:3

  Enter your inputs:
  Input for student 1:
  Name:Anand
  Marks in Eng, science and Maths:100 100 100
  Rollno:1

  Input for student 2:
  Name:Adam
  Marks in Eng, science and Maths:100 100 100
  Rollno:2

  Input for student 3:
  Name:Sam
  Marks in Eng, science and Maths:100 100 98
  Rollno:3

RollNo    Name           s1   s2   s3   Grade  avg
---------------------------------------------------
  1         Anand            100  100  100   A 100.00
  2         Adam             100  100  100   A 100.00
  3         Sam               100  100   98   A 99.33



No comments:

Post a Comment