YnSkn
YnSkn

Reputation: 125

C random integer generator question (A book on C 4th Edition)

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

int main(void)
{
   int i, n;

   printf("\n%s\n%s",
     "Some randomly distributed integers will be printed.",
     "How many do yo want to see? ";
   scanf("%d", &n);
   for (i = 0; i < n; ++i) {
     if (i % 10 == 0)
       putchar('\n');
     printf("%7d", rand());
   }
   printf("\n\n");
   return 0;
}

this is the code from the textbook "A book on C".

when you type 23 when prompted it is supposed to generate 23 random numbers in 3 rows, 8 columns (3*8-1).

i learned that printf("%7d", rand())is supposed to return a value printed in a format of a decimal integer and the width of the field where the integer gets printed is 7.

however, I am getting random numbers that are in a width of more than 7 and it doesn't look neat at all. (no columns nor rows, just a huge chunk of consecutive numbers like 1235289043528935294835698246182965982)

I thought it has something to do with the expression printf("%7d", rand()) function and the way how it is supposed to return values.

I'm starting to think that the textbook is wrong.

Upvotes: 1

Views: 71

Answers (4)

chux
chux

Reputation: 154245

Rather than guess the maximum width of a rand() number, calculate the width of maximum random number: RAND_MAX.

snprintf(NULL, 0, ... prints the number of characters that would have been written had the buffer been sufficiently large, not counting the terminating null character.

int width = snprintf(NULL, 0, "%d", RAND_MAX);

Later when printing, use the width.

printf(" %*d", width, rand());

as in

#define COLUMN_N 8
for (i = 0; i < n; ++i) {
  printf(" %*d", width, rand());
  if (i % COLUMN_N == COLUMN_N - 1 || i + 1 == n) {
    putchar('\n');
  }
}

Upvotes: 0

C. Dunn
C. Dunn

Reputation: 101

Your numbers are bigger than 7 digits. You can try:

A) Changing the width field higher:

printf("%14d", rand() );

or

B) Making the generated numbers smaller than 7 digits:

printf("%7d", rand() % 1000 );

More information on format specifiers can be found here

Hope that helps!

Upvotes: 1

Gili
Gili

Reputation: 1

In addition to the comment above, if I understand correctly you want all 8 numbers then the line should be changed to be: if (i % 8 == 0);

Upvotes: 0

William Pursell
William Pursell

Reputation: 212414

You are not printing any whitespace. Try inserting some:

printf("%7d\t", rand());

Upvotes: 0

Related Questions