Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't this array save the scanned numbers?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

  • n is 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 =].

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading