4

I'm just now picking up C, so I'm pretty terrible since I'm coming from basic Python. I'm trying to print the elements in an array using a for-loop, but it's not coming out the right way.

#include <stdio.h>
#include <math.h>
int main()
{
  int array[]={0,1,2,3,4};
  int i;
  for (i=0;i<5;i++);
  {
      printf("%d",array[i]);
  }
  printf("\n");
}

My output is

134513952

I have no clue why it's printing this.

2
  • You don't need <math.h>. You might want to separate the numbers from each other (spaces, or %2d or something). And you definitely don't want to go accessing out of the bounds of your array — the semicolon after the for means you are accessing array[5] which is out of bounds. Commented Sep 19, 2013 at 0:33
  • Once you delete the extra semicolon, your output should be 01234, which is difficult to read. You might want change your format string from "%d" to " %d", so the numbers are shoved together. Commented Sep 19, 2013 at 0:40

3 Answers 3

7

You have an extra semicolon.

 for (i=0;i<5;i++);
                  ^
                  |
        here -----+

That semicolon means your for loop has an empty body, and you end up printing after the loop completes, equivalently:

printf("%d", array[5]);

Since that value is beyond the end of the array, you get undefined behaviour and some strange output.

Editorial note: You should look into a compiler that gives better warnings. Clang, for example, gives this warning, even with no special flags passed:

example.c:7:20: warning: for loop has empty body [-Wempty-body]
  for (i=0;i<5;i++);
                   ^
example.c:7:20: note: put the semicolon on a separate line to silence this
      warning
Sign up to request clarification or add additional context in comments.

Comments

2

Skip the semi-colon in the for-loop:

for (i=0;i<5;i++);

For your logic, you don't need a simi-colon after the for-loop.

Due to semi-colon, the for-loop is evaluated 5 times and by the time it reaches the printf, the value of i is 5. Now, trying to access the index 5 in array is giving you an unknown value since you have initialized the array with 5 values only. This can become clearer, if you were to print the value of i in the printf statement:

  for (i=0;i<5;i++);
  {
     printf("i: %d \t Val: %d",i, array[i]);
  }

Will give you an output such as:

i: 5     Val: 32767

Comments

0

semicolon after for loop was the problem. Before it was printing some random number, since the storage class was automatic.

#include <stdio.h>
#include <math.h>
int main()
{
  int array[]={0,1,2,3,4};
  int i;
  for (i=0;i<5;i++);
  {
      printf("%d",array[i]);
  }
  printf("\n");
}

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.