examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

guess-number.c (642B)


      1 #include <stdio.h>
      2 #include <time.h>
      3 #include <sys/random.h>
      4 
      5 int main()
      6 {
      7 	unsigned short n, guess, score = 0;
      8 
      9 	time_t start = time(NULL);
     10 
     11 	getrandom(&n, sizeof(n), 0);
     12 
     13 	do
     14 	{
     15 		printf("Enter number: ");
     16 
     17 		int res = scanf("%hu", &guess);
     18 		switch (res)
     19 		{
     20 		case EOF:
     21 			puts("\nGiving up so soon?");
     22 			return 0;
     23 		case 0:
     24 			scanf("%*[^\n]");
     25 			puts("Invalid input, Try again!");
     26 			break;
     27 		case 1:
     28 			++score;
     29 			if (n < guess)
     30 				puts("Lower!");
     31 			else if (n > guess)
     32 				puts("Higher!");
     33 		}
     34 	} while (guess != n);
     35 
     36 	time_t end = time(NULL);
     37 
     38 	printf("Congratultions, your score is %lu\n", score * (end - start));
     39 	return 0;
     40 }