I often rework programs from the forum to either help the original poster or learn a little more from some of the code (or both), but I have run across an unexpected result in a recent rework using scanf().
In this case scanf() is used to fill a simple array, with each value being tested against a limit. But, the array seems to be being manipulated differently in some cases.
In the following code, if all five values are entered at once, with one needing modification, the modified one is moved to the end of the array and the others are moved up. If the values are entered individually, all is as expected.
The program as I rewrote it (compiled using Dev-C++ 4.9.9.2 in WinXP):
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num[5],i;
printf("\nPls enter 5 numbers: ");
for(i=0; i<5; i++)
{
scanf("%d", &num[i]);
while(num[i]>11)
{
printf("\nPls reenter number %d: ", i+1);
scanf("%d", &num[i]);
}
}
printf("\nThe numbers are:");
for(i=0; i<5; i++)
printf("\n%d %d", i+1, num[i]);
printf("\n\n");
system("PAUSE");
return 0;
}
session 1 - all values entered at once:
Pls enter 5 numbers: 1 2 33 4 5
Pls reenter number 3: 3
The numbers are:
1 1
2 2
3 4
4 5
5 3
Press any key to continue . . .
session 2 - each value entered individually:
Pls enter 5 numbers: 1
2
33
Pls reenter number 3: 3
4
5
The numbers are:
1 1
2 2
3 3
4 4
5 5
Press any key to continue . . .
session 3 - double rentry of invalid element:
Pls enter 5 numbers: 1 2 33 4 5
Pls reenter number 3: 33
Pls reenter number 5: 3
The numbers are:
1 1
2 2
3 4
4 5
5 3
Press any key to continue . . .
Obviously, the array is being manipulated different from my expectations. Why is the value of element 2 (shown as 3) being moved in this manner?
Thanks.
Take Care,
Ed