1

why the code written below is giving output like this, instead of just returning the element as written:

CODE

#include<stdio.h>
int main()
{   int temp,a[8] = {000,001,010,011,100,101,110,111};
    for(temp = 0;temp < 8;temp++)
        printf("%d\n",a[temp]);

}

OUTPUT

0
1
8
9
100
101
110
111
  • Just some amendtment to the title: "containing binary numbers". The numbers in your array are not binary numbers. You are just using representations of binary numbers. So in the end, all you need is e.g. 1 char (8bit), set it to 0, and shift the individual bits e.g. with `<<`. But if this is all for demonstration purposes, then ignore it.... –  May 13 '21 at 09:10

2 Answers2

3

Any integer constant with a 0 at the beginning becomes an octal (base 8) number. In octal, 8 is 10, which is why 010, an octal constant, is printed as a decimal integer 8. Technically, 0 itself is an octal constant too, though this makes no real difference. Same for the rest of the numbers with a 0 prefix.

mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33
3

There is no binary constant in C (opposite to C++). And also there is no conversion specifier that could be used to output an integer number in the binary representation (You may output an integer number in the hexadecimal representation). But there is the notion of an octal integer constant.

From the C Standard (6.4.4.1 Integer constants)

Syntax

1     integer-constant:
          decimal-constant integer-suffixopt
          octal-constant integer-suffixopt
          hexadecimal-constant integer-suffixopt

and

  octal-constant:
      0
      octal-constant octal-digit

As it is seen from the grammar any integer constant that starts with zero ( 0 ) is an octal constant.

In this declaration of an array

int temp,a[8] = {000,001,010,011,100,101,110,111};

the first four elements of the array are initialized by octal constants that represent the following values in decimal 0, 1, 8, 9. All other constants are decimal integer constants.

If you want that all the initializers would be octal integer constants you have to write

int temp,a[8] = {000,001,010,011,9100,9101,9110,9111};

In this case you can output them in the form as they are written in the initializer list.

#include <stdio.h>

int main(void) 
{
    int a[] = { 000, 001, 010, 011, 0100, 0101, 0110, 0111 };
    const size_t N = sizeof( a ) / sizeof( *a );
    
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%03o ", a[i] );
    }
    
    putchar( '\n' );
    
    return 0;
}

The program output is

000 001 010 011 100 101 110 111 

In the call of printf there is no need to cast the expression a[i] to the type unsigned int because after the default argument promotions the outputted values can be represented in this type.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335