LearnFrenzy
Sign in Take a free test

C Variables · Variable Programs · Question 3

Pseudo-random number generator with a static seed in C Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Implement a linear congruential generator with a seed kept in a file-scope static variable, a function to set the seed, and one to get the next number from 0 to 99.

Solution
main.c
#include <stdint.h>
#include <stdio.h>

static uint32_t state = 1;            /* private to this file */

void my_srand(uint32_t seed) { state = seed; }

int my_rand100(void) {
    state = state * 1664525u + 1013904223u;   /* wraps modulo 2^32: well-defined for unsigned */
    return (int) (state >> 16) % 100;         /* the high bits are the most random */
}

int main(void) {
    my_srand(42);
    for (int i = 0; i < 5; i++)
        printf("%d ", my_rand100());
    printf("\n");
    my_srand(42);                             /* same seed, same sequence */
    printf("%d\n", my_rand100());
    return 0;
}

Output Verified by compiling and running

37 75 32 85 19
37

Unsigned 32-bit arithmetic wraps modulo 2³², which is exactly what the generator needs. The static state is hidden from other files, and re-seeding reproduces the same sequence – useful for tests. (Not for cryptography.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links