Write C++ programs to perform the following tasks. In the program descriptions b
ID: 3884841 • Letter: W
Question
Write C++ programs to perform the following tasks. In the program descriptions below, example input and output is provided. NOTE: You don’t need arrays to solve any of these problems. You should NOT use arrays to solve any of these problems.
• stat.cpp: Let the user input a one or more integers, space separated, on a single line (as seen below), then work out and display the sum, average, sum of squares and population variance of the numbers. Remember, you do not need nor should you use an array to solve this problem.
Enter integers: 2 4 1 3
Sum: 10.0
Average: 2.5
Sum of Squares: 30.0
Variance: 1.25
NOTE: Given a set of numbers x1, x2, . . . , xn, the population variance be calculated by 1 n Pn i=1 x 2 i 1 n Pn i=1 xi 2 .
• minmax.cpp: Let the user input a one or more integers, space separated, on a single line (as seen below), then work out and display the largest and smallest values. Remember, you do not need nor should you use an array to solve this problem.
Enter integers: 1 9 3 7 5 6 4 8 2 10
Min: 1
Max: 10
Explanation / Answer
stat.cpp
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int numberOfIntegers=0, current;
double average, variance, sum = 0, sumOfSquares = 0;
cout << "Enter integers:";
while(cin.peek() != ' '){
cin >> current;
numberOfIntegers++;
sum += current;
sumOfSquares += pow(current, 2);
}
// Finally, we can compute the average and the variance.
// It is not required to compute them at each iteration.
// However, other aggregating variables should be updated in each loop.
average = (sum/numberOfIntegers);
variance = (sumOfSquares)/numberOfIntegers - pow(average,2);
cout << "Sum:" << sum << endl;
cout << "Average:" << average << endl;
cout << "Sum of Squares:" << sumOfSquares << endl;
cout << "Variance:" << variance << endl;
}
Output
Enter integers: 2 4 1 3
Sum: 10.0
Average: 2.5
Sum of Squares: 30.0
Variance: 1.25
minmax.cpp
#include <iostream>
using namespace std;
int main() {
int max, min, current, numberOfIntegers = 0;
// We need numberOfIntegers because we have to initialize the value of max, min with
// the current integer value only for the first time.
// From the next integer, we will compare and replace if necessary.
cout << "Enter integers:";
while(cin.peek() != ' '){
numberOfIntegers++;
cin >> current;
if(numberOfIntegers == 1){
min = current;
max = current;
}
else{
if(min > current){
min = current;
}
if(max < current){
max = current;
}
}
}
cout << "Min: " << min << endl;
cout << "Max: " << max << endl;
}
Output
Enter integers: 1 9 3 7 5 6 4 8 2 10
Min: 1
Max: 10
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.