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

Creating a Resource

Although an application can use various resources that behave independently of each other, these resources are grouped into a text file that has the .rc extension. You can create this file manually and fill out all necessary parts but it is advantageous to let Microsoft Visual C++ create it for you. To start creating the resources: On the main menu, you can click Project -> Add Resource... In the Solution Explorer, you can right-click the name of the project, position the mouse on Add, and click Resource... Any of these actions would display the Add Resource dialog box. From this dialog box, you would select the type of resource you want and click New (or Import...). You will then be expected to design or customize the resources. Throughout our lessons, we will see various examples. After creating or designing a resource, you must save it. In most cases, you can try closing the resource. In this case, Microsoft Visual C++ would prompt you to save the resource. If you agree to do t...

Overview

In an MFC application, a resource is a text file that allows the compiler to manage such objects as pictures, sounds, mouse cursors, dialog boxes, etc. Microsoft Visual C++ makes creating a resource file particularly easy by providing the necessary tools in the same environment used to program. This means you usually do not have to use an external application to create or configure a resource file (as done in other programming environments).

Converting a Resource Identifier

An identifier is a constant integer whose name usually starts with ID. Although in Win32 programming you usually can use the name of a resource as a string, in MFC applications, resources are usually referred to by their identifier. To make an identifier name (considered a string) recognizable to an MFC (or Win32) function, you use a macro called MAKEINTRESOURCE . Its syntax is: LPTSTR MAKEINTRESOURCE(WORD IDentifier); This macro takes the identifier of the resource and returns a string that is given to the function that called it. In the strict sense, after creating the resource file, it must be compiled to create a new file that has the extension .res. Fortunately, Microsoft Visual C++ automatically compiles the file and links it to the application.