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

How to create a new static library project in Visual C++

From the File menu, select New and then Project…. From the Project types pane, under Visual C++, select Win32. From the Templates pane, select Win32 Console Application. Choose a name for the project, such as MathFuncsLib, and enter it in the Name field. Choose a name for the solution, such as StaticLibrary, and enter it in the Solution Name field. Press OK to start the Win32 application wizard. From the Overview page of the Win32 Application Wizard dialog, press Next. From the Application Settings page of the Win32 Application Wizard, under Application type, select Static library. From the Application Settings page of the Win32 Application Wizard, under Additional options, deselect Pre-compiled header. Press Finish to create the project.

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...

A Window's Instance

When you start an application such as Notepad, you are said to have created an instance of the application. In the same way, when you declare a variable of a class, an instance of the class is created and made available to the project. The WinMain() function also allows you to create an instance of an application, referred to as the hInstance argument of the WinMain() function. The instance is created as an HINSTANCE . The CWinApp class provides a corresponding instance variable called m_hInstance . This variable can let you get a handle to the instance of your application. Alternatively, to get a handle to the instance of your application, you can call the AfxGetInstanceHandle() global function. Its syntax is: HINSTANCE AfxGetInstanceHandle(); Even more, to get a handle to your application, you can call the Win32 API's GetWindowLong() function. Suppose you have opened Notepad to view the source code of an HTML document. This is said that you have an instance of Notepad. Imag...