Question and Answer, Explanation needed!

Write a C++ program that reads from the command line the names of four players and their scores for an online game.

For example, suppose the following values are entered in the command line:
Gary 4838 Mary 8717 Jack 5413 Jill 4954

Find the player with the highest score.

1
2
3
4
5
6
7
8
9
10
int max = atoi(argv[2]);
int pos = 2;
for (int i=4; i<=8; i=i+2) 
{
 if (atoi(argv[i]) > max) 
 {
 max = atoi(argv[i]);
 pos = i;
 }
}


Kindly explain what the following does:
- atoi(argv[2] - why is it 2
- int pos = 2
- for (int i=4; i<=8; i=i+2)
- in the if loop
max = atoi(argv[i]);
pos = i;
closed account (48T7M4Gy)
Perhaps you could search the voluminous and very comprehensive files of information, including examples, on this website.

Your first step is to understand int main(argv[], argc)) style and how those values of input are used in the body of the main program.

The once ubiquitous Duoas has, needless to say, contributed on this topic.
http://www.cplusplus.com/forum/beginner/5404/#msg23839

Assuming input is valid,
- atoi(argv[2] - why is it 2

argv[0] is the name of the program
argv[1] is the first command line argument
argv[2] is the second command line argument.
In this case, max is initialised with 4838.

- int pos = 2

Similarly, pos is the index of the number.

- for (int i=4; i<=8; i=i+2)

This is a loop to compare all the other numbers to the current max number.
int i=4, to start comparing from the second number in argv.
i<=8, the last number to compare is at index 8 in argv.
i=i+2, remember that each number is 2 positions away from the previous

max = atoi(argv[i]);
pos = i;

Updates the highest number and the index of that number.
Thank you so much Kemort and Integralfx.
Topic archived. No new replies allowed.