Saturday, September 1, 2012

Pete and Repeat Part 2

As the nursery riddle goes, Pete and Repeat were sitting on a fence. Pete fell off. Who was left? (Repeat riddle). Like the riddle, this week's lab is once again centered around repetition.

For this lab, we will use the while and for loop constructs to allow us to repeat instructions based on some condition. This will come in handy when working with a collection of data, so we will encorporate the vector data structure as a container for our collection. We will create an application to track the scores of players on a team. The scores of all of the players will be summed together and the total team score will be displayed. As usual, we will use classes and functions as part of the implementation.

Quick Review

First, let's review the steps to creating a program. Each step listed is a hyperlink that will take you to the instructions and examples for each step. Use your browser's back button to return to this page for links that take you to another page.

Getting Started

  1. Create a new project in your IDE.
    Visual Studio project
    Eclipse project
  2. Create a header file (for your class) and client file (for your main function) and include them in your IDE project
    Visual Studio header file
    Eclipse header file
  3. Create your class in the header file
  4. Write the code for your client (main) function
  5. Run your program often and resolve errors as they happen

Create Your Class


#include <iostream>
#include <string>
#include <vector>

class scores
{
public:
    void loadScores();
    void displayScores();
private:
    std::vector<int> stats;

};

Here is most of the code for the functions you'll need:
void scores::loadScores()
{
    int points;
    int n = 1;

    std::cout <<"Enter score for player " << n <<" (0 to quit):";
    while(std::cin >> points && points !=0)
    {
        n++;
        std::cout << "Enter score for player " << n << " (0 to quit):";
        stats.push_back(points);
    }
}
void scores::displayScores()
{
    int total = 0;
    for (int i = 0; i < stats.size(); i++)
    {
	std::cout << stats[i] << std::endl;
	total = total + stats[i];
    }
     //display the total
}


Here is an example of what the output might look like for this application.

Write the code for your client (main) function

Remember how to create an object of your class and call the class functions? If not, review the Hello World example, then try it on your own for this class. Here are the steps you'll need:

  1. Declare the class type and give the object a name (remember the semicolon).
  2. Use the object name followed by a dot and the function name you want to call (remember the open and closed parens and the semicolon at the end).

Here's a link to the example from last week: helloworld main function