Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Simple number guessing game, annotated
- * @author Patrick Kage
- */
- // include some standard functions
- #include <stdlib.h>
- #include <stdbool.h>
- // standard input/output
- #include <stdio.h>
- // random number generator (+ time to seed RNG)
- #include <time.h>
- #include <ranlib.h>
- /*
- * Here is the main function. It's the entry point for the application.
- * Don't worry too much about the arguments for now.
- */
- int main(int argc, char** argv) {
- // First, let's seed the random number generator
- srand(time(0));
- // Generate a number 1-100. rand() generates a random integer, so we need
- // to take the modulo to get a number within our desired range.
- int target_number = rand() % 100;
- // Next, print our welcome message. printf() is the standard way of writing
- // to the terminal. Note that we explicitly have to add a newline to the end
- // of the statement
- printf("Welcome to the guessing game! Guess our number 1-100.\n");
- // Next, let's declare some variables for later.
- int guess = 0; // creates an integer
- char input[60]; // creates an array of length 60 filled with uninitialized data
- // Start the game loop
- while (true) {
- // Prompt for a guess, read into an input
- printf("Guess: ");
- scanf("%s", input);
- // Convert from string to int. If this fails, it's set to zero and a
- // global variable called errno is set.
- guess = atoi(input);
- // Handle the guess
- if (guess > target_number) {
- printf("Lower!\n");
- } else if (guess < target_number) {
- printf("Higher!\n");
- } else {
- // If we win, break out of the game loop
- printf("Hooray!\n");
- break;
- }
- }
- // Returning a number from the main function indicates whether the program
- // ran successfully. A non-zero exit code indicates a failure.
- return 0;
- }
Add Comment
Please, Sign In to add comment