Logo  

CS256 - Fundamentals of Structured Programming

Displaying ./code/functions/rnd.c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>

/**
 * Returns a random integer between 'a' and 'b' (inclusive)
 */
int R(int a, int b)
{
  int diff = (a < b? b-a : a-b)+1;
  int min = a < b? a : b;
  return min + (rand()%diff);
}

void line(int n)
{
  for(int i=0; i < n; i++)
    putchar('#');
  putchar('\n');
}

int main(void)
{
  int n[21];

  srand(time(0)+getpid());

  for(int i=0; i < 21; i++) n[i] = 0;

  for(int i=0; i < 1000; i++) {
    int idx = R(0,20);
    n[idx]++;
  }

  for(int i=0; i < 20; i++) {
    printf("%2d: %3d ", i, n[i]);
    line(n[i]);
  }
  
  return 0;
}