This is my code. It is supposed to scan numbers until 0 is entered. Then it should print the numbers. But all it prints is zero.
#include <stdio.h>
int main()
{
int x[100];
int n;
int i;
for(i = 0; ; i++)
{
while(x[i] != 0)
{
scanf("%d", &x[i]);
n++;
}
if(x[i] == 0)
{
break;
}
}
for(i = 0; i < n;i++)
{
printf("%d\n", x[i]);
}
}
I was expecting to see the exact numbers that I entered.
>Solution :
The reason for the early exit is because here: while(x[i] != 0) can fail if the uninitialized value (x[i]) is 0. Though it might not be 0. But this logic is severely flawed in a couple other ways.
-
There is really no need to do a while loop since the for loop is already iterating through the array.
-
You should really have a terminating condition in the loop since, you could iterate passed 100 and write outside the bounds of the array.
-
nis uninitialized, so it could actually start counting at any number like 12456 or something =]
Here is what I think you want:
#include <stdio.h>
int main()
{
int x[100];
int n = 0; // init this!
int i;
for(i = 0; i < 100; i++) // added terminating condition here
{
scanf("%d", &x[i]);
n++;
if(x[i] == 0)
{
break;
}
}
for(i = 0; i < n;i++)
{
printf("%d\n", x[i]);
}
}
Also, you should really be checking the return value of scanf. I’ll leave that one to you =].