0% found this document useful (0 votes)
7 views

M3

The document provides guidance notes for a C++ programming module, emphasizing the use of the C++ 11 standard and the importance of proper compilation and execution of programs. It outlines the structure of a basic C++ program, introduces key concepts such as variables, data types, and constants, and encourages hands-on practice with coding. Additionally, it includes tips for debugging and using different development environments, particularly for Windows users.

Uploaded by

yeunggingsing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

M3

The document provides guidance notes for a C++ programming module, emphasizing the use of the C++ 11 standard and the importance of proper compilation and execution of programs. It outlines the structure of a basic C++ program, introduces key concepts such as variables, data types, and constants, and encourages hands-on practice with coding. Additionally, it includes tips for debugging and using different development environments, particularly for Windows users.

Uploaded by

yeunggingsing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

Module 3 Guidance Notes

C++ Basics
ENGG1340 COMP2113
Computer Programming II Programming Technologies

Estimated Time of Completion: 3 Hours


Important Note: C++ 11 Standard
• We will deal with C++ only in this module. and will leave the
C counterparts on I/O (i.e., input/output) handling to latter
modules.
• Important: We will be using the C++ 11 standard, so make
sure that your compiler option is set appropriately. We
suggest to use the following command to compile your C++
program in Linux:
g++ -pedantic-errors -std=c++11
your_program.cpp
The -pedantic-errors flag is to make sure that your code conforms to the ISO
C/C++ standard. We will enforce this in your assignment submission too.
For more information about C/C++ standards, you may read
https://en.wikipedia.org/wiki/ANSI_C and https://isocpp.org/std/the-standard
2
Important Note: Guidance Notes
• Our guidance notes aim at leading you through the
learning of the materials. It also defines the scope of our
course (say what we expect that you should know for the
purpose of this course).
• Pages marked with “Reference Only” or “Optional” mean
that they are not in the scope of assessment for this
course.

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

PROGRAM COMPILATION &


EXECUTION

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;
}

Now, copy the code and save it in a file named hello.cpp


in your home directory.

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.

hello.cpp in the vi editor

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.

1. Use this command line to compile hello.cpp:


g++ -pedantic-errors -std=c++11 hello.cpp -o hello
2. If the compilation is successful, you should find another file “hello” in the
working directory.
3. Run the executable “hello” by typing “./hello” at the prompt

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.

Dev-C++ IDE for Windows Code::Blocks IDE for Windows

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.

We will come back to the basic I/O afterwards.

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)

• Used to store data.


• Data stored in a variable may change over time.
• When we declare a variable, the computer will assign an appropriate number
of memory cells in the main memory to each variable according to the type
of data to be stored.

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

Recall that the execution starts from the main() function 18


Variable Names (aka Identifiers)
• An identifier must start with either
int area;
– a letter (i.e., A to Z, and a to z), or int length;
int area = length*length;
– the underscore symbol (i.e., _)
vs.
• The rest of the characters may be int a;
– letters (i.e., A to Z, and a to z), int b;
int b= a*a;
– digits (i.e., 0 to 9), or
– the underscore symbol (i.e., _)
• Meaningful identifiers make a program more readable
• C++ is case-sensitive
– e.g., radius, RADIUS, Radius, etc., are different
• Cannot be a reserved keyword in C++
19
C++ Reserved Keywords
• Reserved words in C++ with predefined meanings.
• CANNOT be used as names for variables or anything else.
asm do inline return typedef
auto double int short typeid
bool dynamic_cast log signed typename
break else long sizeof union
case enum mutable static unsigned
catch explicit namespace static_cast using
char extern new struct virtual
class false operator switch void
const float private template volatile
const_cast for protected this wchar_t
continue friend public throw while
default goto register true
delete if reinterpret_cast try

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

const year1-student _oOOo_

an integer change%2 ABCx123

string Days_of_Week friend

cout delete cos

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++:

Name Description Size Range


