Monday 2 June 2014

0

C Program 9: To Calculate Sum And Average of Array

  • Monday 2 June 2014
  • IndianBooktuber
  • Share
  • Aim: to calculate the sum and average of an array
    Theory: We will ask the user to input the values into the array and then we would find out the sum and average.
    Following is the code:
    #include<stdio.h>
    #include<conio.h>
    void main()
    {
        int arr[5], sum= 0, i=0, j;
        float avg;
        printf("enter the values into the array: ");
        scanf("%d%d%d%d%d%d", &arr[0], &arr[1], &arr[2], &arr[3], &arr[4], &arr[5], &arr[6]);
        printf("The Values you entered are: ");
        for (j=0; j<=5; j++)
        {
            printf("%d\n", arr[j]);
        }
        //finding the sum
        while (i<=5)
        {
              sum = sum + arr[i];
              i++;
        }
        printf("The sum is of the array is: %d \n", sum);
        //finding average
        avg= sum/5;
        printf("The average of the array is: %f", avg);
        getch();
        

    }

    First, as already mentioned, we would ask the user to input the values into array. One should prefer to use a for loop for the same purpose. However, I have stuck to the very basic form of inputting values into array. Then we will use for loop to print the values entered by the user.
    Now, we will find the sum. This is also possible using for loop but we can accomplish this with while loop as well. We can find the sum using this statement sum = sum + arr[i]; 
    Once we find the sum, we will display the output. Then we will apply formula for finding the average of an array which is very simple avg = sum/5
    This way we will get the following output:

    This is a very basic program using arrays. In case, you have any doubts, contact me. 

    0 Responses to “C Program 9: To Calculate Sum And Average of Array”

    Post a Comment

    Subscribe