Introduction: C for Beginners: Functions/Loops: Guessing Game

Picture of C for Beginners: Functions/Loops: Guessing Game

In this instructable, you will learn how to code a simple guessing game in C. Throughout the steps, you will be implementing many basic features of the C language. Before we dive into the code itself it is important that you learn the fundamentals beforehand. Learning the following topics will make understanding the code a bit easier.

Note: If you are familiar with the basics of the C language, skip to Creating a New Project.

1. Commenting

In code, commenting is used to add important notes about each step being performed. To comment a single line of code simply type // followed by the comment.

Ex. //comment

Comments are also used to create headers at the beginning of the source code. To comment multiple lines of code you would type /* followed by the comment and you would add a corresponding */ to close the comment. Ex. /* Name

Date

Program Name */

Commenting is especially important when other people look at your code. They should be able to view your code and understand your implementation in each step you take.

2. Libraries

Libraries in C hold a group of functions and declarations that are accessible to the programmer when included. Library declarations are typically placed at the beginning of a file and follow the format #include<libraryname.h>. The ones we will be using in this program are:

//includes functions that have to do with input and output

#include <stdio.h>

//includes functions that are standard for C

#include <stdlib.h>

//includes functions that have to do with time #include

#include <time.h>

3. Preprocessors

In C, preprocessors are a number of directives that instruct the compiler to do required preprocessing (hence the name preprocessor) before the code is actually compiled. Preprocessors begin with the symbol (#).

Ex. #include

#define

4. Variables

In code, you will have to create names for variables that the program can manipulate. Each variable is declared with a type followed by the variable name. Some common variable types include:

int: used for natural sized integer variables

char: integer type of one byte

float: used for decimals (can store 7 digits)

double: used for decimals (can store 15-16 digits)

5. Arithmetic

To solve certain problem in code, arithmetic will be needed. In C, there are specific ways to use operators to do math. Let's look at some of these ways:

When doing arithmetic to a variable, always remember that the variable being affected goes on the left side of the equation.

Ex. int variable =3;

Rule 1: The value of the variable can be changed at any time by adding another statement.

Ex. variable=123;

Rule 2: You can also increment or decrement the value of an integer by one by doing the following:

variable++; //value of variable will increase by 1

variable--; //value of variable will decrease by 1

Rule 3: To add onto or subtract a value from the variable you would do the following:

variable+=3; //the current value of variable will increase by 3

variable-=3; //the current value of variable will decrease by 3

This rule also applies to multiplication.

Ex. variable*=3; // the current value of variable will be multiplied by 3

Rule 4: To divide you would use the (/) symbol.

Ex: float avg;

int scoreOne;

int scoreTwo;

avg=(scoreOne+scoreTwo)/2;

There is another operator (%) that will give the remainder of a division problem. It is called the modulus operator. Let's say you want to know what's left over after you divide 31 by 4. This is how you would write that in code:

int num=31;

num%3; //this computes the remainder when you divide 31 by 4. The answer will be 3.

6. Print Statements & Scanning

The print function can be called in order to type something that you want the user to see when you run the program. For example, if you need input from the user you have to first ask them for that input. The print function is used as followed:

printf(“Enter a number”);

When the user runs the program they will only see “Enter a number.”

Once they enter a number you need to have stored memory for that number variable. This is done by using the scan function.

Ex. int number; //first declare the variable

printf(“Enter a number”); //prompt user for number

scanf(“%d, &number); // scan in the number from the user

The (%d) tells the computer we are reading in an integer. The (&) symbol assigns the input value to the address in memory for the variable number.

7. While & If Statements

Sometimes, you will only want part of a code to run in some sort of conditional way. This is where while and if statements come into play. The while statement continually executes a block of code while the condition is true. It is written as:

while(some condition){

statement(s)

}

An if statement is pretty similar. If the conditional if statement is true the the block of code that follows will be executed. If the condition is not true then that block of code will be skipped.

Ex. If( some condition){

statement(s)

}

Step 1: Installing an IDE and Creating a New Project

Before we get started programming, we need to install an IDE, or Integrated Development Environment. An IDE includes all of the software you will need to write and compile this program, including a text editor, compiler (for making your program able to run), and a debugger (for testing code in larger programs).

Installing CodeBlocks

For this instructable, we will be using CodeBlocks as our compiler.

  1. Go to www.codeblocks.org in your favorite web browser.
  2. Click the “Downloads” button on either the top or left side panel of the page.
  3. Click “Download the binary release.”
  4. Find your computer’s operating system and download the appropriate setup package.
    1. Windows users:
      1. Note: Please be sure to download the correct package. Other packages may not include all the files necessary to run your program.
      2. Download the package titled “codeblocks-16.01mingw-setup.exe” by going to the link provided. Download should begin automatically. Follow the installer’s prompts, and you should be good to go!
    2. Mac users:
      1. Download “CodeBlocks-13.12-mac.zip” by going to the link provided. Download should begin automatically. Install the program, and you should be good to go!

Creating a New Project

  1. To create a new project, first open up CodeBlocks, then go to File>New>Project and select Empty Project from the list.
  2. Click the Next button.
  3. The screen you’re on should now have fields to title your project and choose the folder you want to place it in. In the Project title field, type what you want your project to be called. Click Next.
  4. The next page is choosing the compiler and other options. Leave all these at their defaults and click Finish.
  5. Go to File>New>Empty file, save it as a .c file, add the file to your newly created project, click OK for any other prompts that pop up, and you are ready to start coding!

Step 2: Functions

Picture of Functions

Functions are used to perform specific tasks to simplify your program. Rather than having a busy and unorganized main function, you can call for specific functions inside your main function.

Functions are created in the following form (Picture 1).

The return type can be any primitive data type in C (int, double, char, etc) or it can be void. If it is void, it does not return anything to the main function, but may do something within the function like print out a message.
If it is a primitive type, you can declare a variable of that type within main and set it equal to the function.

Following the return type is the name of the function.Any name can be used, but make it summarize what the function does for future understanding of your program or public understanding if the code is published.

The parameters go inside a set of parenthesis. Parameters are used as input variables to the function. When creating the function, the parameter type as well as its name is put with commas in between. When calling for the function within main (or within another function) simply put the variable in the parameters, not the data type.

The body of the function is what is to be performed when the function is called. If it is not a void function, the body of the function should end with a return statement followed by the variable of the function’s return type. If the function is not placed before the main function, a function declaration is needed. This is placed right under the libraries. An example of a function declaration is shown in Picture 2.

As you can see it is very similar to the function itself, but followed by a semicolon rather than its brackets.

Step 3: Main Menu

Picture of Main Menu

Now, to start building our project!

First, begin to build a menu function.

In this void function, a menu of options is printed to the terminal. Although the only thing this function does is print a menu, when used preceding the GetChoice function, it will show the list of options that can then be entered and selected in the GetChoice function.

Step 4: A. GetChoice

Picture of A. GetChoice

This GetChoice function allows the user to pick a choice from the menu prompt. The min and max values are entered in the function when it is called in the main() function.

Step 1: A function needs to be initialized named GetChoice.

Step 2: The parameters of min and max need to be initialized.

Note: In the function main(), these parameters will be given values which will be shown to the player of the game when the program runs.

Step 5: B. GetChoice

Picture of B. GetChoice

Step 3: Inside of the function, the first item needs to be initializing the variable Choice and setting it equal to zero.

Note: Initializing this variable to zero ensures the compiler will not assign a random number to this variable and complicate later commands.

Step 6: C. GetChoice

Picture of C. GetChoice

Note: This function will need the use of a while loop. You can review the introduction on how these loops function. For this application, a while loop ensures that no matter what the user inputs, the only input that will prompt the code to continue will be between the variables min and max (will be declared in main and are the number of options the menu has).

Note: For this loop, we want the Choice that the user inputs to be between the parameters of the menu. By this definition, we can say that the Choice must be greater than min OR less than max. In the C language, “||” means “or”.

Step 4: Set your parameters of the while loops to the variable Choice is greater than min or less than max.

Step 7: D: GetChoice

Picture of D: GetChoice

Step 5: Write a printf statement saying “Enter a choice from (min) to (max)”.

Step 6: Create a scanf statement to assign the above printf statement to the variable Choice.

Step 8: E. GetChoice

Picture of E. GetChoice

Step 7: Return the variable Choice.

Note: The finished product of this function should look like the second picture.

Step 9: A. GuessGame

Picture of A. GuessGame
  • This step is the core portion of the guessing game; in which the processing of the inputs and calculation of the score take place.
  • You initially will have to include your variables to work with as well as initializing time. Time is included in the time.h library, where you typed in the very first lines of the function. You will need time to calculate the score and also to seed the random number generator.

Step 10: B. GuessGame

Picture of B. GuessGame
  • The random number generator function srand() is included in the stdlib.h library, and is needed to spawn the number to be guessed. max variable will be limiting the maximum number and is inputted by the user.
  • After retrieving the max variable input from the user, you will initialize time and get a random number to be guessed with a lower bound of 1 and a confined upper bound of max variable.

Step 11: C. GuessGame

Picture of C. GuessGame
  • Following the while loops and if statements, you will write the code to check the guessed number inputs which are retrieved by the user with scanf function.
  • While the guessed input is not equal to the correct number, of which is calculated with “!=” relational operator, the program will inform the user if the guessed number is higher or lower than the correct number.
  • If guess is not equal to random, while loop will continue to execute.
  • If guess is less than random, the program will print "Your guess is too low. Guess again."
  • If guess is more than random, the program will print "Your guess is too high. Guess again."

Step 12: D. GuessGame

Picture of D. GuessGame
  • The program will only go into the while loop if the number guessed is not equal to the correct number.
  • When the guessed number is equal to the correct number, you need to write the portion of the code where the time function is being terminated. You will also need to inform the user with a terminal output of how many tries they had to guess the correct number and how many seconds has passed since the beginning of the game by including the counter variable of i and time counter variable of timespent.

Step 13: E. GuessGame

Picture of E. GuessGame
  • Finally for this step, you will write a code to calculate the score.
  • You will be including the timespent variable and dividing it by the double of digits variable, where digits is the number of digits in a given number, which you will see on the next step.
  • Then, you will be returning the InScore variable to the main function, to keep it allocated in the memory of the program, in case the user wants to keep track of the points if they want to reprint the score or play the game again.

Step 14: PrintScore & Quit

Picture of PrintScore & Quit

PrintScore

In this void function, which returns nothing, your current score is printed to the terminal.

Score is a global variable. A global variable is a variable that is accessible throughout the entire program. If you have any trouble understanding “%d” or how “printf” works, reference the Intro page.

PrintScore is shown in Picture 1.

Quit
In this void function, a message is printed out to the terminal. After that is printed, the program calls for the exit function. Since Quit is the last function that the program uses, it ends the program with exit (). The exit function is a built in function in the language of C. When calling for exit (0), the program exits successfully. When calling exit (-1), it will end the program with an error.

Quit is shown in Picture 2.

Step 15: NumDigits and NumPoints

The guessing game is scored based on how large the highest number is and the amount of time it takes the user to answer the question. For example, if the highest number the user wished to guess to 100 and not 10, the scoring would be more lenient.

Step 16: A. NumDigits

Picture of A. NumDigits

The first function, NumDigits, is designed to determine the number of digits within the highest number the user wishes to guess to.

Step 1: Initialize the NumDigits function and initialize the number parameter.

Step 17: B. NumDigits

Picture of B. NumDigits

Step 2: Initialize the variable counter at zero.

Note: This prevents the compiler assigning a random value in this variable before the calculations are conducted in this variable.

Step 18: C. NumDigits

Picture of C. NumDigits

Note: A while loop is needed to calculate how many digits are in the highest number to guess to. One way to accomplish this is to do a while loop with the conditions of the number not equal to (in C, is written as “!=”) 0. Mathematically, if a number is divided by 10 until it reaches 0, then the number of digits in this number will be the result. With this being said, inside of the while loop, the number will be divided by 10 and the count will increase by 1 every time this occurs until the number is 0.

Step 3: Create while loop with the conditions of number not equal to 0.

Step 4: In the loop, take the number and divide it by 10.

Note: If the symbols do not look familiar to you, review the introduction.

Step 5: Increment the variable count by 1.

Note: If the symbols do not look familiar to you, review the introduction.

Step 19: D. NumDigits

Picture of D. NumDigits

Step 6: Return the variable count.

Note: The finished product of this function should look like the second picture.

Step 20: A. NumPoints

Picture of A. NumPoints

The second function, numPoints, goes off of the idea that depending on how much time the user takes to guess and if the answer is correct - points awarded to the user. The scoring of the game is based on if the user guesses in 1 second and gets the correct answer, the points awarded will be 10. However, if the user takes 10 seconds to guess and guesses correctly, 1 point will be awarded.

Step 1: Initialize numPoints

Step 2: Initialize the variable timesec as a double in the parameters of the function.

Step 21: B. NumPoints

Picture of B. NumPoints

Note: In order to calculate the points the user earned, if and else if statements will be implemented. If you need to review if statements, refer to the introduction.

Step 3: Create if and else if statements for timesec from 1 to 10. To each corresponding timesec, return it’s appropriate score.

After viewing the first picture:

Note: Since timsec is a double variable, the time must be rounded to a single digit number and the less than symbol accomplishes this. Near the end of the function, if the timesec is less than or equal to 10, it returns 1 however, if the timesec is greater than 10, the score returned is 0.

Note: The third picture is a continuation of the second picture.

Step 22: Main

Picture of Main

The Main function of a program is what ties all the separate functions together. It tells the computer what order to call the functions so that the result is a cohesive program.

Part 1:

In this function, after declaring our Choice variable, we first call the MainMenu function. Recall that this prints a menu out to the terminal. The GetChoice function follows, reading in and storing the option that a user selects from the menu.

Part 2:

Next we have a while loop, which will continue looping until the user chooses choice 3 and quits the game.

If the user selects choice 1 or choice 2, the program will call the function(s) listed within the if-else statement, and will exit the if-else statement.

After the if-else statement ends, MainMenu and the GetChoice function are called, where the user can make another selection.

This process will continue repeating until the user selects choice 3, which will then cause the program to end thanks to the Quit function.

Part 3:

Finally we finish with a “return 0” and the closing bracket to the main function. The “return 0” is the standard return value for main functions and will allow the program to end if the while loop were to fail for any reason.

Step 23: Building and Running

Picture of Building and Running

Many errors may occur once you attempt to compile your program.

Syntax errors occur when the rules of C programming are not followed. Semantic errors occur when the written program is not meaningful. Logical errors are not determined by the IDE, but by the programmer. These errors occur when something not wanted is printed to the terminal. Make sure to double check that every semicolon is placed where it needs to be. Also, check each open bracket to make sure it has a matching closing bracket.

Look at the function NumDigits as shown in Picture 1.

As you can see, the brackets (surrounded by green boxes), which represent the scope of the entire function, are matched to only include the body of the function. The lines of code initializing and manipulating variables all end with “;”(as demonstrated by the red box).

If the import libraries are not included at the top of the file, the program will not run (Picture 2).

It is also imperative that everything is spelled correctly. If you choose to make different function or variable names that is fine, as long as it is implemented with the same name throughout the program.

To compile the program, Select Build - Build and Run (Picture 3).

A command prompt will appear (Picture 4).

At this prompt the user can choose 3 options.
By simply typing your choice followed by enter; the prompt will continue to run through the program. Follow through the program, answering each question by digits and enter. Once the number is guessed, the main menu will pop back up, prompting a number 1-3 again. Congratulations on making your program!

Comments

grayl (author)2016-03-29

Step 7: Don't you mean:

Choice > min || Choice < max ??

Group1ENC (author)grayl2016-03-30

The while loop is used to continue looping until a valid choice is entered.

So if Choice < min or Choice > max, it is out of range and is not a valid selection, so we want to prompt the user to enter a valid selection.

Once choice >= min and Choice <= max, the condition in the while loop will be false.

The code will then continue on to the next statement in the function, which is "return Choice", which will then return the user's choice for other functions to use.

grayl (author)Group1ENC2016-03-30

Right. I'm used to ANDs in Do/While Loops, not ORs. Good Ible.

wold630 (author)2016-03-27

Thanks for sharing all of these detailed steps for beginners!

About This Instructable

4,255views

212favorites

License:

More by Group1ENC:C For Beginners: Functions/Loops: Guessing Game
Add instructable to: