2

I would expect this code to print

0 1 2 3 4 5 6 7 8 9

but it only prints the first two elements of the array:

0 1

I realize I could just change the condition in my for loop to i < 10 to get the desired output, but I want to understand how/whether I can use the value of an element of the array to set the condition.

Thank you!

code:

#include <stdio.h>

int main()
{

    int array[10];

    for(int i = 0; array[i] < 10; i++)
    {
        array[i] = i;
        printf("%d ", array[i]);
    }

}

3 Answers 3

4

What you really want for your for loop is

for(int i = 0; i < 10; i++)

The way you've got it now, you're checking the value of array[i] before it is given a value, meaning its value is whatever junk memory was on the stack when your function began.

Sign up to request clarification or add additional context in comments.

Comments

2

Your array is uninitialized, so the values it contains are indeterminate. There' no guarantee that uninitialized values will contain any particular value, and in fact the value read may change on subsequent reads.

If you want meaningful results, the elements of the array need to be initialized with some value before you can read them.

Comments

2

In your code, the array element that you are looking is uninitialized, and contains garbage. You can check values that are initialised on the previous iteration, like this:

#include <stdio.h>

int main()
{

    int array[10];
    array[0]=0;
   printf("%d ", array[0]);
    for(int i = 1; array[i-1] < 9; i++)
    {
        array[i] = i;
        printf("%d ", array[i]);

    }

}

I have made some changes to your code, please try this. If anyone has any suggestion or correction, please leave a comment.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.