Skip to main content

Decomposing makes everything easier...

Time for us to start writing computer games! This first one will be a bit simple, but it's a start. Our task is to write a program that implements a guessing game. Our program generates a random number between 0 and 100. The player must guess the secret number. The program provides hints like "that's too high" or "that's too low" until the player finally guesses the secret number.
We will work on this game in three steps. 
  1. Figure out how to generate a random number within a given range of values.
  2. Create a main function that processes one guess from the player, and provides hints.
  3. Add what we need to allow for multiple guesses until the player guesses the number.
This process of development is called decomposition, which means breaking a task into sub-tasks, each of which is easy to do. Starting with step 1, do a Google search to see how to generate a random number using C++. Try searching on "rand C++".

// random.cpp.  Maggie Johnson
// Description: Illustrates how to generate a random number in Visual C++

#include <iostream>
#include <time.h>
using namespace std;
int main () {
  int random_number;
  // Initialize random seed.
  srand (time(NULL));
  // Generate random number between 1 and 100
  random_number = rand() % 100 + 1;
  cout << "Your random number:" << random_number << endl;
  system("pause");
}

For step 2, we need to receive an integer input from the player (with appropriate error-checking on cin), and check it against the secret number. Try and write this part of the game yourself before checking our solution.

// guess.cpp.  Maggie Johnson
// Description: A guessing game where the player guesses
// the secret number.

#include <iostream>
#include <time.h>
using namespace std;

int main () {
  int random_number, guess;

  // Initialize random seed.
  srand (time(NULL));

  // Generate random number between 1 and 100
  random_number = rand() % 100 + 1;

  cout << "Guess our number (1 to 100) ";
  if (!(cin >> guess)) {
    cout << "Please enter only numbers" << endl;
  } else {
    if (random_number < guess) cout << "The secret number is lower than " << guess << endl;
    else if (random_number > guess) cout << "The secret number is higher than" << guess << endl;
    else cout << "You guessed it: " << random_number << endl;
  }
  cout << "random: " << random_number << endl;
  return 0;
}


Finally, we need to add a loop that keeps collecting guesses from the player until they finally guess the secret number. After completing this part of the program, you can check our solution.

// guess.cpp.  Maggie Johnson
// Description: A guessing game where the player guesses
// the secret number.

#include <iostream>
#include <time.h>
#include <cstdlib.h>
using namespace std;

int main () {
  int random_number, guess;

  // Initialize random seed.
  srand (time(NULL));

  // Generate random number between 1 and 100
  random_number = rand() % 100 + 1;

  cout << "Guess our number (1 to 100) ";
  do {
    if (!(cin >> guess)) {
      cout << "Please enter only numbers" << endl;
    } else {
      if (random_number < guess) cout << "The secret number is lower than " << guess << endl;
      else if (random_number > guess) cout << "The secret number is higher than " << guess << endl;
    }
  } while (random_number != guess);
  cout << "Congratulations!" <<  endl;
  return 0;
}

Decomposition is one of the most important skills for a programmer to learn. Being able to break a task down into manageable pieces, and then complete one at a time is critical, no matter how big or how small the project. Here are some other opportunities for you to practice decomposition.
  • Many everyday tasks provide opportunities to build skills in decomposition. It might surprise you to discover that your mind just works this way! For example, if I have to clean up a really messy kitchen (perhaps some little girls just baked a cake), I break the tasks down to provide a plan, and to make sure I don't have to re-do work later. I don't want to wash the floor first if there's all kinds of stuff on the counters to clean up - I'll probably have to do the floor again later. So, maybe I put all the ingredients away first; move all the dishes into the sink; clean off the counters; wash the dishes; and finally, clean up the floor. There are other ways to perform this task, but by thinking it through first, it helps me define a plan that will not require re-work.
    Use everyday tasks as examples for developing your decomposition skills. Who knows - it might even make you more efficient around the house!
  • The greatest common divisor of two integers is the largest number that divides them both evenly. For example, gcd(12, 18) = 6, gcd(−4, 14) = 2. The most efficient way to compute gcd is with the Euclidean algorithm. Write a program with a function to compute gcd for two integers. Try doing the function without recursion first - it will help you understand how the algorithm works. Explicitly define your sub-tasks, for example, find the code for the Euclidean algorithm; create a non-recursive function for the algorithm; etc. Here is our solution.
// gcd.cpp, Maggie Johnson
// Description: An implementation of Euclid's algorithm for computing gcd.
// Fundamental idea of Euclid's algorithm (one of the oldest known algorithms)
// for finding the greatest common divisor of two integers:
// gcd(a, 0) = a
// gcd(a, b) = gcd(b, a % b)  // % means modulo, that is, the remainder of a/b.
// For example, gcd(6, 4) = 2; gcd(12, 18) = 6.

#include <iostream>
using namespace std;

// A non-recursive version of Euclid's algorithm
int gcd (int a, int b) {
  int temp;
  while (b != 0) {
    temp = a % b;
    a = b;
    b = temp;
  }
  return(a);
}

int main () {
  int x, y;
  cout << "Enter two integers: ";
  if (!(cin >> x >> y)) {
    cout << "Please enter only integers" << endl;
  } else {
    cout << "gcd(" << x << ", " << y << ") = " << gcd(x,y) << endl;
  }
  return(0);
}

Comments

Popular posts from this blog

Adding Existing Files to a Project

If a file had already been created and exists on a separate folder, drive, directory or project, you can import it and add it to your application. When you decide to add an existing file to a project, because Microsoft Visual Studio allows you a great level of flexibility on the types of files you can add, it is your responsibility to check that the file is valid. If you copy a file from somewhere and paste it in the folder that contains your project, the file is still not considered as part of the project. You must explicitly add it. Before adding an existing file to your project: On the main menu, you can click File -> Add Existing Itemテδ「テ「窶堋ャテつヲ On the main menu, you can also click Project -> Add Existing Itemテδ「テ「窶堋ャテつヲ In the Solution Explorer, you can right-click the name of the project, position your mouse on Add and click Add Existing Itemテδ「テ「窶堋ャテつヲ Any of these actions would open the Add Existing Item dialog box. This requires you to locate the item and select it. O...

Introduction to Microsoft Visual C++/MFC

Microsoft Visual C++ is a programming environment used to create applications for the Microsoft Windows family of operating systems. To use these lessons, you must have installed either Microsoft Visual Studio 2010. Although Microsoft Visual Studio 2010 Professional provides many programming environments for the price of one, in our lessons, we will use it but we will cover only the Microsoft Foundation Class (MFC) library side. After installing it, to use the programming environment, you must first open it. To do that, you would click Start -> (All) Programs -> Microsoft Visual Studio 2010 -> Microsoft Visual Studio 2010. In our lessons, unless used in code, the -> arrow means an action that should follow another. Based on this: Edit -> Copy means click Edit, then click Copy View -> Toolbars -> Custom means click View position the mouse on Toolbars, and then click Custom To start Microsoft Visual C++ or Visual Studio, on the Taskbar, click Start (All) Prog...

Creating a File

Although the most popular files used in Microsoft Visual C++ are header and source files, this IDE allows you to create various other types of files that are not natively C++ types. To create a file, if a project is currently opened: On the main menu, click Project -> Add New Item... This would open the New dialog box from where you can select the desired type of file and click Open. By default, the new file would open in the Source Code Editor. If you want to open the file otherwise, after selecting it in the New dialog box, click the arrow of the Open As combo box. In the Solution Explorer or the Class View, right- click the name of the project, position the mouse of Add, and click the option you want