You are on page 1of 25

Intermediate PL Handout 2023

Chapter - three
Basics of C++

3.1 Structure of a program


A digital computer is a useful tool for solving a great variety of problems. A solution to a
problem is called an algorithm; it describes the sequence of steps to be performed for the
problem to be solved. A simple example

Problem: Sort a list of names in ascending lexicographic order.


Algorithm: Call the given list list1; create an empty list, list2, to hold the sorted
list. Repeatedly find the ‘smallest’ name in list1, remove it from list1, and make it the next entry
of list2, until list1 is empty.

An algorithm is expressed in abstract terms. To be intelligible to a computer, it needs to be


expressed in a language understood by it. The only language really understood by a computer is
its own machine language. Programs expressed in the machine language are said to be
executable. A program written in any other language needs to be first translated to the machine
language before it can be executed.
A machine language is far too cryptic to be suitable for the direct use of programmers. A further
abstraction of this language is the assembly language which provides mnemonic names for the
instructions and a more intelligible notation for the data. An assembly language program is
translated to machine language by a translator called an assembler. Even assembly languages are
difficult to work with. High-level languages such as C++ provide a much more convenient
notation for implementing algorithms. They liberate programmers from having to think in very
low-level terms, and help them to focus on the algorithm instead. A program written in a high-
level language is translated to assembly language by a translator called a compiler. The
assembly code produced by the compiler is then assembled to produce an executable program.

Example 1.1 shows our first C++ program, which when run, simply outputs the message

Hello World.

1. // my first C++ program


2. #include <iostream>
3. using namespace std;
4.
5. int main ()
6. {
7. cout << "Hello World!";
8. return 0; Output
9. }

1 of 16 | P a g e
Intermediate PL Handout 2023

The previous program is the typical program that programmer apprentices write for the first time,
and its result is the printing on screen of the "Hello World!" sentence. It is one of the simplest
programs that can be written in C++, but it already contains the fundamental components that
every C++ program has. We are going to look line by line at the code we have just written:

// my first program in C++


