M3
M3
C++ Basics
ENGG1340 COMP2113
Computer Programming II Programming Technologies
3
Important Note: Guidance Notes
• We suggest you to copy every code segment in the notes
to the coding environment and try run the program
yourself.
• Also, try make change to the code, then observe the
output and deduce the behavior of the code. This way of
playing around with the code can help give you a better
understanding of the programming language.
4
Outline
(P. 6 – 11) Part I: Program Compilation & Execution
(P. 13 – 59) Part II: Basic Operations
• Variables & Constants
• Operators
• Expressions
• Data Types & Type Conversions
• Basic Input/Output
(P. 60 – 129) Part III: Flow of Control
• Branching
• Looping
5
Part I
6
The First C++ Program
As usual, we will start with the Hello World program.
// this is my first C++ hello world program
#include <iostream>
using namespace std;
int main() {
cout << “Hello World!” << endl;
return 0;
}
7
Program Editing
In the Ubuntu (Linux) environment that you have been working on for the
previous modules, you may use vi or any other text editor to edit your
program.
8
Compiling and Execution
In Linux environment, we can rely on command line (via the terminal) for
compiling and executing your program.
Now, suppose you already have hello.cpp in
your current working directory.
9
Compiling and Execution
Now try again to mess up with your code.
1. Delete line 3 “using namespace std;”
2. Compile and run the executable, and note what the error message is.
10
Hints on Debugging
• Hint 1: The line number of an error reported by the compiler
may be incorrect. It is possible that the error is located before
the reported line. After all, the compiler can only try its best to
guess what you meant to write down.
• Hint 2: For the same above reason, the nature of an error
reported by the compiler may be incorrect.
• Hint 3: If your source code has multiple errors, always fix the
first error and recompile, and repeat the process until the
compilation is successful. This is because error messages
subsequent to the first one have a higher likelihood of being
incorrect.
11
Offline options for Windows
users
• If you are using Windows computer, you can use IDEs like Dev-C++
(https://www.bloodshed.net/) or Code::Blocks (https://www.codeblocks.org/) to
write simple C++ programs locally.
• They support simple C++ programming only. Advanced functions like input /
output redirection and separate compilation are not supported.
• Before assignment submission, you MUST test your programs on Linux platform.
12
Part II
BASIC OPERATIONS
13
The First C++ Program
The Hello World program gives the basic structure of a C++ program.
// this is my first C++ hello world program A line starting with // is
called a comment line, any
#include <iostream>
text after // till the end of
using namespace std; line is ignored by the
compiler.
int main() {
cout << “Hello World!” << endl; This is the include directive
which tells the compiler
return 0;
where to find information
} about certain routines
used by the program;
iostream is the name of a
The iostream library that contains the
This is the main function which contains the object/operation cout and declarations of the
main body of the C++ program. In this case, endl are under the routines (cout/endl) that
we have two statements “cout…” and “return namespace std. If this line is handle input from the
..” in the main body. The main function is also removed, then you will need keyboard and output to
the starting point of the program execution of to write std::cout and the screen;
all C++ program: the program is executed std::endl without raising a Later, you may also use
statement by statement starting from the first compilation error. other libraries (e.g., the
statement in this main function. (You can try and look for the math library by 14
error yourselves.) #include <math>.
The First C++ Program
// this is my first C++ hello world program
#include <iostream>
using namespace std;
int main() {
cout << “Hello World!” << endl;
return 0;
}
By looking at the output of this program, you probably can guess what this
program does. How would you change the program so that it can output
Hello ENGG1340!
on the screen?
The last statement return 0; in the main function indicates (to the operating
system) that the program ended successfully. Note that on C++ compilers and
more recent C compilers (C99 onwards), the compiler will add this statement
for you if you omit it.
15
The First C++ Program
// this is my first C++ hello world program
#include <iostream>
using namespace std;
int main() {
cout << “Hello World!” << endl;
return 0;
}
cout is the standard output stream object defined in the iostream library. The
standard output is the screen by default.
www.cplusplus.com is a good place to look for the definition and usage of the
C++ constructs and functions.
You are highly recommended to go through the related topics in their tutorial
as well: http://www.cplusplus.com/doc/tutorial/
16
Variables
Let’s start with how a variable can be defined in C/C++.
Suppose we need a variable named “width”
which is to store an integer. This statement is called a
declaration.
int width;
Variable type Variable name (identifier)
17
Variables What happens in the computer?
Main Memory
1
int main ( ) {
int width; width
int height;
… A memory chunk for storing an
return 0; integer will be created in the main
} memory and associated with the
name “width”
Main Memory
2
int main ( ) {
int width; width
int height;
…
return 0;
} height
You are not required to memorize all these names. You will get to
recognize most of them later on.
20
Valid identifiers
• Which of the following identifiers are valid in C++?
a_man 2008 program.cc
Words like cin, cout, string, and cos are NOT keywords in C++. They are
defined in libraries required by the C++ language standard. Redefining these
words, though allowed, can be confusing and thus should be avoided.
21
Data Type of a Variable
Data type is an important concept when using a variable. This concept
is stricter in C++ than in Python.
• Tells the computer how to interpret the data stored in a variable
• Determines the size of storage needed to store the data
• Some basic data types in C++:
25
Initializations
• A variable that has not been given a value is said to be
uninitialized, and will simply contain some “garbage
value”
• Using uninitialized variables in computations will give
unexpected results, and thus should be avoided
• A variable may be initialized in its declaration:
int age = 5, steps = age + 10; A character constant
char c = ‘Y’; is written as a
bool win = true; character within
double height = 120.5, length = 1.5e3; single quotes.
Scientific notation
(floating point notation)
1.5e3 = 1.5 * 103 = 150026
Strings – The Very Basics
• Very often we need to work on textual information, and
this can be done in C++ using strings (C has a different
handling of strings and we will discuss that later).
• A string variable is just a variable containing a sequence of
characters.
• Strings are not one of the fundamental C++ data types but
are so frequently needed that they are defined as a class
within the standard library.
• Include the <string> header when using strings in your
program.
Sometimes you got no compilation error even if you don’t include the <string> header; it’s because it
might be included in some standard libraries already, however, this depends on the implementation
of the standard libraries and so it’s always a good practice to include it when using strings. 27
Strings – The Very Basics
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = “Hi”, name = “ENGG1340”;
cout << greeting << “ “ << name << endl;
greeting = “Good morning”;
cout << greeting << “ “ << name << endl;
return 0;
}
29
Constants
• Sometimes we want to assign a fixed value to a variable
double PI = 3.14159265359;
Line 8 “PI = 3.14159;” generates a compile error since PI is declared as a constant variable in line 5, but
here we attempt to change its value
You can see that this helps to ensure the value of a variable will not be changed accidentally. 30
Expressions
• Combine variables and constants to produce new values
(i.e., to evaluate an expression)
• Composed of operators (instructions) and operands (data)
operands
radius * 2 * 3.1416
• Operators operators
32
Arithmetic Operators
Arithmetic Operators Sign in the expression
Addition +
Subtraction -
Multiplication *
Division /
Modulus %
33
Arithmetic Operators
• Note: when both operands of the / operator are of integer
types, the / operator performs integer division which truncates
any fractional part of the division result.
int a = 3, b = 2;
int c = a / b, d = 8 / 3;
cout << "The value of c is " << c << endl ;
cout << "The value of d is " << d << endl ; What is the screen output?
The value of c is 1
The value of d is 2
34
Division by Zero
• If the divisor of the / operator is 0, a division by zero
error will be generated during runtime.
35
Precedence
• In evaluating an expression with mixed operators,
those operators with a higher priority will be carried
out before those with a lower priority.
36
Precedence
• In evaluating an expression with mixed operators,
those operators with a higher priority will be carried
out before those with a lower priority.
37
Precedence & Associativity
Operator types Operators Associativity
unary +, –, ++, --, ! - High precedence
binary arithmetic *, /, % left to right
binary arithmetic +, – left to right
relational <, <=, >, >= left to right
relational ==, != left to right
logical && left to right
logical || left to right
assignment =, +=, –=, *=, /=, %= right to left
Lower precedence
39
Relational Operators
Relational Operators Sign in the expression
Greater than >
Greater than or equal >= same
Smaller than < higher
precedence
Smaller than or equal <=
Equal ==
lower precedence
Not equal !=
40
Relational Operators
• In C/C++, the numeric value of a relational or logical
expression is 1 if the relation is true, and 0 if the relation
is false.
0
Suppose all 3 1
cout << (a == b);
examples start
with:
int a = 1, b = 2;
0
2 cout << (a > b);
1
3 cout << (a < b);
41
Relational Operators
int i = 1, lim = 2; 0
4 cout << (i < lim – 2) ;
int i = 1, lim = 2; -1
5 cout << ( (i < lim) – 2 );
A B A && B A || B !A
0 0 0 0
1 0: False
0 1 0 1 1: True
1 0 0 1
0
1 1 1 1
bool i_am_cool =
2 (gals != 0) && ((gifts / gals) >= 2);
44
Increment & Decrement
Operators
Assignment Operators Sign in the expression
Increment ++
Decrement --
int i = 0; int i = 0;
is equivalent to
--i ; i = i – 1;
45
Increment & Decrement
Operators
• The operators ++ and -- may be used either as
prefix (e.g., ++i) or postfix (e.g., i++) operators.
int c = 0, i = 0; int c = 0, i = 0;
c = i++; is equivalent to c = i; c = ???
i = i + 1; i = ???
46
Assignment Operators
• Expression such as i=i+2 in which the variable on
the left-hand side is repeated immediately on the
right can be written in the compressed form i+=2
• Most binary operators have a corresponding
compound assignment operator, e.g., -=, *=, /=, and
%=
Examples
x *= y + 1; is equivalent to x = x * (y + 1);
x %= y % 3; is equivalent to x = x % (y % 3);
47
Type Conversions
• When an operator has operands of different types,
they are converted to a common type according to a
small number of rules.
1 “lower” type promoted to “higher” type
This also shows that you, as the programmer, can control how values are stored. 49
Type Conversions
50
Basic I/O (Input/Output)
• A stream is an object where a program can either insert or
extract characters to/from it.
• We may use streams to perform input and output operations
in sequential media such as the screen or the keyboard.
• The standard C++ library includes the header file iostream
where the standard input and output stream objects are
declared.
• We need to include the header file by the #include directives
before using any objects and functions
in the iostream library. #include <iostream>
using namespace std;
Include the iostream library to use cin and cout. The
int main () {
iostream library is some existing object codes developed by
…
others. As this is so useful, it is regarded as standard C++ }
library. 51
Basic I/O
#include <iostream> This statement is important!
using namespace std; Because cout and endl are provided
under the namespace (i.e., a container
int main () {
of names) std.
cout << “Hello!” << endl;
} Their names are indeed std::cout and
std::endl.
Try out these escape sequences in a program and see the result!
54
Standard Input
• From time to time, we need to obtain user input to our program.
• The standard input device is usually the keyboard, and the C++
stream object defined to access it is cin.
• The extraction operator >> is used to extract data from the
stream
• The type of the variable will determine the type of data that is
extracted from the stream.
int x; char x;
vs.
cin >> x; cin >> x;
An integer is expected to be input A character is expected to be input
• Note that cin can only process the input from the keyboard once
the RETURN key has been pressed.
55
A Sample Program on I/O
Be careful about the directions of the << and >> operators!
#include <iostream>
using namespace std;
int main(){
int age;
double height, weight;
cout << "Please input your age, height and weight: ";
cin >> age >> height >> weight;
cout << endl << "Your age is " << age << endl;
cout << "Your height is " << height << endl;
cout << "Your weight is " << weight << endl;
return 0;
}
Screen output
56
A Sample Program on I/O
#include <iostream>
using namespace std;
int main(){
int age;
double height, weight;
cout << "Please input your age, height and weight: ";
cin >> age >> height >> weight;
cout << endl << "Your age is " << age << endl;
cout << "Your height is " << height << endl;
cout << "Your weight is " << weight << endl;
return 0; user input from keyboard
}
Screen
57
output
A Sample Program on I/O
#include <iostream>
using namespace std;
int main(){
int age;
double height, weight;
cout << "Please input your age, height and weight: ";
cin >> age >> height >> weight;
cout << endl << "Your age is " << age << endl;
cout << "Your height is " << height << endl;
cout << "Your weight is " << weight << endl;
return 0;
}
Your age is 20
Your height is 175.5
Your weight is 132
Screen
58
output
Using File Redirection as Standard
Input to Your Program
• Sometimes it is just too tiring to enter the input values to your program again and
again, especially during the testing and debugging stages. In this case, you may
execute your program using command line and file redirection so that the contents
of a file will be fed into your program as if they are from the standard input (i.e., by
default the keyboard)
User input stored in a file “info.txt” and use file redirection to fed file
contents to the program as input. 59
Part III
FLOW OF CONTROL
60
What we are going to learn?
• Making decisions in your program (branching)
– the if selection statement
– the if…else double selection statement
– the switch multiple-selection statement
• Doing something repeatedly (looping)
– while loop
– for loop
– break and continue in loops
61
Algorithms
• An algorithm is a procedure for solving a problem in
terms of
– the actions to execute and
– the order in which the actions execute (flow of control)
Get out of bed Get out of bed
Go to campus ✓ Go to campus ✗
62
Reference Only
Pseudocode
• “fake” code — An artificial and informal language similar to
everyday English for developing an algorithm
• Helps you think out a program without worrying the syntax of
a programming language.
63
Flowchart
• A diagram to illustrate program flow (program logic).
• Used in analyzing, designing, documenting or managing a
program.
64
Flow of Control
• Recall that statements in the main function are
executed sequentially.
• In more complex programs, however, it is often
necessary to alter the order in which statements are
executed, e.g.,
– Choosing between two alternative actions – branching
– Repeating an action a number of times – looping
• The order in which statements are executed is often
referred to as flow of control.
65
Branching & Looping
Compile program
Wake up
Branching Looping
66
Making a decision
BRANCHING
67
Branching – Making a Decision
• Sometimes an action is taken selectively based on a
decision/condition.
Get dressed
Y
Does it rain?
Go to campus
Do this only when the
condition is true
68
The if statement
Pseudocode
If student’s mark is greater than or equal to 60
print “passed”
C++ code
Print “passed”
N
Flowchart
69
The if statement
Syntax
if (condition) statement;
70
The if…else statement
Pseudocode
If student’s mark is greater than or equal to 60
print “passed”
Else
print “failed”
C++ code
Flowchart
71
The if…else statement
Syntax
if (condition)
statement1;
else
statement2;
72
Example 1
• Write a program that reads 2 input
integers and outputs the bigger one.
How would you solve the
#include <iostream>
using namespace std;
problem?
int main() {
First step: devise a logical
flow (i.e., the algorithm) for
the solution.
73
Example 1
• Write a program that reads 2 input Read 2 integers:
integers and outputs the bigger one. a and b
#include <iostream>
using namespace std; Y
a > b?
int main() {
N
max = b max = a
74
Example 1
• Write a program that reads 2 input Read 2 integers:
integers and outputs the bigger one. a and b
#include <iostream>
using namespace std; Y
a > b?
int main() {
N
Now think about it:
How many variables do you need? max = b max = a
What are their data types?
return 0;
}
75
Example 1
• Write a program that reads 2 input Read 2 integers:
integers and outputs the bigger one. a and b
#include <iostream>
using namespace std; Y
a > b?
int main() {
int a, b, max; N
cin >> a >> b;
max = b max = a
if (a > b)
max = a;
else
max = b; Output max
cout << max;
return 0;
}
76
Example 2 Read 3 integers:
• Write a program that reads 3 input a, b and c
max = b max = a
77
Example 2 Read 3 integers:
• Write a program that reads 3 input a, b and c
78
Compound Statements
• What if an action involves more than one statement?
Syntax
if (condition) statement;
mark >= 60? Y
Print “passed”
if (mark >= 60) {
grade = ‘P’;
cout << “passed”;
}
79
Compound Statements
mark >= Y
60? if (mark >= 60) {
grade = ‘P’;
N cout << “passed”;
}
grade = ‘F’ grade = ‘P’ else {
grade = ‘F’;
cout << “failed”;
}
Print “failed” Print “passed”
80
Nested if…else Statements
Age
within
Y • An if-else statement can
[18, 25]?
be nested within
N another if-else
Height Y
>=180? statement
N
My Mr. Right…
1. 18 to 25 years old, AND
2. Height: 180 cm or above
81
Nested if…else Statements
age …
Y
within if (age >= 18 && age <=25)
[18, 25]? {
N
// the Yes part to
// be dealt with here
height Y
>=180?
N }
else {
cout << "Bye bye.";
“Bye bye” “I am sorry” “Yes I do!” }
…
My Mr. Right…
1. 18 to 25 years old, AND
2. height: 180 cm or above
82
Nested if…else Statements
age …
Y
within if (age >= 18 && age <=25)
[18, 25]? {
N
if (height >= 180)
cout << "Yes I do!";
height Y
>=180? else
cout << "I am sorry.";
N }
else {
cout << "Bye bye.";
“Bye bye” “I am sorry” “Yes I do!” }
…
My Mr. Right…
1. 18 to 25 years old, AND
2. height: 180 cm or above
83
A Note on Block Statement in C/C++ vs. Python
• How do you specify a block statement in Python?
if (mark >= 60) {
if mark >= 60:
grade = ‘P’;
grade = "P"
cout << “passed”;
print("passed")
}
else:
else {
grade = "P"
grade = ‘P’;
print("failed")
cout << “failed”;
Python: Indentation }
C/C++: { }
• In C/C++ , we use {} to specify a block instead
• Indeed, the C/C++ compiler does not care about indentation
which means that you can write in as few lines as possible, as
long as the compiler can parse it.
Try this: a C++ program in 2 lines
#include<iostream>
int main() {if (2>3) std::cout << "no way"; else std::cout << "Why
do you desperately need to make life harder?\n"; return 0;}
84
Coding Hints
• Visualize the logic of the program before writing the
code.
• When writing the code, follow the logic in the
diagram, implement the processes in the diagram one
at a time.
• Use proper indentation (spacing) to make your
program more human readable (even when C/C++
does not require this). Always remember that you or
others will need to maintain your codes later.
85
Dangling-Else Problem
Unlike Python, indentation does NOT determine blocks of statements in C/C++!
The following program segments are treated the same by the C/C++ compiler,
although they have different indentations as appear to us. So how would the
C/C++ treat it? Should the else be paired with the 1st if or the 2nd if?
if ( x > 5 )
if ( y > 5 ) Looks as if:
cout << “x and y are > 5”; 1st cout is executed when x > 5 and y > 5,
else 2nd cout is executed when x <= 5
cout << “x is <= 5”;
if ( x > 5 )
if ( y > 5 ) Looks as if:
cout << “x and y are > 5”; 1st cout is executed when x > 5 and y > 5,
else 2nd cout is executed when x > 5 and y <= 5
cout << “x is <= 5”;
✓ this is what the compiler treats as 86
Dangling-Else Problem
• Recall that C++ is a free formatting language
– The compiler will ignore any whitespaces, including
indentations
• The compiler always pairs an else with the nearest
previous if that is not already paired with some else
• To avoid the dangling else problem, use braces { } to
tell the compiler how to group the statements
87
Dangling-Else Problem
if ( x > 5 ) {
if ( x > 5 )
if ( y > 5 )
if ( y > 5 ) is
cout << “x and y are > 5”;
cout << “x and y are > 5”; equivalent
else
else to cout << “x is <= 5”;
cout << “x is <= 5”;
}
88
A Dangling-Else Example
if ( temperature >= 20 )
if ( temperature >= 30 )
cout << “good day for swimming” << endl;
else
cout << “good day for golfing” << endl;
else
cout << “good day to play tennis”;
89
Multi-way if-else Statement
mark Y
Print “A”
>=90?
if ( mark >= 90 ) // 90 and above gets "A"
N
cout << "A";
Y else
mark
Print “B” if ( mark >= 80 ) // 80-89 gets "B"
>=80?
cout << "B";
N else
if (mark >= 70 ) // 70-79 gets "C"
mark Y cout << "C";
Print “C”
>=70? else
N if (mark >= 60 ) // 60-69 gets "D"
cout << "D";
mark Y else // less than 60 gets "F"
Print “D” cout << "F";
>=60?
N
Print “F”
90
Multi-way if-else Statement
mark Y
Print “A”
>=90? A more compact style is preferred
N
if ( mark >= 90 ) // 90 and above gets "A"
mark Y cout << "A";
Print “B”
>=80? else if (mark >= 80 ) // 80-89 gets "B"
cout << "B";
N
else if (mark >= 70 ) // 70-79 gets "C"
Y cout << "C";
mark
Print “C” else if (mark >= 60 ) // 60-69 gets "D"
>=70?
cout << "D";
N else // less than 60 gets "F"
cout << "F";
mark Y
Print “D”
>=60?
N
Print “F”
91
Series of if vs. Multi-way if-else
• What’s the difference between the following two program segments?
Faster, skip remaining if testing once Slower, needs to test all conditions even
hitting a true condition though only one of them can be true
93
1
When a switch statement is
switch Statement executed, the
controlling_expression is
char grade; evaluated,
2 cin >> grade; the value of which must be one
The constants given after switch ( grade ) of Boolean, integer or character
the case keywords are { types
checked in order until the case ‘A’:
first that equals the value cout << "grade point is 4.0";
of the
break;
case ‘B’:
controlling_expression is
cout << "grade point is 3.0";
found, and then the
break;
following statements are case ‘C’:
executed cout << "grade point is 2.0";
3 break;
The switch statement case ‘D’:
ends when a break cout << "grade point is 1.0";
statement is encountered break;
case ‘F’:
4 cout << "grade point is 0.0";
break;
If none of the constants default:
matches the value of the cout << "grade is invalid";
controlling_expression, then }
the default_statement is 94
executed
switch Statement
char grade;
cin >> grade;
switch ( grade )
{ is equivalent to
case ‘A’:
cout << "grade point is 4.0";
break; char grade;
case ‘B’: cin >> grade;
cout << "grade point is 3.0"; if (grade == ‘A’)
break; cout << "grade point is 4.0";
case ‘C’: else if (grade == ‘B’)
cout << "grade point is 2.0"; cout << "grade point is 3.0";
break; else if (grade == ‘C’)
case ‘D’: cout << "grade point is 2.0";
cout << "grade point is 1.0"; else if (grade == ‘D’)
break; cout << "grade point is 1.0";
case ‘F’: else if (grade == ‘F’)
cout << "grade point is 0.0"; cout << "grade point is 0.0";
break; else
default: cout << "grade is invalid";
cout << "grade is invalid";
}
The switch statement is sometimes preferably especially when it can show clearly
the flow of control depends on the value of grade only.
95
switch Statement more examples
Assuming that mark is of type
switch ( mark / 10 ) { int with range 0 to 100. Note
case 0: case 1: that this is an integer division
case 2: case 3: which results in an integer
case 4: case 5: value.
grade = ‘F’;
break; What is the range of mark for grade to
case 6: be assigned ‘A’? 90-100
grade = ‘D’;
break; for grade to be assigned ‘B’? 80-89
case 7:
grade = ‘C’;
break; for grade to be assigned ‘C’? 70-79
case 8:
grade = ‘B’; for grade to be assigned ‘D’? 60-69
break;
case 9: for grade to be assigned ‘F’? 0-59
case 10:
grade = ‘A’;
break; What if mark is out of the range 0 to
default: 100?
cout << “invalid mark";
The program will output
} “invalid mark” on screen
96
switch Statement more examples
97
int main()
{
switch Statement
int mark; more examples
cout << “Enter the mark: ”;
cin >> mark;
A recap
switch ( mark / 10 ) {
case 0: case 1: What is the output of the program
case 2: case 3: segment if the input mark is 75?
case 4: case 5:
cout << “The grade is F.” << endl;
break; Enter the mark: 75
case 6: The grade is C.
cout << “The grade is D.” << endl;
break;
case 7:
cout << “The grade is C.” << endl;
break;
case 8:
cout << “The grade is B.” << endl;
break;
case 9:
case 10:
cout << “The grade is A.” << endl;
break;
default:
cout << “Invalid mark.“ << endl;
}
return 0;
} 98
switch Statement more examples
int main()
{ Pay ATTENTION!
int mark; The break; statements are missing!
cout << “Enter the mark: ”;
cin >> mark;
switch ( mark / 10 ) {
case 0: case 1: What is the output of the program
case 2: case 3:
case 4: case 5: segment if the input mark is 75?
cout << “The grade is F.” << endl;
case 6: Enter the mark: 75
cout << “The grade is D.” << endl; The grade is C.
case 7: The grade is B.
cout << “The grade is C.” << endl;
case 8: The grade is A.
cout << “The grade is B.” << endl; Invalid mark.
case 9:
case 10:
cout << “The grade is A.” << endl;
default:
cout << “Invalid mark.“ << endl;
}
return 0;
} 99
Common Mistakes
• Below are some common mistakes in the Boolean condition of an
if or if…else statement:
– Using an assignment instead of the equality operator, e.g.,
if (a = 10)
✗ if (a == 10)
✓
– Using bitwise AND/OR instead of logical AND/OR operator, e.g.,
✗ ✓
if (a != 0 & b > 0) if (a != 0 && b > 0)
if (a != 0 | b > 0) if (a != 0 || b > 0)
if (a < b < c)
✗ if (a < b && b > c)
✓
• These are all legal expressions in C++ and hence the compiler will
not report any syntax error 100
?: — A Shorthand for If-Else
• A ternary operator that takes three operands:
101
Doing something repeatedly
LOOPING
102
Loop
• A loop is any program construction that repeats a
statement (or a compound statement) a number of
times.
• The statement to be repeated in a loop is called the
body of the loop.
• Each repetition of the loop body is called an iteration.
• In C++, looping can be achieved using either a while
statement or a for statement.
Note: There is also the do…while statement, but we will leave it for
you interest only.
103
while Statement Loop body
loop true
statement(s)
condition
false
104
while Statement
Syntax Syntax
while (condition) while (condition) {
statement; statement_1;
statement_2;
…
statement_n;
loop body }
return 0;
}
106
while Statement
We may use a loop variable (or
#include <iostream> counter), which is of integer
using namespace std;
type, to count the number of
int main() iterations (i.e., how many times
{
int answer = 0; the loop body is executed).
int trials = 0;
return 0;
}
107
while Statement
#include <iostream> Sentinel-controlled while loops
using namespace std; to use a special value to indicate end of loop
int main()
In this example, the special value is any
{
int x = 0, total = 0; negative number. Also, the number of
cout << "Enter a negative num to end." << endl; times the loop body is executed is
determined at run time only (loops until
while (x >= 0) { user inputs a negative number).
total += x;
cout << "Total = " << total << endl;
Screen output?
cout << "next number? ";
cin >> x; Enter a negative number to end.
} Total = 0
next number? 4 ↵
cout << "Program ends." << endl;
Total = 4
return 0; next number? 3 ↵
} Total = 7
next number? 2↵
Total = 9
Note that the loop condition depends on the value of x,
next number? 1↵
and hence it is important to make sure that the value of x Total = 10
will be updated within the loop body (as in cin >> x) in next number? -1 ↵
order for the condition (x >= 0) to change to false to exit Program ends.
the loop. 108
while Statement
Counter-controlled while loops
#include <iostream> by decrementing a counter
using namespace std;
while (n > 0) {
cout << "next number? ";
cin >> x;
total += x;
cout << "Total = " << total << endl;
n--;
}
Enter the number of values to be added: 3↵
return 0; next number? 4↵
} Total = 4
next number? 3↵
Again, note that how the value of Total = 7
n is updated within the loop body next number? 2↵
Total = 9
to control loop repetition Screen output? 109
while Statement
#include <iostream>
using namespace std; Counter-controlled while loops
by incrementing a counter
int main()
{
int x = 0, total = 0, i, n;
cout << "Enter the number of values to be added: ";
cin >> n;
i = 0;
while (i < n) {
cout << "next number? ";
cin >> x; condition for continuation
total += x;
cout << "Total = " << total << endl;
i++;
} updating of loop variable inside
the loop body
return 0;
}
113
Quick Exercise 1
Write a complete C++ program that outputs the
numbers 1 to 20, one per line, using a while loop.
114
for Statement
• The for statement (a.k.a. for loop) in C++ provides a compact
way of expressing a loop structure
Output 1 to 20, one number of a line, using Now, take a close look at the three statement inside
a for loop (i.e., same program outcome as the round brackets () after the for keyword:
quick exercise 1).
i = 1;
#include <iostream> this statement is for initialization, i.e., it will only be
using namespace std; executed once before the loop begins for the first
time
int main()
{ i <= 20;
int i; this statement is the loop condition for deciding
whether to continue to loop. The loop body will be
for (i = 1; i <= 20; ++i) executed only if it is true.
cout << i << endl;
++i
return 0; this statement is the updating statement which will
} be executed after each iteration of the loop. It
usually updates the loop control variable (in this
case i).
115
for Statement
1
initialization
2 3
loop true
statement updating
condition
false
Syntax
1 2 3
for (initialization; condition; updating) {
execution statement_1;
path if
condition is
…; execution
statement_n; path if
false, i.e., to
condition is
exit the loop } true, i.e., to
execute the
loop body
116
for Statement
• When a for statement is executed
117
for Statement
• Most while loops can be implemented as a for loop
#include <iostream>
using namespace std;
Compare this program to this
int main() previous while loop example.
{
int answer = 0;
int trials;
return 0;
}
118
for vs. while
#include <iostream>
#include <iostream> using namespace std;
using namespace std;
int main()
int main() {
{ int x = 0, total = 0, i, n;
int x = 0, total = 0, i, n; cout << “How many numbers to add? ”;
cout << “How many numbers to add? ”; cin >> n;
cin >> n;
// while loop
// for loop i = 0;
for (i = 0; i < n; i++) { while (i < n) {
cout << “next number? ”; cout << “next number? ”;
cin >> x; cin >> x;
total += x; total += x;
cout << “Total = ” << total << endl; cout << “Total = ” << total << endl;
} i++;
}
return 0;
} return 0;
}
Compare the above two programs which have the same program behavior.
119
Quick Exercise 2
Write a program that outputs 9 8 7 6 5 4 3 2 1 0 in a
single line using a for loop.
120
Quick Exercise 3
Write a program that calculates the sum of odd
numbers between 1 and 20 using a for loop.
121
break Statement
• The break statement can be used to exit a loop from
inside a loop body.
• When a break statement is executed,
– the loop ends immediately.
– the execution continues with the statement following the loop.
• The break statement may be used in both while loop and
for loop.
• Note: Avoid using a break statement to end a loop unless
absolutely necessary because it might make it hard to
understand your code.
– A proper way to end a loop is using the condition for
continuation.
122
break Statement
Yes, you may declare and initialize the counter variable at the same time in
the initialize statement in the for loop
int main()
{ The break statement is used
for (int i = 0; i >= 0; i++) { here to exit the infinite loop
if (i == 15) break; when i == 15
cout << i << “ ”;
}
Screen output?
return 0;
} 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Can you rewrite the program so that it produces the same output
without using the break statement?
123
continue Statement
• The continue statement is used to terminate the
current iteration of a loop.
• When a continue statement is executed,
– any loop body statements after it will be skipped.
– the loop continues by starting the next iteration.
• Like the break statement, the continue statement may
be used in both while loop and for loop.
124
continue Statement
#include <iostream> The continue statement is used here
using namespace std; to skip those i’s which are even
int main()
{
for (int i = 0; i < 20; ++i) {
if (i % 2 == 0) continue;
cout << i << “ ”; When the continue statement is
} executed, the succeeding cout
cout << endl; statement are skipped. The next
iteration begins by updating the
return 0; loop variable and checking the
} condition.
Screen output?
1 3 5 7 9 11 13 15 17 19
Can you rewrite the program so that it produces the same output
without using the continue statement? 125
Examples on break and
continue
int count;
for ( count = 1; count <= 10; ++count) {
if (count == 5) break;
1 2 3 4
Screen output?
Broke out of loop at count = 5
1 2 3 4 6 7 8 9 10
Screen output?
126
Answer to Quick Exercise 1
Write a complete C++ program that outputs the
numbers 1 to 20, one per line, using a while loop
#include <iostream>
A shorter version
using namespace std;
#include <iostream>
int main()
using namespace std;
{
int i = 1, n = 20;
int main()
{
while (i <= n) {
int i = 1, n = 20;
cout << i << end;
i++;
while (i <= n)
} We can’t use ++i here.
cout << i++ << end;
Using ++i will output 2 to
return 0; 21 instead. Why? Review
return 0; how the prefix and postfix
}
} operators work here.
127
Answer to Quick Exercise 2
Write a program that outputs 9 8 7 6 5 4 3 2 1 0 in a
single line using a for loop.
#include <iostream>
using namespace std;
int main()
{
int i;
128
Answer to Quick Exercise 3
Write a program that calculates and outputs the sum of
odd numbers between 1 and 20 using a for loop.
#include <iostream>
using namespace std;
int main()
{
int i, sum = 0;
for (i = 1; i <= 20;
++i) {
if (i % 2 == 1) {
sum += i;
}
}
cout << sum << endl;
return 0;
}
129
We are happy to help you!
130