daily pastebin goal
42%
SHARE
TWEET

Untitled

a guest Jul 19th, 2018 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Simple number guessing game, annotated
  3.  * @author Patrick Kage
  4.  */
  5.  
  6. // include some standard functions
  7. #include <stdlib.h>
  8. #include <stdbool.h>
  9.  
  10. // standard input/output
  11. #include <stdio.h>
  12.  
  13. // random number generator (+ time to seed RNG)
  14. #include <time.h>
  15. #include <ranlib.h>
  16.  
  17. /*
  18.  * Here is the main function. It's the entry point for the application.
  19.  * Don't worry too much about the arguments for now.
  20.  */
  21. int main(int argc, char** argv) {
  22.     // First, let's seed the random number generator
  23.     srand(time(0));
  24.  
  25.     // Generate a number 1-100. rand() generates a random integer, so we need
  26.     // to take the modulo to get a number within our desired range.
  27.     int target_number = rand() % 100;
  28.  
  29.     // Next, print our welcome message. printf() is the standard way of writing
  30.     // to the terminal. Note that we explicitly have to add a newline to the end
  31.     // of the statement
  32.     printf("Welcome to the guessing game! Guess our number 1-100.\n");
  33.  
  34.     // Next, let's declare some variables for later.
  35.     int guess = 0; // creates an integer
  36.     char input[60]; // creates an array of length 60 filled with uninitialized data
  37.  
  38.     // Start the game loop
  39.     while (true) {
  40.         // Prompt for a guess, read into an input
  41.         printf("Guess: ");
  42.         scanf("%s", input);
  43.  
  44.         // Convert from string to int. If this fails, it's set to zero and a
  45.         // global variable called errno is set.
  46.         guess = atoi(input);
  47.  
  48.         // Handle the guess
  49.         if (guess > target_number) {
  50.             printf("Lower!\n");
  51.         } else if (guess < target_number) {
  52.             printf("Higher!\n");
  53.         } else {
  54.             // If we win, break out of the game loop
  55.             printf("Hooray!\n");
  56.             break;
  57.         }
  58.     }
  59.  
  60.     // Returning a number from the main function indicates whether the program
  61.     // ran successfully. A non-zero exit code indicates a failure.
  62.     return 0;
  63. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top