C++ Programming II
Compiled By Mr. Abunu T.
CONTENTS
01. What is programming
02. Building blocks of programs
03. Basic Elements of programming(C++ tokens)
04. Control statements
4.1 Decision statements
4.2 Loop statements
4.3 Flow control statements
1 Computer Programming
◆ Programming refers to a technological process for telling a computer which tasks to perform in
order to solve problems.
◆ You can think of programming as a collaboration between humans and computers, in which
humans create instructions for a computer to follow (code) in a language computers can
understand.
◆ How does computer programming work?
✓ First, a programmer writes code—a set of letters, numbers, and other characters. Next, a
compiler converts each line of code into a language a computer can understand. Then, the
computer scans the code and executes it, thereby performing a task or series of tasks.
2
What is C++
◆ C++ is a general purpose, case-sensitive, free-form programming language that supports
object-oriented, procedural and generic programming.
◆ C++ is an extension of the C programming language
◆ C++ is a general-purpose programming language, created by Bjarne Stroustrup
◆ C++ includes all the elements of the C language plus it has additional features for working
with objects, classes, events, and other object-oriented concepts
3 Structure of C++
Let’s look the following simple C++ program
Hello World
4 Structure of C++
#include : is a preprocessor directive
It instructs the preprocessor to include a section of standard C++ code, known as header
iostream, that allows it to perform standard input and output operations.
The preprocessor reads your program before it is compiled and only executes those
lines beginning with a # symbol.
Think of the preprocessor as a program that “sets up” your source code for the
compiler.
The #include directive causes the preprocessor to include the contents of another file in
the program
5 Structure of C++
The word inside the brackets, iostream , is the name of the file that is to be included
The iostream file contains code that allows a C++ program to display output on the
screen and read input from the keyboard
<iostream> also called standard input-output stream
The contents of the iostream file are included in the program at the point the #include
statement appears.
The iostream file is called a header file, so it should be included at the head, or top, of
the program
6 Structure of C++
#include iostream provides the most used standard input and output streams, cin and cout.
The syntax for using them is as follows:
Standard Output Stream -- cout
It is an instance of the ostream class.
It produces output on the standard output device, i.e., the display screen
We need to use the stream insertion operator << to insert data into the standard output
stream cout, which has to be displayed on the screen
Syntax:
cout << variable_name;
7 Structure of C++
Standard Input Stream -- cin
It is an instance of the istream class
It reads input from the standard input device, i.e., the keyboard.
We need to use the stream extraction operator >> to extract data entered using the
keyboard
Syntax:
cin>>variable_name;
8 Structure of C++
using namespace std;
Programs usually contain several items with unique names. Variables, functions, and
objects are examples of program entities that must have names
C++ uses namespaces to organize the names of program entities
The statement using namespace std; declares that the program will be accessing
entities whose names are part of the namespace called std
The reason the program needs access to the std namespace is because every name
created by the iostream file is part of that namespace
9 Structure of C++
Namespace is a declarative region that provides a scope to the identifiers inside it
Namespaces in C++ provide scope for identifiers like variables, functions, and classes
with the same names.
The identifiers present inside a namespace's scope can be accessed outside the scope
only by using fully qualified names for each identifier
Namespaces are an essential aspect of C++ because they help avoid naming conflicts in
our programs. If namespaces are used, multiple identifiers can have the same names
provided they are defined in separate namespaces
10 Structure of C++
What is a Namespace?
Ex. There are two students with the same name in a classroom. To distinguish the two
students, we need to call them by their names and surnames. A situation like this can occur
in C++ as well. It might happen that a function we created with the name sqrt(), but this is
already present in the cmath library of C++. In this case, the compiler cannot differentiate
between the two function names. Hence, it will yield an error. To avoid this confusion,
namespaces are used.
Namespaces provide a method to avoid name conflicts in a project. In essence a
namespace defines a scope
11 Structure of C++
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the
namespace name as follows: namespace namespace_name
{
Syntax: // code declarations
}
To call the namespace-enabled version of either function or variable, prepend (::) the
namespace name as follows :
name::code; // code could be variable or functions
12
Examples
13
Output
This is custom namespace
The using directive
You can also avoid prepending of namespaces with the using namespace directive
14
The using keyword is used to:
Bring a specific member from the namespace into the current scope.
Bring all members from the namespace intothe current scope.
Bring a base class method or variable into the current class’s scope.
15
Bring a specific member from the namespace into the current scope.
1 and 2 (string & cout ) are specific members of namespace
Output
C++ Programming
16
Bring all members from the namespace intothe current scope
Output
Enter Your Name: Nahom
Your Name is: Nahom
17 int main()
This marks the beginning of a function
A function can be thought of as a group of one or more programming statements that
collectively has a name
The name of this function is main, and the set of parentheses that follows the name
indicate that it is a function
The word int stands for “integer.” It indicates that the function sends an integer value
back to the operating system when it is finished executing
Although most C++ programs have more than one function, every C++ program must
have a function called main .
18 Steps for C++ Program Development and Execution
Execution
Loading
Linking
Compiling
Editing
5
4
3
2
1
19 Editing
Editing refers the typing or writing the program in any text editor.
But we want all the things in one place like writing the program, compiling, and
executing it
This can be achieved using IDE (Integrated Development Environment)
IDE integrated all the tasks that are required to run a program.
Examples of IDE’s: codeblocks, Dev++ etc.
20
Compiling
Consider a program [Link] which is saved in your computer hard disk.
To compile the [Link] file, we need an IDE that contains a compiler. The compiler
converts the high-level code into machine-level language code.
An object file has the .obj or .o file extension and is created for each source code file
after compilation of [Link]
The object file contains all of the machine-level instructions for that file. It is referred
to as an intermediary file because it’s not until the final stage
21 cont..
If you had 3 cpp programs, the compiler would generate three objects.
Source file Source file Source file
[Link] [Link] [Link]
compiled compiled compiled
object file object file object file
Calculator.o Hello.o Addition.o
22 Linking
After the compiler creates one or more object files, then another program called the
linker kicks in.
The job of the linker is three fold:
First, to take all the object files generated by the compiler and combine them into a
single executable program object file : Calculator.o
Linker
Other libraries
C++ standard libraries
Executable file: [Link]
23 Linking
Second, in addition to being able to link object files, the linker also is capable of linking
library files.
A library file is a collection of pre-compiled code that has been “packaged up” for
reuse in other programs.
The built-in objects and functions are grouped inside libraries that can be included in
programs as header files.
These libraries and header files are linked with the code during compilation where the
24 Linking
Third, the linker makes sure all cross-file dependencies are resolved properly.
For example, if you define something in one .cpp file, and then use it in another .cpp
file, the linker connects the two together.
If the linker is unable to connect a reference to something with its definition, you’ll get
a linker error, and the linking process will abort.
Once the linker is finished linking all the object files and libraries (assuming all goes
well), you will have an executable file and you can run the executable file.
25
Loading
To execute the program code, the code must be brought to the main memory from the
secondary memory.
Execution:
As soon as the program gets loaded in the main memory the program execution starts
The execution of the program starts from the first line of the main function.
26 Basic Elements of C++ Program (C++ tokens)
A token is the smallest unit of a program that is meaningful to the compiler
Tokens can categorized as follows
Operators
6 1 Keywords
Symbols
5 C++ tokens
2 Identifiers
Strings 4 3 Constants
27 Keywords
Keywords are pre-defined or reserved words in a programming language
Keywords (also known as reserved words) have special meaning to the C++ compiler
and are always written or typed in short(lower) cases.
They are explicitly reserved identifiers and can’t be used as names for the program
variables or other user defined program elements
28 Identifiers
Identifiers refers to the name of variable, functions, array, class etc. created by
programmer
These are user-defined names consisting of an arbitrarily long sequence of letters and
digits with either a letter or the underscore(_) as a first character.
There are certain rules shat should be followed while naming identifiers
• An identifier name should begin with a letter or an underscore ( _ )
• An identifier name should be made up of letters, digits and underscores only
• Special characters and white spaces are not allowed.
• It should not be a keyword.
• Identifier names are case sensitive.
29 Identifiers
Which of the following is valid identifier and which is not
30 Constants
Constants are also like normal variables. But, the only difference is, their values can
not be modified by the program once they are defined.
Constants refer to fixed values. They are also called literals.
To declare constants: Syntax : const data_type variable_name;
The different types of constants are:
Integer constants – These constants store values of the int data type
const int data = 5;
N.B: const-is a pre-defined keyword which used to declare constant variables in our
program
31 Constants
Floating constants – These constants store values of the float data type
Ex: const float e = 2.71;
Character constants – These constants store values of the character data type.
Ex: const char answer = ‘y’;
String constants – These constants are also of the character data type but differ in the
declaration part.
Ex: const char title[] = ‘‘DataFlair’’;
Ex: const string name = “Programming”;
32 Strings
A string stores a sequence of characters. It terminates with a null character ‘\0’.
Unlike characters, strings in C++ are always enclosed within double quotes (” “).
In C++, there are two types of strings:
C-style strings
Example – char name[ ] = “Information”;
Objects of the string class in the Standard C++ Library
Example – string name = “Systems”;
33 Symbols
The following special symbols are used in C++ has some special meaning
Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.
Comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
34 Symbols
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity.
Asterisk (*): It is used to create a pointer variable and for the multiplication of
variables
Pre-processor (#): The preprocessor is a macro processor that is used automatically
by the compiler to transform your program before actual compilation.
Period (.): Used to access members of a structure or union.
35 Operators
Operators are symbols that trigger an action when applied to C++ variables and other
objects
The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
1
Unary Operators:
Those operators that require only a single operand to act upon are known as unary
operators.
For Example increment and decrement operators (++, - -)
36 Operators
Examples of Unary Operators
Output
5
5
6
37 Operators
2 Binary Operators
Those operators that require two operands to act upon are called binary operators.
Binary operators are classified into :
Arithmetic operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operator
38 Operators
Arithmetic Operators:
These operators are used to perform arithmetic/mathematical operations on operands.
Examples: (+, -, *, /, %,++,–)
Addition operator(‘+’): int x=5, y=10; z=x+y; // prints 15
Subtraction operator(‘-’): int x=5, y=15; z=y-x; //prints 10
Multiplication operator(‘*’): int a=5; b=5; c =a*b; // prints 25
Division operator(‘/’): int a =10, b=2; c=a/b; //prints 5
Modulus operator(‘%’): int a=10,b =2; c=a%b; //prints 0
39 Operators
Example of arithmetic operators
Addition=:18
Substruction=:8
Multiplication=:65
Division=:2
Modulus=:3
40 Operators
Relational Operators:
Relational Operators in C++ which are also known as Comparison Operators used for
comparing the values of two operands
The result of a relational operator is a bool value that can only be true or false according to the
result of the comparison Operator Operation
== Equal To
=! Not Equal To
> Greater Than
< Lesser Than
>= Greater Than Or Equal To
<= Less than or Equal To
41 Operators
Relational Operators:
If the relation is true, it returns 1 whereas if the relation is false, it returns 0.
Now, the following examples show the actual use of operators. Example of relational operator
1) If 10 > 30 then the result is false
2) If 40 > 17 then the result is true
Output
3) If 10 >= 300 then the result is false
4) If 10 <= 10 then the result is true a>b:0
a<b:1
a>=b:0
a<=b:1
a==b:0
a!=b:1
42 Operators
Logical Operators:
Logical operators in C++ are used to evaluate two or more conditions.
They allow a program to make a decision based on multiple conditions.
If the result of the logical operator is true then 1 is returned otherwise 0 is returned.
There are 3 types of logical operators in C++ and they are:
Operator Operation
&& Logical AND
|| Logical OR
! Logical NOT
43 Operators
Example of Logical Operators
Output
Logical &&: 0
Logical ||: 1
Logical Not: 1
44 Control Statements
Programmers can control which instruction to be executed in a program, which is called
flow control or control statement
C++’s program control statements can be put into the following categories:
Selection Statement
1
2 Repetition Statement
Jump Statements
3
45 Selection Statements
Selection statements are statements in a program where there are points at which the
program will decide at run time whether some part of the code should or should not be
executed.
The selection statements allow choosing the set of instructions for execution depending
upon an expression's truth value.
C++ provides the following two types of selection statements:
1 If Statement
2 Switch Statement
46 C++ If Statements
It is sometimes desirable to make the execution of a statement dependent upon a
condition being satisfied.
The different forms of the “If” statement are described as follows:
1 if statement
2 nested if-statement
3 if-else statement
4 if-else-if statement
47 C++ If Statements
if statement
The if statement selects and executes the statement(s) based on a given condition
The simple if statement will decide only one part of the program to be executed if the
condition is satisfied or ignored if the condition fails.
E.g. C++ program to check whether a person is eligible to vote or not
Syntax:
if (expression) {
statement 1;
statement 2;
statement n;
}
Enter Your Age: 20
You Are eligible for voting
48 C++ If Statements
if-else statement
The “if else if” statement allows us to specify two alternative statements
Syntax: Example: C++ program whether a given number is positive or negative
if (expression) {
statement 1;
}
else{
statement 2;
}
Enter Any Number:
15
15 is positive
49 C++ If Statements
if-else-if statement
The “if else if” statement allows us to specify more than two alternative statements
each will be executed based on testing one or more conditions.
Syntax:
if (expression1)
statements1;
else if(expression2)
statements2;
.
else if(expression N)
Statements N;
else
statements
50 Switch statement
C++ provides a multiple-branch selection statement known as a switch (multiple line
statements).
switch(expression) {
The switch statement components: case constant1:
Statement sequence
Switch break;
Case case constant2:
statement sequence
Default break;
case constant3:
Break statement sequence
break;
……….
default:
statement sequence}
51 Switch statement
Example: a C++ program to demonstrate switch statement
Assume a user will enter 5
Output
Thursday
52 Repetition Statements
Repetition statements control a block of code to be executed repeatedly for a fixed
number of times or until a certain condition fails
There are three C++ repetition statements
For-loop statement While-loop statement Do-while-loop statement
53 For-loop statement
For loop is a Entry Controlled Loop
It allows us to write a loop that is executed a specific number of times.
For loop is used to execute a set of statement repeatedly until a particular condition is
for (initialization; condition ; increment/decrement){
satisfied Syntax:
statement(s);
}
initialization - initializes variables and is executed only once
condition - if true, the body of for loop is executed if false, the for loop is terminated
increment/decrement- updates the value of initialized variables and again checks the
condition
54 For-loop statement
Example 1: Program to find the sum of first N natural numbers
Output
Enter Your Number: assume 5 is given
The sum is : 20
55 Range-based for loop in C++
Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range
Used as a more readable equivalent to the traditional for loop operating over a range of
values, such as all elements in a container
This for loop is specifically used with collections such as arrays and vectors.
Its Syntax is:
for ( range_declaration : range_expression)
{
loop_statement;
}
56 Range-based for loop in C++
range_declaration: a declaration of a named variable, whose type is the type of the
element of the sequence represented by range_expression, or a reference to that type.
range_expression: any expression that represents a suitable sequence or a braced-init-
list
loop_statement: any statement, typically a compound statement, which is the body of
// initialize an int array
the loop. int num[3] = {1, 2, 3}; In this example:
// use of ranged for loop rangeDeclaration - int var
for (int var : num) { rangeExpression - num
// code
}
57 Range-based for loop in C++
According to the previous example: the following figure shows that how the range
based for loop is implemented in C++
58 Range-based for loop in C++
Example: using range based for-loop
Output
Value of I: 1
Value of I: 2
Value of I: 3
Value of I: 4
Value of I: 5
59 Example2: Ragne based for-loop using vector
Output
5 10 15 20 25
60 While-loop-statement
is an entry controlled loop statement
Working of while loop:
A while loop evaluates the condition.
If the condition evaluates to true, the code inside the while loop is executed.
The condition is evaluated again.
This process continues until the condition is false.
When the condition evaluates to false, the loop terminates
while (condition) {
Syntax // body of the while loop
}
61 While loop statement
Example of while loop:
Information Systems
Information Systems
Information Systems
Information Systems
Information Systems
62 While loop statement
Example of while loop:
0 2 4 6 8 10
63 Do-While loop statement
The do-while loop is exit-controlled loop.
In do-while loop the loop body will execute at least once irrespective of test condition.
Working of do-while loop
The body of the loop is executed at first. Then the condition is evaluated.
If the condition evaluates to true, the body of the loop inside the do statement is executed again.
The condition is evaluated once again.
If the condition evaluates to true, the body of the loop inside the do statement is executed again.
This process continues until the condition evaluates to false. Then the loop terminates.
64 Do-While loop statement
Do-while loop syntax:
do {
// body of loop;
}
while (condition);
Enter Number: 5
1
2
3
4
5
65 Do-While loop statement
Program to display sum of numbers until the user enter negative number
Enter Number:
1
2
3
4
-5
Sum:= 10
66 Nested loop statement
A loop can be nested inside of another loop
There are different nested loop structures in different control statements.
Nested for loop
for (initialization; condition; update)
{
for (initialization; condition; update)
Syntax: {
// body of inner for-loop
}
// body of outer for-loop
}
67 Nested loop statement
Nested do-while-loop statement in C++ Nested while loop statement in C++
do { while(condition)
statement(s); {
do {
statement(s); while(condition)
} {
while( condition ); statement(s);
} }
while( condition ); outer while loop statement;
}
68 Program to print numbers using nested loop in C++:
Output
00
01
10
11
69 Nested loop statement
Write a program to display the following pattern using nested (for, while, and do
while)statement respectively.
B C
A
1 1
* 22 12
* * 333 123
* * * 4444 1234
* * * * 55555 12345
70 Cont..
Output
*
* *
* * *
* * * *
71 Cont..
Output
1
22
333
4444
55555
72 Cont..
Output
1
12
123
1234
12345
73 C++ Jump Statements
Jump statements are used to obstruct the normal flow of execution of a program
It is used to terminating or continues the loop inside a program or to stop the execution
of a function
Jump statements in C++ mainly have four types :
Continue statements
Break statements
Goto statements
Return statement
74 C++ Jump Statements
Continue Statements:
Continue statement skips any remaining statements in the current iteration and
immediately passes the control to the next iteration
The continue statement does not terminate the loop (as in the case of break
statements), rather it only terminates the current iteration of the loop.
It is used with a decision-making statement which must be present inside the loop.
This statement can be used inside for loop or while or do-while loop.
Syntax: continue;
75 C++ Jump Statements
A program to show the implementation of the continue statement in C++ :
Odd Numbers between 1 to 10
13579
76 C++ Jump Statements
Break Statements:
It is used to terminate the whole loop if the condition is met.
Unlike the continue statement after the condition is met, it breaks the loop and the
remaining part of the loop is not executed.
Break statement is used with decision-making statements such as if, if-else, or switch
statement which is inside the for loop which can be for loop, while loop, or do-while
loop.
It forces the loop to stop the execution of the further iteration.
Syntax: break;
77 C++ Jump Statements
Program to demonstrate break statement
Output
1234
78 C++ Jump Statements
Return statement
The return statements can be used in any part of the function.
The objective of the return statement is to stop the execution of the current function
and transfers the program control to the point from where it has been called
If a return statement is used in the main function, it will stop the compilation process of
the program.
The return statement is also used to transfer a computed value of the function that
belongs to a predefined return type to the variable used to call the function.
Syntax: return expression;
79 C++ Jump Statements
Program to demonstrate return statement
01234
80 C++ Jump Statements
Goto Statements
Like the return statements, the goto statements can be used in any part of a function.
The objective of the goto statement is to jump directly to any part of the function
The goto statement hits the program control to the part of the program defined by a
label.
A label acts as an argument to the goto statement and an identifier, initiating with a
colon(:), defining a piece of code
A label can be placed anywhere in the program, irrespective of the position of the goto
statement
81 C++ Jump Statements
If the label is placed after the goto statement, it is said to be a forward reference.
If the label is placed before the goto statement, it is said to be a backward reference.
Diagram to show forward and backward reference in the goto statement:
82 Examples
Backward reference Forward reference
THANK YOU!
Any Questions??
You can find me at
abunutesfaw@[Link]
abunu@[Link]