In the following example, we will find the average of numbers between 1 and 10 using for loop.

Example

C++ Compiler

#include<iostream>#include<cmath>using namespace std;
int main()
{
int start =1;
int end =10;
int total =0;
int count = (end - start) +1;
float average =0;
cout <<"Average of numbers between "<< start <<" and "<< end <<":\n";
for(start=start; start<=end; start++)
total += start;
cout <<"\nTotal = "<< total;
cout <<"\nCount = "<< count;
average = (float) total / count;
cout <<"\nAverage is "<< average;
return0;
}

Output

Average of numbers between 1 and 10:
Total = 55
Count = 10
Average is 5.5

Using while loop

In the following example, we will find the average of numbers between 1 and 10 using while loop.

Example

C++ Compiler

#include<iostream>#include<cmath>using namespace std;
int main()
{
int start =1;
int end =10;
int total =0;
int count = (end - start) +1;
float average =0;
cout <<"Average of numbers between "<< start <<" and "<< end <<":\n";
while(start <= end)
{
total += start;
start++;
}
cout <<"\nTotal = "<< total;
cout <<"\nCount = "<< count;
average = (float) total / count;
cout <<"\nAverage is "<< average;
return0;
}

Output

Average of numbers between 1 and 10:
Total = 55
Count = 10
Average is 5.5

Using do while loop

In the following example, we will find the average of numbers between 1 and 10 using do while loop.

Example

C++ Compiler

#include<iostream>#include<cmath>using namespace std;
int main()
{
int start =1;
int end =10;
int total =0;
int count = (end - start) +1;
float average =0;
cout <<"Average of numbers between "<< start <<" and "<< end <<":\n";
do{
total += start;
start++;
}while(start <= end);
cout <<"\nTotal = "<< total;
cout <<"\nCount = "<< count;
average = (float) total / count;
cout <<"\nAverage is "<< average;
return0;
}

Output

Average of numbers between 1 and 10:
Total = 55
Count = 10
Average is 5.5

Find Average of N Numbers for any Given Range

In the following example, we will find the average of N numbers between the user given range.

Example

C++ Compiler

#include<iostream>#include<cmath>using namespace std;
int main()
{
int start, end;
cout <<"Enter a (int) starting number: ";
cin >> start;
cout <<"Enter an (int) ending number: ";
cin >> end;
int total =0;
int count = (end - start) +1;
float average =0;
cout <<"Average of numbers between "<< start <<" and "<< end <<":\n";
for(start=start; start<=end; start++)
total += start;
cout <<"\nTotal = "<< total;
cout <<"\nCount = "<< count;
average = (float) total / count;
cout <<"\nAverage is "<< average;
return0;
}

Output

Enter a (int) starting number: 5
Enter an (int) ending number: 10
Average of numbers between 5 and 10:
Total = 45
Count = 6
Average is 7.5

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on C++ with examples for quick and easy learning.

We are working to cover every Single Concept in C++.