Contact Learn C
Copy Program Share Program

Program 102:To find Average of Class

Program 102:
#include<stdio.h>
main()
{
    int i,j,sum=0,num;
    float avg;
    printf("Enter number of students in class\n");
    scanf("%d",&num);
    int marks[num];
    printf("Enter marks of all students\n");
    for(i=0;i<num;i++)
    {
        scanf("%d",&marks[i]);
        sum+=marks[i];
    }
    avg=(float)sum/num;
    printf("Average of class is %f\n",avg);
}
Explanation:
  1. This program starts with initializing :
    • sum → To store sum of marks
    • i,j →Used as helping variable
    • avg→ To store average of marks.
    • num → To store number of students
  2. printf("Enter number of students in class\n");
        scanf("%d",&num);
    Taking input from user 
  3. for(i=0;i<num;i++)
        {
            scanf("%d",&marks[i]);
            sum+=marks[i];
        }
    The loop will traverse from 0 to number of students in class.Each time you enter marks of a student that will be added to previous value of sum and stored in sum.For example: lets take num=2
    • When i=0,0<2 which is true so then it waits for us to enter number (say 98 is the number we entered).Then as sum=0 by default sum=sum+98=0+98=98.So, sum=98 .Then 'i' is incremented by 1.Now i=1.
    • When i=1,1<2 which is true so then it waits for us to enter number (say 56 is the number we entered).Then as sum=98 from previous run sum=sum+56=98+56=98.So, sum=154.Now i will become 2
    • As i=2 and 2<2 is falseso loop terminated and our final value of sum is 154
  4.  avg=(float)sum/num;
    Finally As we took num=2 which means 2 students in class and got sum as 154 .So avg=154/2=77
  5. Average of 2 students is 77 .This how the program is executed.

 Output:

To find Average of Class

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide