ENG2139 Lecture 2
ENG2139 Lecture 2
Time Allocation
• Lectures 2 hours/week
• Laboratory/ Tutorials 3 hours/week
6
• Use if to specify a block of code to be
executed, if a specified condition is true
• Use else to specify a block of code to be
executed, if the same condition is false
• Use else if to specify a new condition to test, if
the first condition is false
• Use switch to specify many alternative blocks
of code to be executed
7
The if Statement
if (condition) {
// block of code to be executed if the condition is true
}
• Note that if is in lowercase letters. Uppercase
letters (If or IF) will generate an error
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
8
C++ Else
• if (condition) {
• // block of code to be executed if the condition is true
• } else {
• // block of code to be executed if the condition is false
• }
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
9
The else if Statement
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
• if (condition1) {
• // block of code to be executed if condition1 is true
• } else if (condition2) {
• // block of code to be executed if the condition1 is false and condition2
is true
• } else {
• // block of code to be executed if the condition1 is false and condition2
is false
• } 10
C++ Short Hand If Else
• There is also a short-hand if else, which is known as the
ternary operator because it consists of three operands.
• It can be used to replace multiple lines of code with a
single line. It is often used to replace simple if else
statements:
• variable = (condition) ? expressionTrue : expressionFalse;
11
C++ Switch
• Use the switch statement to select one of many code
blocks to be executed.
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
12
• This is how it works:
– The switch expression is evaluated once
– The value of the expression is compared with the
values of each case
– If there is a match, the associated block of code is
executed
– The break and default keywords are optional, and
will be described later in this chapter
13
The break Keyword
• When C++ reaches a break keyword, it breaks
out of the switch block.
• This will stop the execution of more code and
case testing inside the block.
• When a match is found, and the job is done, it's
time for a break. There is no need for more
testing
• The default keyword specifies some code to run
if there is no case match:
14
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
15
C++ While Loop
• The while loop loops through a block of code as
long as a specified condition is true:
• while (condition) {
• // code block to be executed
• }
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
16
The Do/While Loop
• The do/while loop is a variant of the while
loop. This loop will execute the code block
once, before checking if the condition is true,
then it will repeat the loop as long as the
condition is true.
do {
// code block to be executed
}
while (condition);
17
• The example below uses a do/while loop. The
loop will always be executed at least once, even
if the condition is false, because the code block is
executed before the condition is tested:
• Do not forget to increase the variable used in the
condition, otherwise the loop will never end!
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
18
C++ For Loop
• When you know exactly how many times you
want to loop through a block of code, use the
for loop instead of a while loop:
19
• Statement 1 is executed (one time) before the
execution of the code block.
• Statement 2 defines the condition for
executing the code block.
• Statement 3 is executed (every time) after the
code block has been executed.
20
Nested Loops
• It is also possible to place a loop inside another loop. This is
called a nested loop.
• The "inner loop" will be executed one time for each iteration of
the "outer loop":
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}
}
21
The foreach Loop
• There is also a "for-each loop" (introduced in
C++ version 11 (2011), which is used
exclusively to loop through elements in an
array (or other data sets):
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
22
C++ Break and Continue
• The break statement can also be used to jump out
of a loop.
• This example jumps out of the loop when i is equal
to 4:
25
• We have now declared a variable that holds an
array of four strings. To insert values to it, we
can use an array literal - place the values in a
comma-separated list, inside curly braces:
• string cars[4] = {"Volvo", "BMW", "Ford",
"Mazda"};
• To create an array of three integers, you could
write:
• int myNum[3] = {10, 20, 30};
26
Access the Elements of an Array
• You access an array element by referring to
the index number inside square brackets [].
• This statement accesses the value of the first
element in cars:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo
27
Loop Through an Array
• You can loop through the array elements with
the for loop.
• The following example outputs all elements in
the cars array:
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda",
"Tesla"};
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}
28
C++ Omit Array Size
• In C++, you don't have to specify the size of the
array. The compiler is smart enough to determine
the size of the array based on the number of
inserted values:
• It is also possible to declare an array without
specifying the elements on declaration, and add
them later:
string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements
string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array
elements
string cars[5];
29
Get the Size of an Array
• To get the size of an array, you can use the
sizeof() operator:
• To find out how many elements an array has,
you have to divide the size of the array by the
size of the data type it contains:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {
cout << myNumbers[i] << "\n";
}
30
Multi-Dimensional Arrays
• A multi-dimensional array is an array of arrays.
• To declare a multi-dimensional array, define
the variable type, specify the name of the
array followed by square brackets which
specify how many elements the main array
has, followed by another set of square
brackets which indicates how many elements
the sub-arrays have:
31
• As with ordinary arrays, you can insert values
with an array literal - a comma-separated list
inside curly braces. In a multi-dimensional
array, each element in an array literal is
another array literal.
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
32
Access the Elements of a Multi-Dimensional
Array
• To access an element of a multi-dimensional array,
specify an index number in each of the array's
dimensions.
• This statement accesses the value of the element in the
first row (0) and third column (2) of the letters array.
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
33
Change Elements in a Multi-Dimensional
Array
• To change the value of an element, refer to
the index number of the element in each of
the dimensions:
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";
35
C++ Structures
• Structures (also called structs) are a way to group several
related variables into one place. Each variable in the
structure is known as a member of the structure.
38
Named Structures
• By giving a name to the structure, you can treat it as a
data type. This means that you can create variables with
this structure anywhere in the program at any time.
39
• To declare a variable that uses the structure, use the name of the
structure as the data type of the variable:
struct car {
string brand;
string model;
int year;
};
int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
41