In: Computer Science
C++
while loop Exercise
Write a program that continues to ask the user to enter any set of numbers, until the user enters the number -1. Then display the total sum of numbers entered and their average. (note that you need to define a counter that counts how many numbers so the average = (sum/n) where n is your counter total.
#include <iostream> using namespace std; int main() { int number, n=0, sum=0; cout << "Enter a number to start with " << endl; cin >> number; while (number != -1) { . . . } . . . return 0; } |
Exercise 3: For loop
Modify Exercise 2 so that the user enters only 5 numbers, and the code display the total sum and their average.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int number, n=0, sum=0;
float average;
cout << "Enter a number to start with " << endl;
cin >> number;
while (number != -1)
{
sum = sum + number; // summing the numbers
n++; // increment the counter
cin >> number;
}
average = (float)sum / n; // calculate average
cout << "Average = " << average; // print average
return 0;
}
OUTPUT :
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 5, sum = 0, a[5];
float average;
for(int i = 0; i < n; i++)
{
cin >> a[i]; // read the array
sum = sum + a[i]; // summing
}
cout << "Sum = " << sum << endl; // print the
sum
cout << "Average = " << (float)sum / n; // print the
average
return 0;
}
OUTPUT :