Learn C by writing a simple game | Opensource.com

Learn C by writing a simple game

This "guess the number" game is a great introductory program when learning a new programming language. Here's how to write it in C.

Business woman on laptop sitting in front of window
Image credits : 

Image by Mapbox Uncharted ERG, CC-BY 3.0 US

x

Subscribe now

Get the highlights in your inbox every week.

I taught myself about programming back in elementary school. My first programs were on the Apple II, but eventually, I learned C by reading books and practicing. And the best way to practice programming is to write sample programs that help exercise your new knowledge.

One program I like to write in a new language is a simple "guess the number" game. The computer picks a random number from 1 to 100, and you have to figure it out by making guesses. In another article, I showed how to write this "Guess the number" game in Bash, and my fellow Opensource.com authors have written articles about how to write it in Java, Julia, and other computer languages.

What's great about a "Guess the number" game is that it exercises several programming concepts: how to use variables, how to compare values, how to print output, and how to read input.

Over the summer, I recorded a video series to teach people how to write programs in the C programming language. Since then, I've heard from many people who are learning C programming by following it. So, I thought I'd follow up by writing a "Guess the number" game in C.

Pick a random number

Start the "Guess the number" game by writing a function to pick a random number. When writing functions, good programmers try to make them flexible, so they can reuse them to solve slightly different problems. So, instead of hard-coding the function to pick a random number between 1 and 100, write the function to pick a random number between 1 and some integer value maxval:

#include <stdio.h>
#include <sys/random.h>

int
randnum(int maxval)
{
  /* pick a random number from 1 to maxval */

  int randval;

  getrandom(&randval, sizeof(int), GRND_NONBLOCK);

  /* could be negative, so ensure it's positive */

  if (randval < 0) {
    return (-1 * randval % maxval + 1);
  }
  else {
    return (randval % maxval + 1);
  }
}

The function uses the Linux system call getrandom to generate a series of random bits. You can learn more about this system call on the man page, but note that getrandom will fill the variable with random zeroes and ones. That means the final value could be positive or negative, so you need to do a test afterward to ensure the result of your randnum function is a positive value.

Write the program

You can use this function to write your "Guess the number" program:

#include <stdio.h>
#include <sys/random.h>
 
int
randnum(int maxval)
{
  ...
}

int
main(void)
{
  int number;
  int guess;

  number = randnum(100);

  puts("Guess a number between 1 and 100");

  do {
    scanf("%d", &guess);

    if (guess < number) {
      puts("Too low");
    }
    else if (guess > number) {
      puts("Too high");
    }
  } while (guess != number);

  puts("That's right!");

  return 0;
}

The program starts by picking a random number between 1 and 100 using the randnum function. After printing a prompt to the user, the program enters a do-while loop so the user can guess the number.

In each iteration of the loop, the program tests the user's guess. If the user's guess is less than the random number, the program prints "Too low," and if the guess is greater than the random number, the program prints "Too high." The loop continues until the user's guess is the same as the random number.

When the loop exits, the program prints "That's right!" and then immediately ends.

$ gcc -o guess -Wall guess.c

$ ./guess
Guess a number between 1 and 100
50
Too high
30
Too low
40
Too low
45
Too high
42
Too low
43
Too low
44
That's right!

Try it out

This "guess the number" game is a great introductory program when learning a new programming language because it exercises several common programming concepts in a pretty straightforward way. By implementing this simple game in different programming languages, you can demonstrate some core concepts and compare details in each language.

Do you have a favorite programming language? How would you write the "guess the number" game in it? Follow this article series to see examples of other programming languages that might interest you.

A bunch of question marks

The C++ language is complex, but it can teach you a lot about data types, memory management, and code linking.
Learning and studying technology is the key to success

Writing simple games is a fun way to learn a new programming language. Put that principle to work to get started with Java.
Person reading a book and digital copy

Sharing knowledge with others is often a great way to refresh and update your own expertise.

Topics

About the author

photo of Jim Hall
Jim Hall - Jim Hall is an open source software advocate and developer, best known for usability testing in GNOME and as the founder + project coordinator of FreeDOS. At work, Jim is CEO of Hallmentum, an IT executive consulting company that provides hands-on IT Leadership training, workshops, and coaching.