0
#include <stdio.h> 
int main () {

int n[ 10 ] = {002535}; /* n is an array of 10 integers */
int j;

/* output each array element's value */
for (j = 0; j < 10; j++ ) {
  printf("Element[%d] = %d\n", j, n[j] );
}

return 0;
}

The above code runs and returns the first element to be equal to 1373. Could you explain this? I am not able to understand the reason behind the number being changed due to padding in the integer provided.

Output comes out to be the following lines.

Element[0] = 1373
Element[1] = 0
...
Element[9] = 0

2 Answers2

0

In your program, you are initializing the array n -

int n[ 10 ] = {002535};

The number 002535 is interpreted as a octal number because of leading zeros. So, this will assign the octal value 002535 to n[0] i.e. 0th location in your array n and rest of array elements will be initialized with 0.

In for loop, you are printing it with format specifier %d.

The decimal equivalent of 002535 octal value is 1373. That's why you are getting Element [0] as 1373.

If you want to print octal number as output, use %o format specifier:

for (j = 0; j < 10; j++ ) {
  printf("Element[%d] = %o\n", j, n[j] );

And if you want the decimal 2535 as first element of array n, remove leading zeros:

int n[ 10 ] = {2535};
H.S.
  • 11,654
  • 2
  • 15
  • 32
0

An integer literal starting with 0 is interpreted as an octal number. And 02535 octal is equivalent to the decimal 1373

sidyll
  • 57,726
  • 14
  • 108
  • 151