Guess a number between 1 and 100 - C Data Type

C examples for Data Type:Random Number

Description

Guess a number between 1 and 100

Demo Code

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

int main() {/* w ww. j  a va2s  .c  om*/
   int answer, guess, random(int, int);

   printf("Guess a number from 1 to 100.\n");

   srand(time (0));
   answer = random(1, 100);

   printf("Your guess? ");
   scanf("%d", &guess);
   while (guess != answer && guess != 0) {
      if (guess < answer) 
         printf("Too low\n");
      else 
         printf("Too high\n");
      printf("Your guess? ");
      scanf("%d", &guess);
   }
   if (guess == 0) 
      printf("Sorry, answer is %d\n", answer);
   else 
      printf("Congratulations, you've got it!\n");
}

int random(int m, int n) {
   int offset = rand() / (RAND_MAX + 1.0) * (n - m + 1);
   return m + offset;
}

Related Tutorials