Interaction

Okay. Here is our second program. This was actually the assignment for project #2 for my first pascal (Introduction to Programming) class:

Write an interactive program that calculates and prints how many total points a basketball team scored in a particular game. The program should ask the user for:

Recall that field goals are worth 2 points, 3-point baskets are worth three and free throws are worth 1 point.

A sample run might look like this:

[screen]
-----------------------------------------------------------
Enter the number of field goals: 32
Enter the number of 3-point baskets: 4
Enter the number of free throws: 11
The team scored a total of 87 points.
$
------------------------------------------------------------

And here's the code to do it in C++.


#include <iostream>

int main()

{   // Start main block

// Declare the integers you'll need for calculations:
   int fieldgoals;   
   int threepoints;
   int freethrows;
   int totalscore; 

// Get user inputs for the variables
   cout << "Enter the number of field goals: ";
   cin >> fieldgoals;

   cout << "Enter the number of 3-point baskets: ";
   cin >> threepoints;

   cout << "Enter the number of free throws: ";
   cin >> freethrows;

// Calculate total

   totalscore = (fieldgoals * 2) + (threepoints * 3) + freethrows;

// Output total   
   cout << "The team scored a total of " << totalscore << " points." << endl;

// Signal successful end to program
   return 0;

}    // End main block

Name this program/project interaction.* Use what you learned in the helloworld to compile and run this program. When you run it, use the same values as in the screen sample and see if your output is correct.

Let's analyze the code a little bit to gain more understanding of what your doing. Here's a breakdown, line by line.

#include <iostream>

By doing an include, you are adding code that has already been written elsewhere. In this case, you are adding the code to access the input/output streams of the OS/Platform that have been already written for you. This is so you don't have to learn the how's of getting characters to the screen or accepting input from the keyboard. I/O streams are absolutely necessary if you wish to get a display to work or input from the keyboard in command line programs such as this. There are literally thousands of existing libraries for use that allow you access to all kinds of functions and abilities to assist you in your programming. Some of these are included with the Standard Template Library, while others are given to you by Be with the BeIDE for accessing specific BeOS things. There are even more available freely on the internet or for purchase through many vendors and third-party commercial software companies.

