Chapter 02 - Introduction To C++ Programming
Chapter 02 - Introduction To C++ Programming
1
2
3
2.1 Introduction
4
2.2 First Program in C++:
Printing a Line of Text
We begin with our first program
◦ Simple program that prints a line of text
5
1 // Fig. 2.1: fig02_01.cpp
2 // Text-printing program
3 #include <iostream>
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome to C++! \n"; // display message
9
10 return 0; // indicate that program ended successfully
11 } // end function main
6
2.2 First Program in C++:
Printing a Line of Text (cont.)
// indicates that the remainder of each line is a comment
◦ You insert comments to document your programs and
◦ To help other people read and understand your code
◦ Comments are ignored by the C++ compiler, thus it does not cause
the computer to perform any action
A comment line that begins with // is called single-line
comment because it terminates at the end of the current line
Multiple-line comment begins with /* and ends with */
7
2.2 First Program in C++:
Printing a Line of Text (cont.)
Lines beginning with # are preprocessor directives
Lines that begin with # are processed by the preprocessor
before the program is compiled
#include <iostream>
◦ Notifies the preprocessor to include in your program the
contents of the input/output stream header file <iostream>
9
2.2 First Program in C++:
Printing a Line of Text (cont.)
You use blank lines, space characters and tab characters (i.e.,
“tabs”) to make programs easier to read
◦ Together, these characters are known as white space
◦ White-space characters are ignored by the compiler
11
2.2 First Program in C++:
Printing a Line of Text (cont.)
main is a part of every C++ program
C++ programs begin executing at function main, even if main
is not the first function defined in the program
The parentheses after main indicate that main is a building
block called a function
C++ programs typically consist of one or more functions and
classes
Exactly one function in every program must be named main
12
2.2 First Program in C++:
Printing a Line of Text (cont.)
The keyword int to the left of main indicates that main
“returns” an integer (whole number) value
◦ A keyword is a word that is reserved by C++ compiler for a
specific use
◦ For now, simply include the keyword int to the left of main in
each of your programs
13
2.2 First Program in C++:
Printing a Line of Text (cont.)
A left brace { must begin the body of every function
A corresponding right brace } must end each function’s body
14
2.2 First Program in C++:
Printing a Line of Text (cont.)
A statement instructs the computer to perform an action
We refer to characters between double quotation marks simply
as strings
◦ White-space characters in strings are not ignored by the compiler
Most C++ statements end with a semicolon (;), also known as
the statement terminator
◦ Preprocessing directives (like #include) do not end with a
semicolon
15
2.2 First Program in C++:
Printing a Line of Text (cont.)
Typically, output and input in C++ are accomplished with streams
of data
When a cout statement executes, it sends a stream of characters
to the standard output stream object, std::cout
◦ Which is directly “connected” to the screen
◦ The std:: before cout is required when we use names that we’ve
brought into the program by #include <iostream>
◦ The notation std::cout specifies that we are using a name, in
this case cout, that belongs to “namespace” std
◦ The names cin (standard input stream object) and cerr (the
standard error stream object) also belong to namespace std
19
2.2 First Program in C++:
Printing a Line of Text (cont.)
In the context of an output statement, the << operator is referred to
as the stream insertion operator
◦ It takes the value of its right operand and inserts it to the left
operand, i.e. the output stream
◦ The characters \n are not printed on the screen
◦ The backslash (\) is called an escape character
◦ It indicates that a “special” character is to be outputed
◦ When a backslash is encountered in a string of characters, the next
character is combined with the backslash to form an escape sequence
◦ The escape sequence \n means newline, i.e. causes the cursor to
move to the beginning of the next line on the screen
20
21
2.2 First Program in C++:
Printing a Line of Text (cont.)
When the return statement is used at the end of main the
value 0 indicates that the program has terminated successfully
According to the C++ standard, if program execution reaches
the end of main without encountering a return statement,
it’s assumed that the program terminated successfully
Exactly as when the last statement in main is a return
statement with the value 0
22
2.3 Modifying Our First C++ Program
23
1 // Fig. 2.3: fig02_03.cpp
2 // Printing a line of text with multiple statements
3 #include <iostream>
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome ";
9 std::cout << "to C++! \n"; // display message
10
11 return 0; // indicate that program ended successfully
12 } // end function main
24
2.3 Modifying Our First C++ Program
25
1 // Fig. 2.4: fig02_04.cpp
2 // Printing multiple lines of text with single statement
3 #include <iostream>
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome\nto\n\nC++!\n"; // display message
9
10 return 0; // indicate that program ended successfully
11 } // end function main
26
2.4 Another C++ Program: Adding Integers
27
1 // Fig. 2.5: fig02_05.cpp: addition program RAM
2 // that displays the sum of two integers
3 #include <iostream>
4 num1 0
int main() {
5 // declaring and initializing variables
num2 0
6 int num1{0}; // initialized to 0
7 int num2{0}; // initialized to 0 sum 0
8 int sum{0}; // initialized to 0
9
10 std::cout << "Enter first integer: "; // prompt user
11 std::cin >> num1; // read first integer from user
12 std::cout << "Enter second integer: "; // prompt user
13 std::cin >> num2; // read second integer from user
14
15 sum = num1 + num2; // add numbers, store result in sum
16 std::cout << "Sum is " << sum << std::endl; // display sum
17 return 0;
18 } 28
2.4 Another C++ Program:
Adding Integers (cont.)
Declarations introduce identifiers into programs
The identifiers num1, num2, & sum are the names of variables
A variable is a location in the computer’s memory where a
value can be stored for use by a program
Variables num1, num2, and sum are data of type int
Meaning that these variables will hold only integers
◦ Whole numbers such as 7, –11, 0 and 31914
29
2.4 Another C++ Program:
Adding Integers (cont.)
Lines 6–8 initialize each variable to 0 by placing a value in
braces { 0 } immediately following the variable’s name
◦ Known as list initialization
◦ Introduced in C++11
Previously, these declarations would have been written as:
int num1 = 0;
int num2 = 0;
int sum = 0;
30
2.4 Another C++ Program:
Adding Integers (cont.)
All variables must be declared with a name and a data type
before they can be used in a program
If more than one name is declared in a declaration, the names
are separated by commas
This is referred to as a comma-separated list, for example:
int num1, num2, sum;
31
2.4 Another C++ Program:
Adding Integers (cont.)
Data type double is for specifying real numbers
Real numbers are numbers with decimal points, such as 3.14,
0.01 and –11.19
Data type char for specifying character data
char variable can hold only one single character, that can be:
◦ Lowercase letter
◦ Uppercase letter
◦ Digit
◦ Special character (e.g., $, *, @, …)
34
2.4 Another C++ Program:
Adding Integers (cont.)
Data types such as int, double, and char are called
fundamental types
Fundamental-type names are keywords and therefore must
appear in lowercase letters
Appendix C contains the complete list of fundamental types
35
2.4 Another C++ Program:
Adding Integers (cont.)
A variable name is any valid identifier that is not a keyword
An identifier is a series of characters consisting of letters,
digits and underscores ( _ ) that does not begin with a digit
C++ is case sensitive, i.e. uppercase and lowercase letters are
different
◦ So a1 and A1 are different variables
36
2.4 Another C++ Program:
Adding Integers (cont.)
Declarations of variables can be placed almost anywhere in a
program
But variables must be declared before they are used in the
program
41
2.4 Another C++ Program:
Adding Integers (cont.)
A prompt directs the user to take a specific action
A cin statement uses the input stream object cin and the
stream extraction operator >>, to obtain a value from the
keyboard
Using the stream extraction operator with std::cin takes
character input from the standard input stream, which is
usually the keyboard
42
2.4 Another C++ Program:
Adding Integers (cont.)
When the computer executes an input statement that places a
value in an int variable, it waits for the user to enter a value
for variable num1
The user responds by typing the number then pressing the
Enter key to send the value to the computer
The computer assigns this number to the variable num1
Any subsequent references to num1 in this program will use
this value
43
2.4 Another C++ Program:
Adding Integers (cont.)
In this program, an assignment statement adds the values of
variables num1 and num2 and assigns the result to variable
sum using the assignment operator =
◦ Most calculations are performed in assignment statements
The = and the + operator are called binary operators because
each has two operands
44
2.4 Another C++ Program:
Adding Integers (cont.)
std::endl is a so-called stream manipulator
The name endl is an abbreviation for “end line” and belongs
to namespace std
The std::endl stream manipulator outputs a newline, then
“flushes the output buffer”
◦ This simply means that, on some systems where outputs
accumulate in the machine until there are enough to “make it
worthwhile” to display them on the screen, std::endl forces
any accumulated outputs to be displayed at that moment
◦ This can be important when the outputs are prompting the user
for an action, such as entering data
46
2.4 Another C++ Program:
Adding Integers (cont.)
Using multiple stream insertion operators (<<) in a single
statement is referred to as concatenating stream insertion
operations
Calculations can also be performed in output statements
47
2.5 Memory Concepts
48
49
50
51
2.6 Arithmetic
52
53
2.6 Arithmetic
Arithmetic operators
◦ The asterisk (*) indicates multiplication
◦ The / indicates division, however:
◦ Integer division returns an integer quotient/result
◦ Integer division means that both the numerator and the
denominator are integers
◦ Any fractional part in integer division is discarded, i.e. truncated,
no rounding occurs, for example;
int x = 5 / 3; // x has the value 1
int y = 12 / 5; // y has the value 2
54
2.6 Arithmetic
55
2.6 Arithmetic (cont.)
57
58
2.6 Arithmetic (cont.)
59
60
2.7 Decision Making:
Equality and Relational Operators
The if statement allows a program to take alternative action
based on whether a condition is true or false
◦ If the condition is true, the statement in the body of the if
statement is executed
◦ If the condition is false, the body statement is not executed
◦ Conditions in if statements can be formed by using the equality
and relational operators (Fig. 2.12)
◦ The relational operators all have the same level of precedence
and associate left to right
◦ The equality operators both have the same level of precedence,
and associate left to right
61
62
2.7 Decision Making:
Equality and Relational Operators
Fig. 2.12 uses six if statements to compare two numbers
inputted by the user
If the condition in any of these if statements is satisfied
◦ The output statement associated with that if statement will
execute
65
1 // Fig. 2.13: fig02_13.cpp RAM
2 // Comparing integers using if statement with
3 // relational operators and equality operators
4 num1
#include <iostream>
5 using namespace std;
num2
6
7 int main()
8 {
9 // declaring and initializing variables
10 int num1; // 1st integer to compare, initialized to 0
11 int num2; // 2nd integer to compare, initialized to 0
12
13 cout << "Enter two integers to compare: "; // prompt user
14 cin >> num1 >> num2; // read two integers from user
15
16 if (num1 == num2) { // tests if num1 is equal to
17 num2
18 cout << num1 << " == " << num2 << endl;
66
}
19 if (num1 != num2) { // tests if num1 is != from num2
20 cout << num1 << " != " << num2 << endl;
21 }
22 if (num1 < num2) { // tests if num1 is < than num2
23 cout << num1 << " < " << num2 << endl;
24 }
25 if (num1 <= num2) { // tests if num1 is <= to num2
26 cout << num1 << " <= " << num2 << endl;
27 }
28 if (num1 > num2) { // tests if num1 is > than num2
29 cout << num1 << " > " << num2 << endl;
30 }
31 if (num1 >= num2) { // tests if num1 is >= to num2
32 cout << num1 << " >= " << num2 << endl;
33 }
34
35 return 0;
36 } 67
68
2.7 Decision Making:
Equality and Relational Operators
using declarations, eliminate the need to repeat the std::
prefix, so in the remainder of the program you can write
◦ cout instead of std::cout,
◦ cin instead of std::cin and
◦ endl instead of std::endl
Many programmers prefer to use the declaration
using namespace std;
◦ Which enables a programmer to use all the names in any
standard C++ header file, such as <iostream>
69
2.7 Decision Making:
Equality and Relational Operators
Each if statement in Fig. 2.13 has a single statement in its
body and each body statement is indented
Each if statement’s body is enclosed in a pair of braces, { }
◦ Creating what’s called a compound statement or a block that
may contain multiple statements
70
2.7 Decision Making:
Equality and Relational Operators
Figure 2.14 shows the precedence and associativity of the
operators introduced in this chapter
The operators are shown top to bottom in decreasing order
of precedence
All these operators, with the exception of the assignment
operator =, associate from left to right
76
77