char Character or small integer 1 byte 0 to 255
bool Boolean value 1 byte True(1) or False(0)
int Integer 4 bytes -2147483648 to 2147483648
Double precision floating 1.7e‐308 to 1.7e+308 (~15 digits)
double point number 8 bytes
-1.7e‐308 to -1.7e+308 (~15 digits)
** The size and range of a particular data type depend on the system under which a program is compiled.
The values shown above are those found on most 32-bit systems. Also bool occupies 1 byte because it is the
smallest addressable size of CPU.
22
Declarations
• All variables must be declared before use.
• A declaration specifies a type, and contains a list of
one or more variables of that type.
Syntax
type_name variable_name;
type_name variable_name_1, variable_name_2, …;

• Examples: To declare two integer variables named “age” and “steps”

int age, steps;


char c;
bool win;
double height, width, length;
23
Assignment Statement
• A variable may be initialized or its value can be
changed at a later time after its declaration using an
assignment statement.
• An assignment statement consists of a variable on the
left-hand side of an equal sign, and a value or an
expression on the right-hand side.
Syntax
variable_name = expression;

int age; a constant value


Example
double heights;
age = 5; an expression
heights = 8 * age + 20.5;
24
Assigning Values to Variables
Main Memory
1
int main ( ) {
width ???
5
int width, height, area;
width = 5;
height = 4; height 4
???
area = width * height;
return 0;
} The variable height is area 20
???
uninitialized before
use and the result is
unpredictable. Main Memory
2 int main ( ) {
int width, height, area; width 5
???
width = 5;
area = width * height;
return 0; height ???
}
area ???

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;
}

Can you guess what the output is? Hi ENGG1340


Good morning ENGG1340

We will come back to the more interesting operations of strings later.


28
Constants
• Constants are expressions with fixed values.
• Integers: 65 (decimal), 0101 (octal), 0x41 (hexadecimal)
• Floating point numbers: 3.14159, 6e23, 1.6e-19, 3.0
• Characters: ‘A’, ‘z’,
‘\n’ (newline), ‘’’ (’), ‘\\’ (\), ‘\?’ (?),
‘\101’ (‘A’, octal ASCII code for 65),
‘\x41’ (‘A’, hex ASCII code for 65)
• Strings: “This is a string”, “” (empty string)
• Boolean: true, false Note that a character is enclosed within the single
quotes ‘ ’ while a string is enclosed by the double
quotes “ ”. We will come back to the differences
between characters and strings in later modules.
For now, you may think of a character as a single
letter and a string as a sequence of letters.

29
Constants
• Sometimes we want to assign a fixed value to a variable
double PI = 3.14159265359;

• Add a constant modifier in front of a variable declaration


• The compiler will make sure that the variable remains a constant

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

– Specify what is to be done on the operands


– E.g., arithmetic operators, relational operators, logical operators
• Operands
– Data on which the computation is performed
– May be variables and/or constants
31
Operators
• Arithmetic operators (+, –, *, /, %)
• Relational operators (>, >=, <, <=, ==, !=)
• Logical operators (&&, ||, !)
• Increment and decrement operators (++, --)
• Assignment operators (=, +=, -=, *=, /=)

32
Arithmetic Operators
Arithmetic Operators Sign in the expression
Addition +
Subtraction -
Multiplication *
Division /
Modulus %

• The modulus operator % produces the remainder.


– E.g., 13 % 3 results in 1
because 13 = (3 * 4) + 1

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

• The operator % cannot be applied to double (i.e., floating point


numbers).

34
Division by Zero
• If the divisor of the / operator is 0, a division by zero
error will be generated during runtime.

Note that no compilation error will be generated.

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.

1+2*3 Result: 9✗or 7?



• The operator * has a higher precedence than the
operator + (same as what you learned before ).
• The order of evaluation is equivalent to 1 + (2 * 3).

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.

12 – 11 % 3 Result: 1✗or 10?



