Reputation: 53
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.
Upvotes: 4
Views: 225
Reputation: 1619
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");
}
Upvotes: 0
Reputation: 4666
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
Upvotes: 2
Reputation: 224844
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
Upvotes: 7