Close
Close

structure level 2

   Varun Singh

Write a structure to store the roll no., name, age (between 11 to 14) and address of students (more than 10). Store the information of the students.
1 - Write a function to print the names of all the students having age 14.
2 - Write another function to print the names of all the students having even roll no.
3 - Write another function to display the details of the student whose roll no is given (i.e. roll no. entered by the user).


Answers

  •   

    You have to define an array of 10 structures to define 10 students by writing struct student stud[10].

    First you have to take input of details from user using a for loop. After that you have to call the three functions by passing the structure name stud along with its size 10 to them.

    The first two functions are easy to understand. For the third function, you must know that the default value of an uninitialized variable in C is garbage value. So, the value of roll number which is not entered by the user is a garbage value.

    Now to find out if the value of a roll number is a garbage value, we have to define a range. Suppose in our case, the roll numbers of the students can be between 1 and 20. So any roll number having value outside this range contains garbage value and is not entered by the user.

    #include <stdio.h>
    struct student
    {
      int roll_no;
      char name[30];
      int age;
      char address[50];
    };
    
    void printFunc1(struct student st[], int size) {  /* first function */
      printf("Students having age = 14\n");
      for(int i=0; i<size; i++) {
      	if(st[i].age == 14) {
      	  printf("%s\n", st[i].name);
      	}
      }
    }
    
    void printFunc2(struct student st[], int size) {  /* second function */
      printf("Students having even roll number\n");
      for(int i=0; i<size; i++) {
      	if((st[i].roll_no)%2 == 0) {
      	  printf("%s\n", st[i].name);
      	}
      }
    }
    
    void printFunc3(struct student st[], int size) {  /* third function */
      printf("Students whose roll number is entered\n");
      for(int i=0; i<size; i++) {
      	if((st[i].roll_no > 0) && (st[i].roll_no <= 20)) {
      	  printf("%s\n", st[i].name);
      	}
      }
    }
    
    int main()
    {
      struct student stud[10];
      for(int i=0; i<10; i++) {    /* taking input of details */
        printf("Student %d\n",i+1);
        printf("Enter roll no. :\n");
        scanf("%d", &stud[i].roll_no);
        printf("Enter name :\n");
        scanf("%s",stud[i].name);
        printf("Enter age :\n");
        scanf("%d", &stud[i].age);
        printf("Enter address :\n");
        scanf("%s",stud[i].address);
      }
      printFunc1(stud, 10);
      printFunc2(stud, 10);
      printFunc3(stud, 10);
      return 0;
    }
    

     



Ask Yours
Post Yours
Write your answer