• The operator % has a higher precedence than the
operator –.
• The order of evaluation is equivalent to
12 – (11 % 3).

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

• The order of evaluation may be overridden by inserting


parentheses () into the expressions
– e.g., (1 + 2) * 3 = 9
38
Arithmetic Operator for
Characters
We may perform arithmetic operation with characters. In this case, the numerical
representation as in the ASCII code for each character will be used in the calculation.
The following program also shows a common technique in converting a letter from
upper case to lower case.
1: y
#include <iostream> 2: z
using namespace std;
int main()
{ Screen output
char c = ‘Y’;
// convert a letter from upper case to lower case
c = c + (‘a’ – ‘A’);
cout << "1: " << c << endl; Can you convert a letter
from lower case to upper
// advance to the next character
c = c + 1;
case then?
cout << "2: " << c << endl;
return 0; The ASCII table:
} www.asciitable.com

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 !=

• For comparing the operands.

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) ;

The “–” operator is of higher precedence


than the “<” operator, so “lim – 2” is
executed first

int i = 1, lim = 2; -1
5 cout << ( (i < lim) – 2 );

The bracket () overrides precedence and


associativity,
hence (i < lim) is first evaluated to yield the
intermediate result 1
42
Logical Operators Recall truth tables for computer logics.

Operands AND (&&) OR (||) NOT (!)

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

• Precedence: (High) ! > && > || (Low)


• C++ treats any non-zero value as true, and zero as false
– Hence (3 && 0) is false, and (-5 || 0) is true
• The unary negation operator ! converts a non-zero operand into 0, and a zero
operand into 1 (e.g., ! 3 is evaluated to 0)
43
Logical Operators
int x = 5; 1
1 bool in_range = ! (x < 0 || x > 50);
cout << in_range << endl;

Both expressions connected by || evaluate to a false value (0)

bool i_am_cool =
2 (gals != 0) && ((gifts / gals) >= 2);

No! Because: C/C++ evaluates a logical expression


from left to right, and stops evaluating once the
truth or falsehood of the result is known.
What if gals is 0? (a.k.a. short-circuit evaluation)
Will gifts/gals
generate a runtime Hence, if gals is 0, the expression ((gals != 0) && ???) must
be false anyway, so the expression (gifts / gals) >=2 will
error?
NOT be evaluated, and thus not generating a runtime error.

There is similar short-circuit evaluation for the || operator:


bool omg = (gals == 0) || ((gifts / gals) < 2);

44
Increment & Decrement
Operators
Assignment Operators Sign in the expression
Increment ++
Decrement --

• The increment operator ++ adds 1 to its operand.


int i = 0; int i = 0;
is equivalent to
++i ; i = i + 1;

• The decrement operator -- subtracts 1 from its operand.

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.

– When used as prefix, increment/decrement is done before the value is used.

int c = 0, i = 0; int c = 0, i = 0; c = ???


c = ++i ; is equivalent to i = i + 1; i = ???
c = i;

– When used as postfix, increment/decrement is done after the value is used.

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

2 (int) is promoted to 2.0 (double),


3.0 / 2; and the result is 1.5

Important: Compare this with


No type conversion because both 3 and 2
3 / 2; are integers, therefore
integer division is carried out,
and the result is 1
48
Type Conversions
2 In assignment statements, the value of the right
side is converted to the type of the left

double x = 5; x stores the value 5.0

Converting a double value to an int value causes


int x = 2.8; truncation of any fractional part
x stores the value 2
* The compiler may issue a warning as there is inform

Explicit type casting tells the compiler it is


int x = (int) 2.8; an intended type conversion and prevents
the compiler from producing a warning.
x stores the value 2
* The compiler generates no warning

This also shows that you, as the programmer, can control how values are stored. 49
Type Conversions

3 Type conversions that don’t make sense are not allowed.

e.g., assigning a string literal to an int variable generates a


compilation error:

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.

