PROGRAM IN C++ write a program that will find the sum, mean, or mode of a set of
ID: 639901 • Letter: P
Question
PROGRAM IN C++
write a program that will find the sum, mean, or mode of a set of integers, or a count of the total number of odd or even numbers. The first argument to your program will be a string that specifies which operation the user desires: "sum", "mean", "mode", "odd", or "even". You will then use std::cin to read in the user's numbers. Return the value 0 from your main function upon successful completion.
Your program will accept a single string option as a command line argument (argv[1]).
The option should be "sum", "mean", "mode", "odd", or "even".
Then a series of numbers should be read in from std::cin. Stop reading input
when there is a non-numeric input, e.g.
while (std::cin >> number) {
...
}
The output should look something like this depending on what is asked:
If the option is sum then print out the sum of all of the numbers and return 0.
If the option is mean then print out the average of all of the numbers and return 0.
If the option is mode then print out the most frequently occurring number (if
two are tied then you may return either) and return 0.
If the option is odd then print out the number of odd numbers numbers and return 0.
If the option is even then print out the number of even numbers numbers and return 0
Some examples:
./main sum
1 2 3 7 8 9 quit
30
./main mode
1 2 3 3 4 5 6 6 6 7 8 9 quit
6
./main mean
-1 -2 -3 -4 stop
-2.5
./main odd
-1 -2 -3 -4 stop
2
Explanation / Answer
#include <iostream>
#include <string>
int main(int argc, char *argv[]){
std::string cmd;
int arr[100];
int count = 0, number;
if(argc > 1){
while(std::cin >> number){
arr[count++] = number;
}
cmd = argv[1];
if(cmd == "sum"){
int sum = 0;
for(int i = 0; i < count; ++i){
sum += arr[i];
}
std::cout << sum << std::endl;
}
else if(cmd == "mean"){
int sum = 0;
for(int i = 0; i < count; ++i){
sum += arr[i];
}
std::cout << sum / (double)count << std::endl;
}
else if(cmd == "mode"){
int c = 0, lc = 0, num = 0;
for(int i = 1; i < count; ++i){
if(arr[i] == arr[i - 1]){
lc++;
}
else{
if(lc > c){
c = lc;
lc = 0;
num = arr[i - 1];
}
}
}
std::cout << num << std::endl;
}
else if(cmd == "odd"){
int c = 0;
for(int i = 0; i < count; ++i){
if(arr[i] % 2 != 0){
c++;
}
}
std::cout << c << std::endl;
}
else if(cmd == "even"){
int c = 0;
for(int i = 0; i < count; ++i){
if(arr[i] % 2 == 0){
c++;
}
}
std::cout << c << std::endl;
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.