Help with command line qns

Qns:
Write a C++ program that reads from the command line a set of game scores.
Your program should do the followings:

• Determine the number of game scores in the command line using the
argc variables.
• Display the number of game scores in the command line.
• Find the highest game score.
• Display the highest scores.

For example, suppose the following games scores are entered in the command
line:
92 73 63 97 52 34 41 24 46 17

The, the program should display the following output:
Number of scores : 10
The highest score is 97

The below is the code i was given as a guide!

But i dont understand why is there a int num?
and why is there a check if num > max?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
 cout << "Number of scores : "
 << (argc - 1) << endl;
 int max = 0;
 int num;
 for (int i=1; i<argc; i++) {
 num = atoi(argv[i]);
 if (num > max)
 max = num;
 }
 cout << "The highest score is "
 << max << endl;
 return 0;
}
the integer num is for storing the current number and num>max is for checking if the current num is greater than the max then it will be stored in max. and thus after all the numbers are compared the greatest value will be stored in max because the biggest number will replace the smallest numbers and will be stored in max.
Last edited on
But i dont understand why is there a int num?

The variable num is used to store the result of converting the command-line text into an integer. Rather than declaring int num; on line 7, it could have been declared where needed on line 9.
 
    int num = atoi(argv[i]);


and why is there a check if num > max?

That is the method used to determine the highest game score. Each value is compared with the current highest score, if it is bigger, then the highest score is updated to store the current value.
Hi Sajeel and Chervil

Thank you so much for the explanation.

So can I say that every no in the command line is being passed to num value and later check if it is more then max value. The program runs till every num is checked and we get the max?
yup
Great! Thank you so much Sajeel and Chervil! :)
Topic archived. No new replies allowed.