Here is an example program like we looked at before

1
2
3
4
5
6
7
8
9
10
11
12
13
14

/**
CS-11 Asn 0, helloworld.cpp
Purpose: Prints a message to the screen.
@author Ed Parrish
@version 1.0 8/30/05
*/
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
} // end of main function

Brief Explanation by Line Number

Lines 1-7: comments -- notes to programmers

Line 8: adds a library (pre-written code) to our program

Line 9: all the standard libraries use the std namespace

Line 10: a blank line that we can use anywhere in our programs

Line 11: the main() function where all C++ programs start

Line 12-13: programming statements that give instructions to the computer

Line 14: the end of the main() function followed by another comment

Start your text editor and enter the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

/**
CS-11 Asn 0, helloworld.cpp
Purpose: Prints a message to the screen.
@author Ed Parrish
@version 1.0 8/30/05
*/
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
} // end of main function

If you have problems, ask a classmate or the instructor for help as needed.

Run the code and verify you get the message, "Hello, World!"

$ ./hellome
Hello, World!

Try changing the message to personally greet you with your own name, like the following:

Hello, Ed Parrish!

The code that starts with /** and ends with */ is known as a block comment. Comments are parts of code that are ignored by the compiler. Delete the entire block comment and then recompile and rerun your code.

You should see no change in how your code compiles or runs. If you see a difference, ask a classmate or the instructor for help as needed.

Look at the following line of the code:

} // end of main function

The last part of the line is another type of comment that starts with // and lasts until the end of the line. Delete the comment and then recompile and rerun your code.

You should see no change in how your code compiles or runs. If you see a difference, ask a classmate or the instructor for help as needed.

Remove the directive using namespace std; and then try to recompile the code.

Your program should not compile and you should get an error message. If you have a different experience, ask a classmate or the instructor for help as needed.

Restore the directive using namespace std; back into your program and verify that it compiles.

If you have problems, ask a classmate or the instructor for help as needed.

Let us pretend that we have a friend, named Grace, and we want to remember her phone number: 555-2368

We can store our friend's phone number in our memory

We even label our friend's phone number, like "Grace's phone number"

We do not really know where in our brain we store Grace's phone number

However, whenever we need her phone number, we say to our self, "What is Grace's phone number" and out pops 555-2368

Just like we store our friend's number in our memory, we can store it in a computer's memory

We store data in a computer program using a variable

variable: the name of a place to store data in a computer's memory

Just like we do not know where in our brain we store a phone number, we do not know where in computer memory we store data

We simply give it a name and let the compiler decide where to store the data

Why Data Matters

Why should we care about variables or storing data?

Variables are the most important part of any computer program

Just like in real life, it is hard to do anything without memory

Consider a simple algorithm like adding two numbers:

Get the first number

Get the second number

Add the first and second number and assign it to sum

Display that sum is the result

How many variables did we need for this algorithm?

To find out, let us do some role playing

Imagine a conversation between Hal and Grace:

Hal: Hey Grace, I just learned to add two numbers together.
Grace: w00t!
Hal: Give me the first number.
Grace: 2
Hal: OK, give me the second number.
Grace: 3
Hal: OK, the answer for 2 + 3 is 5

After Grace says, "2", Hal has to store the number in his memory

The same things happens with the number, "3"

Even if the numbers were given in the same sentence, Hal would have to store the numbers somewhere in his memory

After adding the two numbers together, Hal has to store the result of the addition, at least temporarily, so he can state the answer

If we were to write a program to add two numbers together, the computer would have to use memory just like Hal

Check Yourself

The name of a location to store data in a computer's memory is known as a(n) ________.

True or false: remembering data is rarely important when processing information.

To add two numbers, we need to store at least ________ pieces of information.

In this exercise we will write a program to add two numbers together. When it runs, the program acts like this:

Enter the first number: 2
Enter the second number: 3
The sum of 2 and 3 is 5.

Make sure to compile after each step so you know where an error is located if you make a mistake.

Specifications