In almost all older books and in a lot of recent ones, the "header" files are shown using a .h at the end (#include <iostream.h>). This was a legacy of the C standard, but was dropped very recently when C++ finally received its own ANSI/ISO Standard. BeOS R4.5 supports this new standard, although it still allows for the .h method for backwards compatibility. But remember, not all code libraries can be accessed with specifically the old standard or the new standard, depending upon when these libraries were designed. Try the standard one first, and then the older method, if the first fails.

int main()

This is the main function of the program. Every C++ program must have a main function. Program code starts to run at the main function and ends at the main function.

There are three parts to this line, which, by the way, are characteristics of all functions. The return type - in this case main must return type "int"; the name of the function - here it must be named "main"; and arguments to be passed into the function between the parentheses - in this case nothing (), which can also be stated as (void), which also means no arguments.

{   // Start main block

The curly-braces ( { and } ) are required to mark the beginning and the end of blocks of code to be considered a single statement. The main code is the program, and therefore all statements within main should be considered a single statement - i.e., one program. You'll see these curly-braces used for similar purposes later, but for now realize that main needs to use them to mark the beginning and the end of your program code. Without them, the code will not compile.

Note here the use of "//". This, if you haven't guessed already, denotes a comment. There are two forms of comments in C++, "//" which tells the compiler to ignore the rest of that line, and the combination "/*" and "*/" which tells the compiler that when it sees "/*" to ignore everything until it sees the end of comment "*/".

Comments are used so that programmers can annotate in plain english (well, any ASCII-based spoken language, actually) what is happening in the code. This is a good habit to develop. The more detailed the comments are, the easier it is for someone else, or yourself, to figure out what is going on in the code. Even if you never plan on sharing your source code with anyone, notice I also said yourself, because what if you wrote a really cool program, and then a year or so later you want to update it, or say a new version of BeOS, or even port it over to another platform, but you didn't comment it. Now you have to re-figure out all those complicated algorithms and how you implemented them because it had been so long you forgot. It would be much easier if you had commented them. It's also just in good style. Comment your code.

I comment my opening and closing curly-braces always, so I can easily see where and what it begins and ends. It doesn't look bad here, but as code gets more complicated, and the braces are nested within braces within braces, the code gets harder to follow. One forgotten closing curly-brace can spell a whole lot of errors (and head-aches) that you could easily find and avoid if these braces are annotated correctly.

// Define the integers you'll need for calculations:
   int fieldgoals;   
   int threepoints;
   int freethrows;
   int totalscore; 

Here, as the comments annotate, we are defining some variables to be used in the program. Variables are just spaces in memory that are reserved for values that can change throughout the duration that the program runs. There are many types of built in variables. Here we are using "int", integer values. We are defining four integers, and giving these values the names, or more properly, identifying them as, fieldgoals, threepoints, freethrows, and totalscore. You should always use lower case for variables, although a very common practice is to mix uppercase within (but not at the beginning) - for example: int myNewNumberVariable;

Notice here we have semicolons (;) at the end of each line. It is actually marking the end of each statement. Each command in C++ is considered a statement. It is a good practice to only include one statement on each line. Multiple statements can be combined to be "one" statement using the curly-braces, but we'll get into that more later.

When we declare "int fieldgoals;", we are telling the compilier - We are going to need space for an integer, and we'll call that space fieldgoals - end this command. The compilier will actually create the binary code that instructs the OS to make a "space" in memory for an integer and label the space fieldgoals. When the compiler sees the semicolon, it knows that the operation has completed, and will make the binary code reflect that. The compiler will then continue on to the next statement. It's actually quite a bit more complicated than this, but this sums it up a little.

// Get user inputs for the variables
   cout << "Enter the number of field goals: ";

We have seen this before in our first program. Now I will explain it. "cout" is an ostream output stream that the iostream library allows you access to, and will display things to the screen for you. Using the "<<" is actually the extraction function you are calling from the ostream, and it's like saying "the following". The above statement is like saying: display to the screen the following - Enter ... goals: ". Notice that everything that you wish to be displayed on the screen to be taken literally is within quotations ("). There are exceptions to this literal, but we won't get into that yet. I've placed an extra space at the end of what I want to appear on the screen so that when the user enters their input, it is not squished up right next to my output.

You also remember that in the helloworld program we did before, you can concatenate these "<<" to do multiple outputs in one statement.

cout << "Helloworld" << endl;  

The endl tells the OS to flush the display buffer at that moment (sometimes the OS will wait, and if the program exits, it will not ever be displayed). This also will place the screen's cursor to the next line of the screen.

   cin >> fieldgoals;

"cin" is another "stream" of the iostream library, the istream (input stream) that accepts input from the keyboard. You're basically telling the OS to take whatever the user inputs at the keyboard and feed it to the program, and the program will put the input into the memory space created by the variable declarations. The user's input is fed from the keyboard's buffer when the user presses the enter key. This is not always the case, but that is a topic for later.

   cout << "Enter the number of 3-point baskets: ";
   cin >> threepoints;

   cout << "Enter the number of free throws: ";
   cin >> freethrows;

Repeating the above and placing the input into the related variables.

// Calculate total
   totalscore = (fieldgoals * 2) + (threepoints * 3) + freethrows;

Okay, now with some math operations. Computers follow pretty much the same order of operations that we do (yeah, try to remember those algebra classes now :). But now there are more, which we will get into in the following lessons. Here, what you need to know is that you are taking fieldgoals and multiplying it by 2 and threepoints and multiplying it by 3 - muliplication and division before addition and subtraction, remember? Actually this operation was performed because of the parentheses. The compiler will evaluate the expressions within parenthesis first. After those number within the parenthesis have been evaluated, the 2 new numbers just evaluated and freethrows are added together and the sum is placed into the totalscore variable.

A note to point out: only totalscore's value has changed. No operations were actually conducted on the other three variables, therefore the values contained within all three of the variables have not changed after this operation.

// Output total   
   cout << "The team scored a total of " << totalscore << " points." << endl;

Concatenation of cout - display all within the quotations, then display the value stored in totalscore, then more text between the quotations, and then flush the display buffer and send the cursor to the beginning of the next line on the screen.

// Signal successful end to program
   return 0;

You must end your main with a "return 0". This tells the OS that the program has finished executing successfully. Without, the OS will think that the program did not complete successfully. In other functions (not main) you can return different types, int, float, char, boolean, etc, or nothing at all. But main must return the value 0 of an integer type. This was decided long ago by those who developed the standards.

}    // End main block

Here we just close out the main function's code block and end the program's code.

If you understood this page well enough, and think you have a good understanding of each line of code for this program, move on to more.

If things are a bit cloudy still, don't worry. Just study this page and its contents one more time, and it should come to you.

And now on to the first of more arithmetic problems.