C++ Programming II: Compiled by Mr. Abunu T
C++ Programming II: Compiled by Mr. Abunu T
Hello World
4 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++
Syntax:
cin>>variable_name;
8 Structure of C++
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++
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
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
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
If you had 3 cpp programs, the compiler would generate three objects.
Linker
Other libraries
C++ standard libraries
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)
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
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=: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 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
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;
}
Output
Thursday
52 Repetition Statements
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++
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++
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
Information Systems
Information Systems
Information Systems
Information Systems
Information Systems
62 While loop statement
0 2 4 6 8 10
63 Do-While loop statement
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
} }
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
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
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.
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
[email protected]
[email protected]