Reputation: 1945
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.
Upvotes: 0
Views: 55
Reputation: 958
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.
Upvotes: 0
Reputation: 70362
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.
Upvotes: 1