A program = data + instructions
Data:
Instructions:
Sample C++ program
#include <iostream> // a. using namespace std; // b. int main() // c. { int num1, num2; // d. num1 = 10; // e. num2 = 15; num1 = num1 + num2; // f. cout << "Sum is: " << num1; // g. return 0; // h. }
Notes:
Program Error Types
1. Compile error - invalid C++ statements; so your code cannot be translated to machine language. Examples:
In example 1 you must use int, not integer.
In example 2 the ; at the end of the line is missing
2. Link error: one of the functions used in the program is not found when it's time to run the program. In the program above, there are no such functions, but we could encounter this problem later.
3. Run-time error - program does not run to completion. Example:
4. Logic error - program runs to completion, but the results are wrong. Example:
Fixing 3 and 4 is called debugging.
You must learn to understand that the computer did what you said, not necessarily what you meant.
The C++ Language - Introduction
Note: C++ is a superset of the C programming language. Any C code is also C++ code, but some C++ code is not C. Much of what you learn in this course could also be used in a C program. There are lots of new features and capabilities in C++. We will learn some of them (but far from all of them) in this course.
The C++ Language is made up of
These programmer-defined names:
C++ Data Types
Each data item has a type and a name chosen by the programmer.
The type determines the range of possible values it can hold as well
as the operations that can be used on it. For example, you can add
a number to a numeric data type, but you cannot add a number to someone's name.
(What would "Joe" + 1 mean?)
Three commonly-used data types
1. int (integer numbers)
To make a variable that your program can use, you must declare it.
Declaration Examples:
int x; // gives type and name; no value yet
int x, y; // declares 2 ints; no values yet
int population = 16000; // declares & sets init value
So you could picture the results of the last two lines as:
x
|
y
|
population
|
Note: It is critically important that variables have values before they are used in a program. In the examples above, x and y have no values even though they have been declared. More accurately, they do have values but those values could be anything between -2 billion and +2 billion. Before you use x or y you would have to give them values (perhaps as shown in the first program example.)
2 and 3. float and double (floating point or real numbers). These data types are also commonly referred to as real variables (following mathematics usage) when it is not important which one we mean and we don't want to always have to say "float or double".
Declaration Examples:
float pi = 3.1416; //declares, names, sets init value
double x = 3.5, //note comma here
y = 1245.6543; //can use > 6 digits
OR
double x = 3.5; double y = 1245.6543; float big = 5.28e3; // exponential notation: 5280
4. char (single characters)
Declaration examples:
char ch;
char choice = 'q';
5. string (character "strings" or sequences)
Declaration Examples:
string s; string MyName = "Jim";
Arithmetic Operations and Examples
The arithmetic operators are:
Note: there is no exponentiation operator.
| Notes on Division: Recall 3rd grade division: 3 R1
_______ 4 is divisor
4| 13 13 is dividend
12 3 is quotient
1 1 is remainder
In C++, a division with 2 int operands has an int resulting value: 13/4 --> 3 // int quotient 13%4 --> 1 // int remainder But with 1 or 2 float/double operands, the resulting value is a float or double: So: 13.0 / 4 --> 3.25
13 / 4.0 --> 3.25
Be aware. Forgetting this can easily cause a Logic Error. What is the % operator good for? Examples: 1. we can use the % operator to find if one number evenly divides another: Is 1966 a leap year? Yes, if 1966 % 4 is 0 Is the value in the int variable num even or not? It is even if the value of num % 2 is 0. We'll learn exactly how to code the test later. |
Arithmetic Expressions are formed by operands and operators. Operands are the values used, operators are the things done to the numbers. Parts of arithmetic expressions are often grouped by () for clarity or to affect the meaning of the expression:
// declare: int x, y; double realnum; // initialize x = 11; y = 2; realnum = 2.0;
| expression | value | notes |
| x + y | 13 | |
| x * y | 22 | |
| x * y + x | 33 | |
| x - y | 9 | |
| -x + y | -9 | unary negation: "minus x" |
| x / y | 5 | int since both ops are int |
| x % y | 1 | rem when x divided by y |
| x / realnum | 5.5 | one op is real so result is real |
Note that the expressions above by themselves are not valid C++ statements - they would be part of a statement. But each expression (if it is in a valid statement) has a value.
Also - the spaces written between operands and operators are not required by C++, but do improve legibility.
More complex expressions are evaluated by C++ using Rules of Precedence (like algebra)
1. sub-expressions in ()
2. unary -
3. * and / - left to right
4. + and - - left to right
In the examples below, the red numbers show what operation is done as C++ evaluates and expression:
So: 3 + 5 * 4 / 2 =
3 + 20 / 2 =
3 + 10 =
13
But () can be used to change this (or to make expression more readable)
(3 + 5) * 4 / 2 =
8 * 4 / 2 =
32 / 2 =
16
Example 1:
Suppose you accumulate 5 int test scores in sum.
And suppose that sum is 104.
Then to write an expression that is the average, you could write:
sum/5
and the value of that expression is 20 (a bit wrong - we lost the decimal fraction .8)
But if you write:
sum/5.0
Then the value of the expression is 20.8 (correct)
Example 2:
Suppose you don't know how many numbers there are when you write the program. So you can't use 5 or 5.0 because there might be 21 or 3 or 97 numbers. You could use a variable to hold the count of numbers: declare int count and write some instructions that will give it the proper value before you want to calculate the average. We'll see how to do this soon.
You can't write "Count.0" to force it to be real (like we wrote 5.0 above). C++ simply does not allow this.
You must use a type cast - to tell C++ that it should temporarily use the variable as if it were some other data type. To do this, put the name of the data type you want in parenthesis before the variable name. It will not change the variable type or value permanently, but it will force C++ to temporarily treat the variable as a different type:
(double) sum/count // or sum /(double)count
(It is true that we could avoid the need to type cast here by declaring count to be double instead of int. But there are other situations where you will either want or need to do this.)
You cannot do just any type cast: (char) sum would not make sense and would not compile.
Assignment Statement/Operation
The symbol "=" is a command.
It means: "evaluate the expression on the right and store this value in the variable on the left"
Memorize that sentence.
In general:
someVariable = some expression;
Examples:
x = y * 3;
x = x + y;
Notice that there is always exactly one variable on the left to receive the value of the expression on the left.
This is NOT like algebra; it is NOT an equation.
Algebra: x = 1 (T or F for a given x) C++: x = 1; // store 1 into x Algebra: x = x + 1 (false for all x) C++: x = x + 1; //find x+1; result in x
More Assignment Examples
//-- declare vars double dAns; int iAns; int i, j; double x, y; //-- assign values via numeric literals i = 5; j = 8; x = 4.0; y = 1.5; //-- assign values from complex expressions i = i + 2; // 7 dAns = x / y; // 2.666.. iAns = j/2*2; // 8/2*2 = 4*2 = 8 iAns = 8/5; // 1 iAns = 8 % 5; // 3 iAns = 5 / 8; // 0 iAns = 5 % 8; // 5 i = x/y; // 2
The last needs an explanation. the value of the expression x/y is 2.666.. but i is an int variable and so cannot hold the .666 part. C++ simply drops it (truncates it) and so only the whole number part of the value is stored into i.
Notes:
1. All variables in expressions on the right must have defined values or you get random
results. This is an example of what I meant before when I said variables must have
values before they are used.
int x, y; // declared; no init values x = y + 1; // ??? in x
int x; // declared; no init value int y = 2; // declared; given a value x = y + 1; // x has value 3. // It is Ok if x has no value before this
Inadvertant use of uninitialized variables is one of the most common causes of program errors. Learn to be very careful about this.
2. You can do multiple assignments on one line:
x = y = z = 3; //all get value 3
3. Naming Variables: use meaningful names that explain themselves to reader of the program. (You, me, the maintainer of the program after you go to your next job...)
No Yes s score cs class_size ClassSize classSize cav class_average ClassAvg classAvg num student_count NumStudents numStudents stnum student_id StudentID studentID
Input
We will use the standard C++ library input and output features.
For now we will use cin for input. cin's task is to accept user input and store it into variables.
Note that
So typically we will do something like this:
int i; // a.
...
cout << "Enter the temperature: "; // b.
cin >> i; // c.
Notes:
Output
We will use cout for output. cout's task is to display information on the screen.
As shown above, the simplest form of cout is:
cout << "Hello";
You can output (for display) several values, including the values calculated and stored into variables, by stringing them together connected by "<<":
cout << "The average is: " << avg; // avg is a variablecout << "The temperature is: " << temp << " and the rainfall today was: " << rainAmt;
Note that I have put each item to display on a separate line for clarity. This is both legal and is usually desirable if you have more than 2 values.
There are a couple of special techniques to position cursor before or after you display characters, using an escape sequence. (A \ followed by a char. For example, \n is the newline escape sequence.) Note that this is a backslash.
cout << "\nhello"; //moves to next line, shows hello cout << "hello\n"; //shows hello, then goes to new line cout << "hel\nlo"; //shows hel, then lo on next line
Note: to display a single \, you must code two: \\
cout << "the \\ char is special";
This shows: "the \ char is special"
Also, there is an alternate way to move the cursor to the beginning of a new line: the special value "endl":
cout << endl << "Some stuff" << endl;cout << "\nSome stuff\n";
Both will first move the cursor to a new line, then display "Some stuff" and then move the cursor to the next line.
Note that if you don't include endl or \n, all your output will be on one line:
cout << "The average is: " << avg; // avg is a variablecout << "The temperature is: " << temp << " and the rainfall today was: " << rainAmt;
This will display something like this:
The average is 77.5The temperature is: 78 and the rainfall today was: 1.32362