简体   繁体   中英

Explanation for the code needed

Someone wrote the following code when asked to Input N integers seperated by a whitespace

  do
   {
       cin>>temp;
      name[i]=temp;


       if(i==N-1)
           break;
       i++;


   }while(true);

Here it is initialized to zero. I want to know why this piece of code works correctly. If I give the following input with N=4 , 2 34 5 87 , the array name stores the values properly. name[0]=2 name[1]=34 and so on. If I write cout<<"Hello" after the cin statement, it doesn't execute until I press return. Basically I want to know how the loop is actually working. Any help will be appreciated. Thank You.

This is a do - while loop, which means it is entered at least once. Therefore the code does not correctly handle the case when N == 0 .

Assuming N > 0 and i is initialized to 0 and the input read from cin is correct, then the loop runs until the break statement. break will terminate the loop regardless of the terminating condition.

The break statement is executed when i == N-1 is true. This occurs after name[N-1] = temp , which means N items have been assigned when the loop terminates, since i is incremented at each iteration for which i != N-1 is true.

By default, cin treats spaces as separating your "tokens" or pieces of input. Each time cin is used, it will give you the number.

Now try this heavily-commented version.

do {
    /* Read a number */
    cin >> temp;
    /* Save the number into the i'th element of the array name */
    name[i] = temp;

    /* If we have reached the maximum size of the array as given by N, exit the loop. */
    if (i == N-1) {
        break;
    }
    /* If we haven't reached the maximum size, increase i by 1 and keep saving to the array. */
    i++;
} while(true);

The code isn't great. It would be better to put (i < N-1) as the while-condition, and not use break at all.

Also note that this is only a piece of a larger function. The larger function must declare the variables (such as giving a value to N ) if it's going to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM