-1

I store four numbers in my array, 00,11,22,33. When I generate a random number and print it, it displays 0 rather than 00 (when the first element is selected). The other numbers are fine and displaying correctly. How can I store 00 in an array so that it displays properly?

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

int main()
{
    srand(time(NULL));
    int myArray[4] = { 00,11,22,33 };
    int randomIndex = rand() % 4;
    int randomIndex1 = rand() % 4;
    int randomIndex2 = rand() % 4;
    int randomIndex3 = rand() % 4;

    int randomValue = myArray[randomIndex];
    int randomValue1 = myArray[randomIndex1];
    int randomValue2 = myArray[randomIndex2];
    int randomValue3 = myArray[randomIndex3];
    printf("= %d\n", randomValue);
    printf("= %d\n", randomValue1);
    printf("= %d\n", randomValue2);
    printf("= %d\n", randomValue3); 

    return(0);
}
CollinD
  • 7,304
  • 2
  • 22
  • 45
butbut
  • 31
  • 3

2 Answers2

2

00 the number, is exactly the same as 0 the number, while 11 is obviously a different number from 1.

Consider storing strings instead. Alternatively, if you want to display 00, just 2 characters using %02d as your formatting string:

printf("= %02d\n", randomValue);

If this really is your whole program, you could even just modify your array and then print values twice ex:

int myArray[4] = {0,1,2,3};
. . .
printf("= %d%d\n", randomValue, randomValue);
CollinD
  • 7,304
  • 2
  • 22
  • 45
0

The %02d scan code will prints the random number with zero padding:

printf("%02d\n", randomValue);
// Expected output for 0: 00
                          ^
                     This 0 belongs to the scan code 

Also, the %2d scan code will do blank space padding for you:

printf("%2d\n", randomValue);
// Expected output for 0:  0
                          ^
                     This space belongs to the scan code

In general %(0)NM is a scan code where:

  • 0 is optional and it belongs to numbers and if it is used, it will add zero padding to the output; if it is not used, it will add blank space padding.

  • N is the number of digits/characters you want to print e.g. 2.

  • M is the scan code you want to have to show your data type e.g. {d, x, c, s, ...} standing for {number, hexadecimal number, character, string, ...}

You can find a complete list of scan codes here.

hmofrad
  • 1,784
  • 2
  • 22
  • 28