Copy the following program into a text editor, save it as variables.cpp, and then compile and run the starter program to make sure you copied it correctly.

#include <iostream>
using namespace std;
int main() {
// Input first variable
// Input second variable
// Calculate sum
return 0;
}

In main(), declare an int variable named num1 and assign it a value of 0:

Through the miracles of computer science, we will now convert your $500 computer into a $5 calculator! Along the way, we learn how to work with arithmetic using C++.

Specifications

Type the following program into a text editor, save it as arithmetic.cpp, and then compile and run the starter program to make sure you typed it correctly.

Within the curly braces of the main() function, declare two double variables named a and b, and assign them a value of 5 and 2 respectively. For instance:

double a = 5, b = 2;

Add a line of code to display the arithmetic expression (a + b) and then recompile and run the program.

cout << "a + b = " << a + b << endl;

Notice that the last letter on endl is a lower-case "L", NOT a one. The output when you run the program should look like this:

a + b = 7

If you do not see this output, please ask a classmate or the instructor for help.

Add three more lines of code like the previous one that computes the expressions: a - b, a * b and a / b. Compile and run your program again and make sure your program now displays the following output:

a + b = 7
a - b = 3
a * b = 10
a / b = 2.5

The order of operations matters in C++ just like it does in algebra. Multiplication and division are performed before addition and subtraction. Add the following two statements to your program:

cout << "a + b / 2 = " << a + b / 2 << endl;
cout << "(a + b) / 2 = " << (a + b) / 2 << endl;

Compile and run your program again and compare the output. Your program should now display the following output:

a + b = 7
a - b = 3
a * b = 10
a / b = 2.5
a + b / 2 = 6
(a + b) / 2 = 3.5

Note how the output of the two statements is different. You can change the order of operation using parenthesis, just like in algebra. For more information on the order of operations see section: 2.3.2: Arithmetic.

As you can see, arithmetic in C++ works much like you would expect. However, there are some mysteries when working with integer variables which we will explore in the next section:

Truncation in integer division

Modulus (%) operator

Save your arithmetic.cpp file as we will add to it in the following sections.

In this exercise we use integer division, modulus, and mathematical functions to create a deluxe calculator.

Specifications

Start with your arithmetic.cpp code from the last Exercise.

Integer Division: Modify your arithmetic.cpp code from the last Exercise by changing the data type of the two variables from double to int, like this:

int a = 5, b = 2;

Compile and run your program again and compare the output. Note how the result of the division operation changed. What happened to the decimal part of the result?

In programming terms, we say that the decimal part is truncated (cut short). We have to watch out for this in C++ programming or we may get unexpected results in our calculations.

Modulus (%) operator: Sometimes we want the integer remainder from an integer division. To see the integer remainder, we use the modulus (%) operator. Add the following statements to your program:

cout << "a % b = " << a % b << endl;
cout << "a / b % b = " << a / b % b << endl;
cout << "a / (b * b) = " << a / (b * b) << endl;

Compile and run your program again with this added statement. Your program should now display the following output:

a + b = 7
a - b = 3
a * b = 10
a / b = 2
a + b / 2 = 6
(a + b) / 2 = 3
a % b = 1
a / b % b = 0
a / (b * b) = 1

Mathematical functions: More complex mathematical operations require the use of a function in C++. One such function is sqrt(number) which calculates the square root of the number inside the parenthesis.

Add the following statement to your program:

cout << "sqrt(a + b) = " << sqrt(a + b) << endl;

You program will not compile with this new statement because you must include a library of the mathematical functions. Add the statement: #include <cmath> to the top of your program like this:

#include <iostream>
#include <cmath> // math function library
using namespace std;

Compile and run your program again with this added statement. Your program should now compile and display the following output when run:

a + b = 7
a - b = 3
a * b = 10
a / b = 2
a + b / 2 = 6
(a + b) / 2 = 3
a % b = 1
a / b % b = 0
a / (b * b) = 1
sqrt(a + b) = 2.64575

Save your program source code that displays all ten (10) calculator operations so you can submit it to Canvas as part of assignment 2.

