0

I want to put the random numbers from 000 to 999 in the array.

for (i = 0; i < 1000; i++)
{
    arr[i] = rand() % 1000;
    printf("%02d ", arr[i]);
}

This is just print, I want to do zero-padding element in the array. example) arr = [000,001,002,....999]

Is there a way?

2 Answers2

0
#include <stdio.h>

int main(void) {
    int arr[1000];
    for (int i = 0; i < 1000; i++)
    {
        arr[i] = rand() % 1000;
        printf("%03d ", arr[i]);
    }
    return 0;
}

IDEOne link

Output

Success #stdin #stdout 0s 4412KB
383 886 777 915 793 335 386 492 649 421 362 027 690 059 763 926 540 426 172 736 211
368 567 429 782 530 862 123 067 135 929 802 022 058 069 167 393 456 011 042 229 373 
421 919 784 537 198 324 315 370 413 526 091 980 956 873 862 170 996 281 305 925 084
327 336 505 846 729 313 857 124 895 582 545 814 367 434 364 043 750 087 808 276 178
788 584 403 651 754 399 932 060 676 368 739 012 226 586 094 539 795 570 434 378 467
601 097 902 317 492 652 756 301 280 286 441 865 689 444 619 440 729 031 117 097 771
481 675 709 927 567 856 497 353 586 965 306 683 219 624 528 871 732 829 503 019 270
368 708 715 340 149 796 723 618 245 846 451 921 555 379 488 764 228 841 350 193 500
034 764 124 914 987 856 743 491 227 365 859 936 432 551 437 228 275 407 474 121 858
395 029 237 235 793 818 428 143 011 928 529 776 404 443 763 613 538 606 840 904 818
Community
  • 1
  • 1
abelenky
  • 63,815
  • 23
  • 109
  • 159
  • He want to put numbers with zero padding into an Int array(not printing them to standard output) which is impossible. Its better to put some explanation with your answer always. – milad May 06 '20 at 15:43
0

You can not fill an int array with zero-padding numbers. because the int type will store just the integer values, Consider below example:

#include <stdio.h>
    int main(){
        int a = 0001;
        printf("%d\n", a);
        return 0;
    }

The result of above code is:

1

And that's it. By the way, if you want to have zero-padding numbers, you should print them to an array of characters and use sprintf instead printf, look at below example:

#include <stdio.h>
//include other necessary libraries.

int main(){
    char* randomNumbers[1000];
    //while your numbers are at most 4 digit, I will allocate just 4 bytes:
    for(int i = 0; i < 1000; i++){
        randomNumbers[i] = (char*) calloc(4, sizeof(char));
    }

    //here we go to answer your question and make some random numbers which are zero-padding:
    for(int i = 0; i < 1000; i++){
         int a = rand() % 1000;
         sprintf(randomNumbers[i], "%03d", a);
    }
}

The randomNumbers array is your suitable array.

milad
  • 1,854
  • 2
  • 11
  • 27
  • I'm sorry to check late, thank you for your comment! You told me exactly what I don't understand. :) Thank you very much. – Song Chaeeun May 11 '20 at 15:57
  • @SongChaeeun your welcome, if it solved your problem, please accept my answer to close the question. – milad May 12 '20 at 09:09