noob64 noob64 - 1 year ago 80
C Question

I am not able to understand the output I am getting for printing an array of 1st eight array elements

I am trying to understand how the following output is generated for the given code. The array of size eight elements stores the numbers as mentioned in the code. Here is the output it generates:

0 1 8 9 100 101 110 111

What I fail to understand is why is 8 and 9 a part of the output? Why aren't the values 010 and 011 being printed?

The code is given as:

#include <stdio.h>
#include <stdlib.h>

int main()
int i;
int a[8] = {000,001,010,011,100,101,110,111};

for(i=0 ; i<8 ; i++)
printf("%d ",a[i]);

return 0;

Answer Source

Any integer literal, starting with a 0 is considered an octal representation. In your code, you're initializing some of your array members with octal numbers and then printing out the decimal representation (using %d format specifier) of them.

So, your expectation and the output differs.

Basically, your initialization, in decimal form, looks like

 int a[8] = {0,1,8,9,100,101,110,111}; //first 4 initializers are converted to decimal.

On the other hand, just for sake of completion, if you use the %o format specifier (octal representation), you can see the first four initializers, as you expected, but the last four also will be printed as octal, like

 printf("%o  ",a[i]);

will give you an output of

0 1 10 11 144 145 156 157

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download