When completed, please help those around you. Then compare your code to the example below. Your code need not be exactly the same but it is helpful to see other solutions after you have solved the problem yourself.

Completed Program

Discussion Questions

How natural does arithmetic seem in C++ compared to what you normally use?

A mathematical function has an input and an output. What is the input and output of the C++ sqrt() function?

To help us understand the development process we have an example problem

Write a program that asks the user for a number. The program then displays twice that number.

The input and output of the program looks like:

Enter a number: 10
Twice that number is: 20

In the above example run, the users entered the value shown in aqua italics (for emphasis) to produce the output. Your program does NOT print the characters in aqua italics, nor does the user input appear in aqua italics.

As a first step, spend two minutes to open a text editor and rewrite the problem in your own words.

Save the text of your example problem rewrite in a file named "plan.txt".

Be prepared to share your problem rewrite with the class.

Check Yourself

The first step to understand a problem, as assigned in this course, is to ________.

restate the problem in your own words

identify the inputs and outputs

determine if starter code was provided

read the directions

The first step in problem solving is ________.

To write the expression that calculates the answer

To understand the problem and its inputs and outputs

To do examples by hand that confirm the solution will work

To write C++ code that can be executed and tested

Useful questions to ask while trying to understand a problem include ________.

What are you asked to find or output?

Is this problem similar to something covered in the lesson?

What input is needed?

all of these

The reason to restate the problem in your own words is because ________.

to correct grammar errors in the problem statement

the original words may not be an optimal statement of the problem

restating the problem in your own words guarantees that the code will be correct in most cases

if you cannot restate a problem, it is unlikely you will be able to write code to solve it

Our goal for the plan is to design an algorithm for a computer

An example algorithm:

Computer algorithm to square any number:
1. output "Enter a number"
2. input number
3. x = number * number
4. output "The square of the number is "
5. output x

Notice that the steps are combinations of input, processing (calculation), storage, and output

There are many reasonable ways to solve problems and generate algorithms

The following is a partial list of strategies

Problem Solving Strategies

Make an orderly list of steps

Draw a diagram or picture

Look for a pattern

Use a formula

Compare to a previously solved problem

Eliminate possibilities

Work backwards (output, processing and storage, input)

Break into smaller pieces and solve one small part at a time

Solve an equivalent problem

Guess and check

Writing and Checking the Plan

Once we have a plan we write down the steps

Write each step on its own line like the example algorithm above

Make sure the plan has steps for:

input

storage

processing

output

Check the plan by working out an example

Computer algorithm to square any number:
1. output "Enter a number"
2. input number (example: 10)
3. x = number * number (10 x 10 is 100)
4. output "The square of the number is "
5. output x (x is 100)

If you do not get the correct result then revise the algorithm

In this section we look at translating to code and perfecting the plan

When writing software, always start with something that compiles and runs

As an example, start with the following code that compiles and runs

1
2
3
4
5
6
7
8
9
10
11
12
13
14

/**
CS-11 Asn 0, program.cpp
Purpose: Your problem restatement here.
@author Your name
@version 1.0 Today's date
*/
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!\n";
return 0;
}

/**
A very erroneous program.
@author B. A. Ware
@version 1.0 1/25/05
#include <iostrea m>
using namespace standard;
/**
* The main functoin for the program.
*/
int main() {
cout <<< "Hell out there.\";
cout << "Enter a number as a percent: "
cin << ware;
Cout << "As a double the number is: ";
cout << ware / 00 << end1;
return;
}} / / end of main

Find a partner for this exercise and create a text file named errors.txt

Add a comment at the top of the file that contains the name of the person(s) with whom you reviewed the code, like:

// Reviewed with Emma Programmer

With your partner, review the program, finding and listing in your errors.txt file the line number and description of as many errors as you can within 3 minutes. For example:

// Reviewed with Emma Programmer
Line 6: missing closing comment symbols
Line 7: space in iostream
(more errors listed)

Submit your list of errors to Canvas as part of next weeks assignment.