This is a comment line. All lines beginning with two slash signs (//) are considered
comments and do not have any effect on the behavior of the program. The programmer can use
them to include short explanations or observations within the source code itself. In this case, the
line is a brief description of what our program is. C++ supports two ways to insert comments:
// line comment
/* block comment */

#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular
code lines with expressions but indications for the compiler's preprocessor. In this case the
directive #include<iostream> tells the preprocessor to include the iostream standard file. This
specific file (iostream) includes the declarations of the basic standard input-output library in
C++, and it is included because its functionality is going to be used later in the program.

using namespace std;


All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this
expression that we will be using these entities. This line is very frequent in C++ programs that
use the standard library, and in fact it will be included in most of the source codes included in
these course.

int main ()
This line corresponds to the beginning of the definition of the main function. The main function
is the point by where all C++ programs start their execution, independently of its location within
the source code. It does not matter whether there are other functions with other names defined
before or after it – the instructions contained within this function's definition will always be the
first ones to be executed in any C++ program. For that same reason, it is essential that all C++
programs have a main function.

The word main is followed in the code by a pair of parentheses (()). That is because it is a
function declaration: In C++, what differentiates a function declaration from other types of
expressions are these parentheses that follow its name. Optionally, these parentheses may
enclose a list of parameters within them.

Right after these parentheses we can find the body of the main function enclosed in braces ({}).
What is contained within these braces is what the function does when it is executed.

cout << "Hello World!";

2 of 16 | P a g e
Intermediate PL Handout 2023

This line is a C++ statement. A statement is a simple or compound expression that can actually
produce some effect. In fact, this statement performs the only action that generates a visible
effect in our first program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to
insert a sequence of characters (in this case the Hello World sequence of characters) into the
standard output stream (which usually is the screen).

cout is declared in the iostream standard file within the std namespace, so that's why we needed
to include that specific file and to declare that we were going to use this specific namespace
earlier in our code.
.
Notice that the statement ends with a semicolon character (;). This character is used to mark the
end of the statement and in fact it must be included at the end of all expression statements in all
C++ programs (one of the most common syntax errors is indeed to forget to include some
semicolon after a statement).

return 0;
The return statement causes the main function to finish. return may be followed by a return code
(in our example is followed by the return code 0). A return code of 0 for the main function is
generally interpreted as the program worked as expected without any errors during its execution.
This is the most usual way to end a C++ console program.

You may have noticed that not all the lines of this program perform actions when the code is
executed. There were lines containing only comments (those beginning by //). There were lines
with directives for the compiler's preprocessor (those beginning by #). Then there were lines that
began the declaration of a function (in this case, the main function) and, finally lines with
statements (like the insertion into cout), which were all included within the block delimited by
the braces ({}) of the main function.

The program has been structured in different lines in order to be more readable, but in C++, we
do not have strict rules on how to separate instructions in different lines. For example, instead of

int main ()
{
cout << " Hello World!";
return 0;
}

We could have written:

int main () { cout << "Hello World!"; return 0; }

All in just one line and this would have had exactly the same meaning as the previous code.

In C++, the separation between statements is specified with an ending semicolon (;) at the end of
each one, so the separation in different code lines does not matter at all for this purpose. We can

3 of 16 | P a g e
Intermediate PL Handout 2023

write many statements per line or write a single statement that takes many code lines. The
division of code in different lines serves only to make it more legible and schematic for the
humans that may read it.

3.2 How C++ Compilation Works


Compiling a C++ program involves a number of steps (most of which are transparent to the
user):


 First, the C++ preprocessor goes over the program text and carries out the instructions
specified by the preprocessor directives (e.g. #include). The result is a modified program
text which no longer contains any directives.

 Then, the C++ compiler translates the program code. The compiler may be a true C++
compiler which generates native (assembly or machine) code, or just a translator which
translates the code into C. In the latter case, the resulting C code is then passed through a
C compiler to produce native object code. In either case, the outcome may be incomplete
due to the program referring to library routines which are not defined as a part of the
program. For example, Example 1.1 refers to the << operator which is actually defined
in a separate IO library.

 Finally, the linker completes the object code by linking it with the object code of any
library modules that the program may have referred to. The final result is an executable
file.

Figure 3.1 illustrates the above steps for both a C++ translator & a C++ native compiler. In
practice all these steps are usually invoked by a single command (e.g. CC) and the user will not
even see the intermediate files generated.

Figure 3.1: C++ Compiler Structure

4 of 16 | P a g e
Intermediate PL Handout 2023

3.3 Variables
A variable is a symbolic name for a memory location in which data can be stored and
subsequently recalled. Variables are used for holding data values so that they can be utilized in
various computations in a program. All variables have two important attributes:
 A type which is established when the variable is defined (e.g. integer, real, character).
Once defined, the type of a C++ variable cannot be changed.

 A value which can be changed by assigning a new value to the variable. The kind of
values a variable can assume depends on its type. For example, an integer variable can
only take integer values (e.g. 2, 100, and -12).

When a variable is defined, its value is undefined until it is actually assigned one. The assigning
of a value to a variable for the first time is called initialization. It is important to ensure that a
variable is initialized before it is used in any computation. It is possible to define a variable and
initialize it at the same time. This is considered a good programming practice, because it pre-
empts the possibility of using the variable prior to it being initialized.

#include <iostream>
using namespace std;

int main ()
{
int workDays = 5;
float workHours = 7.5;
float payRate = 38.55;
float weeklyPay = workDays * workHours * payRate;
cout << "Weekly Pay = weeklyPay \n";

Simple Input/output: The most common way in which a program communicates with the
outside world is through simple, character-oriented Input/output (IO) operations. C++ provides
two useful operators for this purpose: >> for input and << for output. The input operator >> takes
an input stream as its left operand (cin is the standard C++ input stream which corresponds to
data entered via the keyboard) and a variable (to which the input data is copied) as its right
operand.

Both << and >> return their left operand as their result, enabling multiple input or multiple
output operations to be combined into one statement.

cin >> workHours >> payRate;


cout << "Weekly Pay = " << weeklyPay << '\n';

Comments: A comment is a piece of descriptive text which explains some aspect of a program.
Program comments are totally ignored by the compiler and are only intended for human readers.

5 of 16 | P a g e
Intermediate PL Handout 2023

C++ provides two types of comment delimiters:


 Anything after // (until the end of the line on which it appears) is considered a
comment.

 Anything enclosed by the pair /* and */ is considered a comment.

Comments should be used to enhance (not to hinder) the readability of a program. The
following two points, in particular, should be noted:
 A comment should be easier to read and understand than the code which it tries to
explain. A confusing or unnecessarily-complex comment is worse than no comment
at all.

 Over-use of comments can lead to even less readability. A program which contains
so much comment that you can hardly see the code can by no means be considered
readable.

 Use of descriptive names for variables and other entities in a program, and proper
indentation of the code can reduce the need for using comments.

Memory: A computer provides a Random Access Memory (RAM) for storing executable
program code as well as the data the program manipulates. This memory can be thought of as a
contiguous sequence of bits, each of which is capable of storing a binary digit (0 or 1). Typically,
the memory is also divided into groups of 8 consecutive bits (called bytes). The bytes are
sequentially addressed. Therefore each byte can be uniquely identified by its address.

The C++ compiler generates executable code which maps data entities to memory locations. For
example, the variable definition

int salary = 65000;

causes the compiler to allocate a few bytes to represent salary. The exact number of bytes
allocated and the method used for the binary representation of the integer depends on the specific
C++ implementation but the compiler uses the address of the first byte at which salary is
allocated to refer to it.

Integer Numbers: An integer variable may be defined to be of type short, int, or long. The only
difference is that an int uses more or at least the same number of bytes as a short, and a long uses
more or at least the same number of bytes as an int.

By default, an integer variable is assumed to be signed (i.e. have a signed representation so that it
can assume positive as well as negative values). However, an integer can be defined to be
unsigned by using the keyword unsigned in its definition.

A literal integer (e.g. 1984) is always assumed to be of type int, unless it has an L or l suffix, in
which case it is treated as a long.
6 of 16 | P a g e
Intermediate PL Handout 2023

Literal integers can be expressed in decimal, octal, and hexadecimal notations. The decimal
notation is the one we have been using so far. An integer is taken to be octal if it is preceded by a
zero (0), and hexadecimal if it is preceded by a 0x or 0X. For example:

92 // decimal
0134 // equivalent octal
0x5C // equivalent hexadecimal

Octal numbers use the base 8, and can therefore only use the digits 0-7. Hexadecimal numbers
use the base 16, and therefore use the letter A-F (or a-f) to represent, respectively, 10-15. Octal
and hexadecimal numbers are calculated as follows:

0134 = 1 × 82 + 3 × 81 + 4 × 80 = 64 + 24 + 4 = 92
0x5C = 5 × 161 + 12 × 160 = 80 + 12 = 92

Real Numbers: A real variable may be defined to be of type float or double. The latter uses
more bytes and therefore offers a greater range and accuracy for representing real numbers. For
example, a float uses 4 and a double uses 8 bytes.

float interestRate = 0.06;


double pi = 3.141592654;

A literal real (e.g. 0.06) is always assumed to be of type double, unless it has an F or f suffix, in
which case it is treated as a float, or an L or l suffix, in which case it is treated as a long double.
The latter uses more bytes than a double for better accuracy.

Characters: A character variable is defined to be of type char. A character variable occupies a


single byte which contains the code for the character. This code is a numeric value and depends
on the character coding system being used (i.e. is machine-dependent). The most common
system is ASCII (American Standard Code for Information Interchange). For example, the
character A has the ASCII code 65, and the character a has the ASCII code 97.

char ch = 'A';

Like integers, a character variable may be specified to be signed or unsigned. By the default (on
most systems) char means signed char. However, on some systems it may mean unsigned char. A
signed character variable can hold numeric values in the range -128 through 127. An unsigned
character variable can hold numeric values in the range 0 through 255. As a result, both are often
used to represent small integers in programs (and can be assigned numeric values like integers):

signed char offset = -88;


unsigned char row = 2, column = 26;

A literal character is written by enclosing the character between a pair of single quotes (e.g. 'A').
Nonprintable characters are represented using escape sequences. For example:

7 of 16 | P a g e
Intermediate PL Handout 2023

'\n' // new line


'\r' // carriage return
'\t' // horizontal tab
'\v' // vertical tab
'\b' // backspace

Single and double quotes and the backslash character can also use the escape notation:

'\'' // single quote (')


'\"' // double quote (")
'\\' // backslash (\)

Strings: A string is a consecutive sequence (i.e., array) of characters which are terminated by a
null character. A string variable is defined to be of type char* (i.e. a pointer to character). A
pointer is simply the address of a memory location. A string variable, therefore, simply contains
the address of where the first character of a string appears. For example, consider the definition:

char *str = "HELLO";

Figure 3.2 illustrates how the string variable str and the string "HELLO" might appear in
memory.

Figure 3.2: String and a string variable in memory

A literal string is written by enclosing its characters between a pair of double quotes (e.g.
"HELLO"). The compiler always appends a null character to a literal string to mark its end. A
long string may extend beyond a single line, in which case each of the preceding lines should be
terminated by a backslash. For example:

"Example to show \
the use of backslash for \
writing a long string"

The backslash in this context means that the rest of the string is continued on the next line. The
above string is equivalent to the single line string:

"Example to show the use of backslash for writing a long string"

A common programming error results from confusing a single-character string (e.g. "A") with a
single character (e.g. 'A'). These two are not equivalent. The former consists of two bytes (the
character 'A' followed by the character '\0'), whereas the latter consists of a single byte. The
shortest possible string is the null string (“”) which simply consists of the null character.

8 of 16 | P a g e
Intermediate PL Handout 2023

Names: Programming languages use names to refer to the various entities that make up a
program. Names are a programming convenience, which allow the programmer to organize what
would otherwise be quantities of plain data into a meaningful and human-readable collection.
C++ imposes the following rules for creating valid names (also called identifiers). A name
should consist of one or more characters, each of which may be a letter (i.e. 'A'-'Z' and 'a'-'z'), a
digit (i.e. '0'-'9'), or an underscore character ('_'), except that the first character may not be a digit.
Upper and lower case letters are distinct. For example:

salary // valid identifier


salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
_salary // valid identifier
Salary // valid but distinct from salary

C++ imposes no limit on the number of characters in an identifier. However, most


implementation do. But the limit is usually so large that it should not cause a concern (e.g. 255
characters).

3.3.1 Declaration of variables

In C++ (as in many other programming languages) all the variables that a program is going to
use must be declared prior to use. Declaration of a variable serves two purposes:

 It associates a type and an identifier (or name) with the variable. The type allows the
compiler to interpret statements correctly. For example in the CPU the instruction to add
two integer values together is different from the instruction to add two floating-point
values together. Hence the compiler must know the type of the variables so it can
generate the correct add instruction.

 It allows the compiler to decide how much storage space to allocate for storage of the
value associated with the identifier and to assign an address for each variable which can
be used in code generation.

A typical set of variable declarations that might appear at the beginning of a program could be as
follows:

int i, j, count;
float sum, product;
char ch;

which declares integer variables i, j and count, real variables sum and product, a character
variable ch.

A variable declaration has the form:


type identifier-list;

9 of 16 | P a g e
Intermediate PL Handout 2023

type specifies the type of the variables being declared. The identifierlist is a list of the identifiers
of the variables being declared, separated by commas. Variables may be initialised at the time of
declaration by assigning a value to them as in the following example:

int i, j, count = 0;
float sum = 0.0, product;
char ch = '7';

which assigns the value 0 to the integer variable count and the value 0.0 to the real variable sum.
The character variable ch is initialised with the character 7. i, j, and product have no initial value
specified, so the program should make no assumption about their contents.

To see what variable declarations look like in action within a program, we are going to see the
following C++ code.

1. // operating with variables


2. #include <iostream>
3. using namespace std;
4. int main ()
5. {
6. // declaring variables:
7. int a, b;
8. int result;
9. // process:
10. a = 5;
11. b = 2;
12. a = a + 1;
13. result = a - b;
14. // print out the result:
15. cout << result;
16. // terminate the program:
17. return 0;
18. }
Do not worry if something else than the variable declarations themselves looks a bit strange to
you. You will see the rest in detail in coming sections.

3.3.2 Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you may want
a variable to store a concrete value at the same moment that it is declared. In order to do that, you
can initialize the variable. There are two ways to do this in C++:

The first one, known as c-like, is done by appending an equal sign followed by the value to
which the variable will be initialized:

type identifier = initial_value ;

10 of 16 | P a g e
Intermediate PL Handout 2023

For example, if we want to declare an int variable called a initialized with a value of 0 at the
moment in which it is declared, we could write:

int a = 0;

The other way to initialize variables, known as constructor initialization, is done by enclosing the
initial value between parentheses (()):

type identifier (initial_value) ;

For example:
int a (0);

Both ways of initializing variables are valid and equivalent in C++.

1. // initialization of variables
2. #include <iostream>
3. using namespace std;
4. int main ()
5. {
6. int a=5; // initial value = 5
7. int b(2); // initial value = 2
8. int result; // initial value undetermined
9. a = a + 3;
10. result = a - b;
11. cout << result;
12. return 0;
13. }

Certain words are reserved by C++ for specific purposes and may not be used as identifiers.
These are called reserved words or keywords and which are summarized in the following Table
3.1:

11 of 16 | P a g e
Intermediate PL Handout 2023

3.2 Expressions
This section introduces the built-in C++ operators for composing expressions. An expression is
any computation which yields a value.

When discussing expressions, we often use the term evaluation. For example, we say that an
expression evaluates to a certain value. Usually the final value is the only reason for evaluating
the expression. However, in some cases, the expression may also produce side-effects. These are
permanent changes in the program state. In this sense, C++ expressions are different from
mathematical expressions.

C++ provides operators for composing arithmetic, relational, logical, bitwise, and conditional
expressions. It also provides operators which produce useful side-effects, such as assignment,
increment, and decrement. The precedence rules which govern the order of operator evaluation
in a multi-operator expression.

Arithmetic Operators: C++ provides five basic arithmetic operators. These are summarized in
Table 2.1.

Table 3.2: Arithmetic operators

Except for remainder (%) all other arithmetic operators can accept a mix of integer and real
operands. Generally, if both operands are integers then the result will be an integer. However, if
one or both of the operands are reals then the result will be a real (or double to be exact). When
both operands of the division operator (/) are integers then the division is performed as an integer
division and not the normal division we are used to.

Integer division always results in an integer outcome (i.e., the result is always rounded down).
For example:

9 / 2 // gives 4, not 4.5!


-9 / 2 // gives -5, not -4!

Unintended integer divisions are a common source of programming errors. To obtain a real
division when both operands are integers one of the operands should be real:

int cost = 100;


int volume = 80;

12 of 16 | P a g e
Intermediate PL Handout 2023

double unitPrice = cost / (double) volume; // gives 1.25

The remainder operator (%) expects integers for both of its operands. It returns the remainder of
integer-dividing the operands. For example 13%3 is calculated by integer dividing 13 by 3 to
give an outcome of 4 and a remainder of 1; the result is therefore 1. It is possible for the outcome
of an arithmetic operation to be too large for storing in a designated variable. This situation is
called an overflow. The outcome of an overflow is machine-dependent and therefore undefined.
For example:

unsigned char k = 10 * 92; // overflow: 920 > 255

It is illegal to divide a number by zero. This results in a run-time division-by zero failure which
typically causes the program to terminate.

Relational Operators: C++ provides six relational operators for comparing numeric quantities.
Relational operators evaluate to 1 (representing the true outcome) or 0 (representing the false
outcome).

Table 3.3: Relational operators

Note that the <= and >= operators are only supported in the form shown. In particular, =< and =>
are both invalid and do not mean anything.

The operands of a relational operator must evaluate to a number. Characters are valid operands
since they are represented by numeric values. For example (assuming ASCII coding):

'A' < 'F' // gives 1 (is like 65 < 70)

The relational operators should not be used for comparing strings, because this will result in the
string addresses being compared, not the string contents. For example, the expression

"HELLO" < "BYE"

causes the address of "HELLO" to be compared to the address of "BYE". As these addresses are
determined by the compiler (in a machine-dependent manner), the outcome may be 0 or may be
1, and is therefore undefined.

13 of 16 | P a g e
Intermediate PL Handout 2023

Logical Operators: C++ provides three logical operators for combining logical expression. Like
the relational operators, logical operators evaluate to 1 or 0.

Table 3.4: Logical operators

Logical Negation is a unary operator, which negates the logical value of its single operand. If its
operand is nonzero it produce 0, and if it is 0 it produces 1. Logical AND produces 0 if one or
both of its operands evaluate to 0. Otherwise, it produces 1. Logical OR produces 0 if both of its
operands evaluate to 0. Otherwise, it produces 1. In general, any nonzero value can be used to
represent the logical true, whereas only zero represents the logical false. The following are,
therefore, all valid logical expressions:

!20 // gives 0
10 && 5 // gives 1
10 || 5.5 // gives 1
10 && 0 // gives 0
Increment/Decrement Operators: The auto increment (++) & auto decrement (--) operators
provide a convenient way of, respectively, adding and subtracting 1 from a numeric variable.

Table 3.5: Increment/decrement operators


Both operators can be used in prefix and postfix form. The difference is significant. When used
in prefix form, the operator is first applied and the outcome is then used in the expression. When
used in the postfix form, the expression is evaluated first and then the operator applied.

Assignment Operator: The assignment operator is used for storing a value at some memory
location (typically denoted by a variable). An l value (standing for left value) is anything that
denotes a memory location in which a value may be stored. Its left operand should be an l value,
and its right operand may be an arbitrary expression. The latter is evaluated and the outcome is
stored in the location denoted by the l value.

An assignment operation is itself an expression whose value is the value stored in its left
operand. An assignment operation can therefore be used as the right operand of another
assignment operation. The assignment operator has a number of variants, obtained by combining
it with the arithmetic and bitwise operators.
14 of 16 | P a g e
Intermediate PL Handout 2023

Table 3.6: Assignment operators

Any number of assignments can be concatenated in this fashion to form one expression. For
example:

int m, n, p;
m = n = p = 100; // means: n = (m = (p = 100));
m = (n = p = 100) + 2; // means: m = (n = (p = 100)) + 2;

This is equally applicable to other forms of assignment. For example:

m = 100;
m += n = p = 10; // means: m = m + (n = p = 10);

Operator Precedence: The order in which operators are evaluated in an expression is significant
and is determined by precedence rules. Operators in higher levels take precedence over operators
in lower levels.

15 of 16 | P a g e
Intermediate PL Handout 2023

Table 3.7: Operator precedence levels

Operators with the same precedence level are evaluated in the order specified by the last column
of Table 2.7. For example, in

a = b += c

The evaluation order is right to left, so first b += c is evaluated, followed by a = b.

16 of 16 | P a g e
Intermediate PL Handout 2023

Control statement

When a program is run, the CPU begins execution at the top of main (), executes some
number of statements, and then terminates at the end of main (). The sequence of
statements that the CPU executes is called the program’s path. Most of the programs
you have seen in the previous chapter have been straight-line programs. Straight-line
programs have sequential flow -- that is, they take the same path (execute the same
statements) every time they are run (even if the user input changes). C++ provides
control flow statements (also called flow control statements), which allow the
programmer to change the CPU’s path through the program. A conditional branch is a
statement that causes the program to change the path of execution based on the value of
an expression. The most basic conditional branch is an if statement, if...else, nested
if...else if. and switch statements.

If Statement
The if statement checks whether the test condition is true or not. If the test condition is
true, it executes the code/s inside the body of if statement. But if the test condition is
false, it skips the code/s inside the body of if statement.
Syntax:
if (expression)
{
Statement;
}
If the expression evaluates to true (non-zero), the statement executes. If the expression
evaluates to false, not thing happen.

17 of 16 | P a g e
Intermediate PL Handout 2023

2 If...else
The if...else executes body of if when the test expression is true and executes the body of
else if test expression is false. The if statement checks whether the test expression is true
or not. If the test condition is true, it executes the code/s inside the body of if statement.
But it the test condition is false, it executes the code/s inside the body of else.

18 of 16 | P a g e
Intermediate PL Handout 2023

Syntax:
if(boolean_expression)
{
// statement(s) will execute if the Boolean expression is true
}
else
{
// statement(s) will execute if the Boolean expression is false
}

19 of 16 | P a g e
Intermediate PL Handout 2023

3 Nested if statement

Nested if...else are used if there are more than one test expression. The nested if...else
statement has more than one test expression. If the first test expression is true, it
executes the code inside the braces { } just below it. But if the first test expression is
false, it checks the second test expression. If the second test expression is true, if
executes the code inside the braces { } just below it. This process continues. If all the test
expression are false, code/s inside else is executed and the control of program jumps
below the nested if...else.

20 of 16 | P a g e
Intermediate PL Handout 2023

Syntax:
if (test expression1)
{
statement/s to be executed if test expression1 is true;
}
else if(test expression2)
{
statement/s to be executed if test expression1 is false and 2 is true;
}
else if (test expression 3)
{
statement/s to be executed if text expression1 and 2 are false and 3 is true;
}..
else
{
statements to be executed if all test expressions are false;
}

21 of 16 | P a g e
Intermediate PL Handout 2023

4 Switch statements
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each case.
Syntax: The syntax for a switch statement in C++ is as follows:

22 of 16 | P a g e
Intermediate PL Handout 2023

23 of 16 | P a g e
Intermediate PL Handout 2023

24 of 16 | P a g e
Intermediate PL Handout 2023

What is the output of the following program?

25 of 16 | P a g e

You might also like