#include <iostream> ✗ #include <iostream> ✓


int main () { int main () {
cout << “Hello!” << endl; std::cout << “Hello!”
} << std:: endl;
}

a.cpp: In function int main():


a.cpp:4: error: 'cout' was not declared in this scope
a.cpp:4: error: 'endl' was not declared in this scope Compiler error 52
Standard Output
• By default, the standard output of a program is the
screen, and the C++ stream object defined to access
it is cout.
• The insertion operator << is used to insert data into
the stream, which may be used more than once in a
single statement.
Hello World!
int a = 1 , b= 2, c = 3; 11
cout << “Hello ”; b = 2 and c = 3
cout << “World!” << endl;
cout << 1 << a << endl; Screen output
cout << “b = ” << b << “ and c = ” Note that there is no line break after
“Hello ” and “World!”
<< c << endl; Also there is no space between 1 and the
value of a in the 2nd output line.
53
Standard Output
• There are some escape sequences that have special
usage in the output.
\a alert (bell) character \v vertical tab
\b backspace \\ backslash
\n newline \? question mark
\r carriage return \’ single quote
\t horizontal tab \” double quote

cout << a << endl; cout << a << ‘\n’;


cout << “Hi!” << endl; is equivalent to cout << “Hi!\n”;

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;
}

Please input your age, height and weight:

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
}

Please input your age, height and weight: 20 175.5 132

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;
}

Please input your age, height and weight: 20 175.5 132

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 from 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

Take off pajamas Take off pajamas Flow of control is


important. The
correctness of your
Take a shower Get dressed algorithm determines
whether you can get
the desired result.
Get dressed Take a shower

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.

Problem: Adding two input integers A C++ Program


Pseudocode
cout << “Please input the 1st integer:”;
Prompt the user to enter the 1st integer
cin >> x;
Input the 1st integer
cout << “Please input the 2nd integer:”;
Prompt the user to enter the 2nd integer
cin >> y;
Input the 2nd integer
int res = x + y;
Add 1st integer and 2nd integer, store result
cout << res << endl;
Display result

63
Flowchart
• A diagram to illustrate program flow (program logic).
• Used in analyzing, designing, documenting or managing a
program.

Prompt the user to enter the Input the second integer


first integer
Add first integer and second
Input the first integer integer, store result

Prompt the user to enter the


Prompt the user to enter the first integer
second integer

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

Fix the first


syntax error
N Typhoon Y
#8?
Compilation Y
Error?

Go to campus Go to bed again


Run program

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?

A condition Bring an umbrella


N

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

if (mark >= 60)


Y
mark >= 60? cout << “passed”;

Print “passed”
N

Flowchart

69
The if statement
Syntax
if (condition) statement;

• condition: an expression that evaluates to true or false

mark > 60 ‘A’ == ‘a’ 3 – 2 != 0 3–2

• statement: a statement to execute if condition is true

70
The if…else statement
Pseudocode
If student’s mark is greater than or equal to 60
print “passed”
Else
print “failed”

C++ code

if (mark >= 60)


Y
mark >= 60? cout << “passed”;
else
N cout << “failed”;

Print “failed” Print “passed”

Flowchart
71
The if…else statement
Syntax
if (condition)
statement1;
else
statement2;

• condition: an expression that evaluates to true or false


• statement1 is executed if condition is true; and if
condition is false, statement2 is executed.

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.

Always start with


this template for
writing a program
with standard I/O
return 0;
}

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

Always start with


this template for Output max
writing a program
with standard I/O
return 0;
}

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?

Remember to declare and initialize the variables


before using them. Output max

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

integers and outputs the maximum one.


Y
#include <iostream> a > b?
using namespace std;
int main() { N

max = b max = a

Let’s first come up with an algorithm to solve the


problem.
max > c Y
?
N

Output c Output max


return 0;
}

77
Example 2 Read 3 integers:
• Write a program that reads 3 input a, b and c

