C C++ program to find sum and average of array elements

Coding in C

#include<stdio.h>
int main()
{
    int num[5],i,sum=0;
    float avg;
    printf("Enter five numbers: ");
    for(i=0;i<5;i++)
    {
        scanf("%d",&num[i]);
    }
    for(i=0;i<5;i++)
    {
        printf("Number = %d\n",num[i]);
        sum=sum+num[i];
    }
    avg=sum/5.0;
    printf("Sum = %d\n",sum);
    printf("Average = %f",avg);
    return 0;
}

Coding in C++

#include<iostream>
using namespace std;
int main()
{
    int num[5],i,sum=0;
    float avg;
    cout<<"Enter five numbers: ";
    for(i=0;i<5;i++)
    {
        cin>>num[i];
    }
    for(i=0;i<5;i++)
    {
        cout<<"Number = "<<num[i]<<endl;
        sum=sum+num[i];
    }
    avg=sum/5.0;
    cout<<"Sum = "<<sum<<endl;
    cout<<"Average = "<<avg;
    return 0;
}

Output

C C++ program to find sum and average of array elements

Published by

admin

I am a computer teacher, programmer and web developer