integers and outputs the maximum one.


Y
#include <iostream> a > b?
using namespace std;
int main() { N
int a, b, c, max;
cin >> a >> b >> c; max = b max = a
if (a > b)
max = a;
else
max = b; max > c Y
if (max > c) ?
cout << max << endl; N
else
cout << c << endl; Output c Output max
return 0;
}

78
Compound Statements
• What if an action involves more than one statement?
Syntax
if (condition) statement;
mark >= 60? Y

a statement can also be a


grade = ‘P’ compound statement or a block of
N
statements enclosed in { and }

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

“Bye bye” “I am sorry” “Yes I do!”

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”;
}

• If you want the 2nd if ( x > 5 ) {


cout to be executed if ( y > 5 )
cout << “x and y are > 5”;
when x <= 5: }
else
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”;

1 How to pair up the if’s and else’s?

2 Conditions for swimming, golfing & tennis?

temperature >= 30 20 <= temperature < 30 temperature < 20

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?

if (mark >= 90 ) if ( mark >= 90 )


cout << "A"; cout << "A";
else if (mark >= 80 ) if ( mark < 90 && mark >= 80 )
cout << "B"; cout << "B";
else if (mark >= 70 ) if ( mark < 80 && mark >= 70 )
cout << "C"; cout << "C";
else if (mark >= 60 ) if ( mark < 70 && mark >= 60 )
cout << "D"; cout << "D";
else if ( mark < 60 )
cout << "F"; cout << "F";

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

Same program outcome but different performance!


92
switch Statement
Syntax • A multi-way branching
switch (controlling_expression) {
case constant_1:
action can also be
statement_1; achieved using a switch
break; statement
case constant_2:
statement_2;
break; The controlling expression in a switch
... statement must return either a
case constant_n: Boolean value, an integer or a character
statement_n;
break;
default:
default_statement; optional
}

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

switch ( age >= 18 ) {


case 1:
cout << “Old enough to vote";
break;
case 0:
cout << “Not old enough to
vote";
break;
}

What is the program output?

If age >= 18 is true, then output “Old enough to vote” to screen;


Otherwise output “Not old enough to vote” to screen

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)

– Using strings of inequalities, e.g.,

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:

condition ? expr1 : expr2


• A conditional expression that evaluates to a value:
– if condition is true, expr1 is the value of the expression
– if condition is false, expr2 is the value of the expression

if (mark >= 60) is equivalent to


cout << “passed”; cout << ((mark >= 60)? “passed” : “failed”);
else
cout << “failed”;
Note: if…else is a statement,
?: is an operator that forms an expression

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

The while statement controls whether to repeat


while (condition) { 1 a loop body depending on a condition.
statement_1; Essentially, the loop body is executed repeatedly
statement_2; as long as condition is true

statement_n;
} 1 execution path when condition is true
2
2 execution path when condition is false

104
while Statement
Syntax Syntax
while (condition) while (condition) {
statement; statement_1;
statement_2;

statement_n;
loop body }

• When a while statement (a.k.a. while loop) is executed, the


condition is evaluated.
– If it returns true, the loop body is executed once (i.e., one iteration).
– If it returns false, the loop ends without executing its body.
• After each iteration, condition will be evaluated again and
the process repeats.
105
while Statement
What does this program do?
#include <iostream>
using namespace std; Asks the user to answer 2 * 2
repeatedly until the user
int main() inputs the correct answer
{
int answer = 0;
while (answer != 4) { What if the user keeps giving
cout << “2 * 2 = ”; a wrong answer?
cin >> answer;
} The program will keep asking
again.
cout << “Correct!” << endl;

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;

while (answer != 4) { What is the loop variable in this example?


cout << “2 * 2 = ”; trials
cin >> answer;
trials++;
}

cout << “Correct!” << endl;


cout << “You’ve tried ” << trials << “ times.” << endl;

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;

int main() How many times will the loop body be


{ executed?
n
int x = 0, total = 0, n;
cout << "Enter the number of values to be added: ";
cin >> n;

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; How many times will the loop body be


while (i < n) { executed?
n
cout << "next number? ";
cin >> x;
total += x;
cout << "Total = " << total << endl;
i++;
}
Enter the number of values to be added: 3↵
next number? 4↵
return 0;
Total = 4
} next number? 3↵
Total = 7
next number? 2↵
Total = 9 110
Screen output?
Typical Structure of a Counter-Controlled Loop
#include <iostream>
using namespace std; loop variable —
to count the no. of iterations
int main()
{
int x = 0, total = 0, i, n;
cout << "Enter # of values to add: ";
cin >> n; initialization of loop variable

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;
}

What if you forgot to update the loop


111
variable?
while Statement
#include <iostream>
using namespace std;
Flag-controlled while loops
int main()
{
use a bool variable to control the iterations
int num = 23;
int guess;
What is the flag in this example?
bool isGuessed;
isGuessed
isGuessed = false;
Screen output?
while (!isGuessed) {
cout << "Make a guess (0-99)? "; Make a guess (0-99)? 48 ↵
cin >> guess; Too large. Guess again? 20 ↵
Too small. Guess again? 35 ↵
if (guess == num) { Too large. Guess again? 23 ↵
cout << "Correct!" << endl; Correct!
isGuessed = true;
} Make a guess (0-99)? 48 ↵
else if (guess < num) Too large. Guess again!
cout << "Too small. Guess again!" << endl;
Make a guess (0-99)? 20 ↵
else Too small. Guess again!
cout << "Too large. Guess again!" << endl;
Make a guess (0-99)? 35 ↵
} Too large. Guess again!
return 0; Make a guess (0-99)? 23 ↵
} Correct! 112
while Statement
What's wrong here? Never put a semicolon after the
parenthesis as it is equivalent to
int i = 0, n = 10; introducing an empty statement
(a.k.a. null statement) as the loop
while (i < n);
{ body. Essentially, this while
cout << "next number? "; statement contains an empty loop
cin >> x; body
total += x;
cout << "Total = " << total << endl;
i++;
}
Will the loop counter be updated?
So what will happen? Try it!

113
Quick Exercise 1
Write a complete C++ program that outputs the
numbers 1 to 20, one per line, using a while loop.

(A sample program can be found at the end of this set


of slides.)

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

1. The initialization is performed.


– Generally, it sets the initial value of the loop variable.
– The initialization is executed only once.
2. The condition is evaluated.
– If it is true, the loop body is executed once (i.e., one iteration).
– If it is false, the loop ends without executing its body.
3. After each iteration, the updating of loop variable
is performed, and the loop continues at Step 2.

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;

for (trials = 0; answer != 4; trials++) {


cout << “2 * 2 = ”;
cin >> answer;
}

cout << “Correct!” << endl;


cout << “You’ve tried ” << trials << “ times.” << endl;

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.

(A sample program can be found at the end of this set


of slides.)

120
Quick Exercise 3
Write a program that calculates the sum of odd
numbers between 1 and 20 using a for loop.

(A sample program can be found at the end of this set


of slides.)

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

As the condition is always true,


#include <iostream> this will be an infinite loop
using namespace std;

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;

cout << count << " ";


}
cout << endl << "Broke out of loop at count = " << count << endl;

1 2 3 4
Screen output?
Broke out of loop at count = 5

for ( int count = 1; count <= 10; ++count) {


if (count == 5) continue;
cout << count << " ";
}

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;

for (i = 9; i >= 0; --i)


cout << i << ‘ ‘;
Try to repeat this exercise with a while loop.
return 0;
}

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!

“If you face any problems in understanding the materials,


please feel free to contact me, our TAs or student TAs.
We are very happy to help you!
We wish you enjoy learning C++ programming in this class .”

130

You might also like