ITEC1030_Ch03_Elements of Programming Language (2)
ITEC1030_Ch03_Elements of Programming Language (2)
Department of information
Technology
Programming using C++
_________________________________________
@ 2024 FTVT Institute All Rights Reserved
2
Outline
1.1 Basics of C++
1.1.1 Structure of C++ Program;
1.1.2 Keywords, Identifiers, Inputs, Outputs, Comments,
1.1.3 Parts of a program; Data Types, Variables, and Constants
1.1.4 Operators;
1.1.5 Assignment Operators;
1.1.6 Compound Assignment Operators;
1.1.7 Arithmetic Operators;
1.1.8 Relational Operators;
1.1.9 Increment and Decrement Operators; Infix and postfix types;
1.1.10 Precedence of Operators
1.2 Control Statements
1.2.1 If statements: If…else, nested if
1.2.2 Switch Statements: multiple cases, break ,and default
1.2.3 Looping: for, while, do, break, and
3
Department of Information AUGUST
The IDLE Programming Environment
• The complete development cycle in C++ is: Write the program(Edit),Preprocess, compile the source
code, link the program, and run it.
• C++ programs typically go through five phases to be executed: these are
• edit,
• preprocess,
• compile,
• link,
• Load
Writing a Program
• To write a source code, your compiler may have its own built-in text editor, or you may be using a
commercial text editor or word processor that can produce text files.
• This is accomplished with an editor program.
• The programmer types C++ statements with the editor and makes corrections if necessary
• The programs source file is then stored on secondary storage device such as a disk with a “.cpp” file
name.
• After the program is edited, C++ is principally compiled in three phases: preprocessing, translation
to object code, and linking
4
Department of Information AUGUST
Preprocess
• In a C++ system, a preprocessor program executes automatically before the compiler’s translation phase begins.
• The C++ preprocessor obeys command called preprocessor directives, which indicate that certain manipulations are
to be performed on the program before compilation.
• The preprocessor is invoked by the compiler before the program is converted to machine language.
• 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.
Compiling
• Your source code file can't be executed, or run, as a program can.
• How you invoke your compiler, and how you tell it where to find your source code, will vary from compiler to compiler
• This is still not an executable program, however to turn this into an executable program, you must run your linker.
OF-FTI-ALL -18 5 5
Department of Information AUGUST
Linking
• C++ programs are typically created by linking together one or more OBJ files with one or more
libraries.
• A library is a collection of linkable files that were supplied with your compiler, that you purchased
separately, or that you created and compiled.
• All C++ compilers come with a library of useful functions (or procedures) and classes that you can
include in your program.
• A function is a block of code that performs a service, such as adding two numbers or printing to the
screen.
• A class is a collection of data and related functions.
• A linker links the object code with the code for the missing function to produce an executable image
(with no missing pieces).
• Generally, 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
OF-FTI-ALL -18 6 6
Department of Information AUGUST
Loading
• The loader takes the executable file from disk and transfers it to memory.
• Additional components from shared libraries that support the program are also loaded.
• Finally, the computer, under the control of its CPU, executes the program.
• In practice all these steps are usually invoked by a single command and the user will not even see the
OF-FTI-ALL -18 7 7
Department of Information AUGUST
From a High-Level Program to an Executable
File
OF-FTI-ALL -18 8 8
Department of Information AUGUST
3.2 Fundamental components of
C++
• C++ program is a collection of one or more subprograms,
called functions.
• A subprogram or a function is a collection of statements
that, when activated (executed), accomplishes something
• Every C++ program has a function called main
• The smallest individual unit of a program written in any
language is called a token
• The hello world program is one of the simplest programs,
but it already contains the fundamental components that
every C++ program has.
9
Department of Information AUGUST
Showing Sample Program in C++
• // A hello world program in C++
• #include<iostream>
• using namespace std;
• int main()
•{
• cout << "Hello World!";
• return 0;
•}
1
Department of Information AUGUST 0
---// A hello world program in C++
1
Department of Information AUGUST 1
--- #include<iostream>
• Lines beginning with a pound sign (#) are used
by the compilers pre-processor.
• In this case the directive #include tells the pre-
processor to include the iostream standard file.
• This file iostream includes the declarations of
the basic standard input/output library in C++.
• (See it as including extra lines of code that add
functionality to your program).
1
Department of Information AUGUST 2
--- using namespace std;
• All the elements of the standard C++ library
are declared within what is called a namespace.
• In this case the namespace with the name std.
• We put this line in to declare that we will make
use of the functionality offered in the namespace
std.
• This line of code is used very frequent in C++
programs that use the standard library.
• You will see that we will make use of it in most of
the source code included in these tutorials.
1
Department of Information AUGUST 3
--- int main()
• int is what is called the return value (in this case of the type
integer. Integer is a whole number).
• Every program must have a main() function.
• The main function is the point where all C++ programs start
their execution.
• The word main is followed by a pair of round brackets.
• That is because it is a function declaration. It is possible to
enclose a list of parameters within the round brackets.
• A C++ program is a collection of one or more subprograms
(functions)
• Function
• Collection of statements
• Statements accomplish a task
• Every C++ program has a function called main
1
Department of Information AUGUST 4
--- {}
• The two curly brackets (one in the beginning and one at the end)
are used to indicate the beginning and the end of the function main.
(Also called the body of a function).
• Everything contained within these curly brackets is what the
function does when it is called and executed.
--- cout << “Hello World”;
• This line is a C++ statement.
• A statement is a simple expression that can produce an effect.
• In this case the statement will print something to our screen.
• cout represents the standard output stream in C++.
• In this a sequence of characters (Hello World) will be send to the
standard output stream.
• The words Hello World have to be between ” “, but the ” ” will not
be printed on the screen. They indicate that the sentence begins
and where it will end.
1
Department of Information AUGUST 5
---cont
• cout is declared in the iostream standard file within the std
namespace. This is the reason why we needed to include that specific
file. This is also the reason why we had to declare this specific
namespace.
• As you can see the statement ends with a semicolon (;).
• The semicolon is used to mark the end of the statement.
• The semicolon must be placed behind all statements in C++ programs.
• So, remember this, One of the common errors is to forget to include a
semicolon after a statement.
--- return 0;
• The return statement causes the main function to finish.
• You may return a return code (in this case a zero) but it depends on
how you start your function main( ).
• We said that main ( ) will return an int (integer).
• So we have to return something (in this case a zero).
• A zero normally indicates that everything went ok and a one normally
indicates that something has gone wrong
1
Department of Information AUGUST 6
--- Indentations
• As you can see the cout and the return
statement have been indented or moved to the
right side.
• This is done to make the code more readable. In
a program as Hello World, it seems a stupid thing to
do.
• But as the programs become more complex, you
will see that it makes the code more readable.
• So, always use indentations and comments to
make the code more readable.
• It will make your life (programming life at least)
much easier if the code becomes more complex.
1
Department of Information AUGUST 7
3.3 Basic Elements
• Five kind of tokens in C++
• Keywords (reserved words)
• Identifiers
• Literals
• Operators
• Comments
1
Department of Information AUGUST 8
3.3.1 Keywords (reserved words)
• Words with special meaning to the compiler
• Have a predefined meaning that can’t be
changed
• All reserved words are in lower-case letters
• Must not be used for any other purposes
1
Department of Information AUGUST 9
3.3.2 Identifiers
• An identifier is name associated with a function or data
object and used to refer to that function or data object.
• Programmer given names
• Identify classes, variables, functions, etc.
• Consist of letters, digits, and the underscore character
(_)
• Must begin with a letter or underscore
• Not be a reserved word
• C++ is case sensitive
• Some predefined identifiers are cout and cin
• Unlike reserved words, predefined identifiers may be
redefined, but it is not a good idea
2
Department of Information AUGUST 0
--- valid and invalid Identifiers
2
Department of Information AUGUST 1
3.3.3 Literals
• Literals are constant values which can be a
number, a character of a string.
• Explicit (constant) value that is used by a program
• Literals can be digits, letters or others that
represent constant value to be stored in variables
• Assigned to variables
• Used in expressions
• Passed to methods
• E.g.
• Pi = 3.14; // Assigned to variables
• C= a * 60; // Used in expressions
2
Department of Information AUGUST 2
3.3.4 Comments
• Remark about programs
• Explain programs to other programmers
• Improve program readability
• Ignored by compiler
• Two types
Single-line comment
• Begin with //
• Example
• // This is a text-printing program.
Multi-line comment
• Start with /*
• End with */
• Typical uses
Identify program and who wrote it
Record when program was written
Add descriptions of modifications
2
Department of Information AUGUST 3
Example
1 /* Fig. 2.1: fig02_01.cpp
2 Text-printing program. */
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 cout << "Welcome to C++!\n"; // display message
9
10 return 0; // indicate that program ended successfully
11
Welcome to C++!
2
Department of Information AUGUST 4
3.3.5 Variables
• Location in memory where value can be stored
• All variables have two important attributes
• A type - Once defined, the type of a C++ variable cannot
be changed
• A value - can be changed by assigning a new value
• E.g. int a = 5;
• Type integer
• Value 5
2
Department of Information AUGUST 5
Variable Declaration
• Defining (creating) a variable
• Two parts
• Variable name - unique name of the memory location
• Data type (or type) - defines what kind of values the
variable can hold
• Syntax
• <type> <Var-idf>;
• E.g.
• double varTime;
• int myAge;
• Can declare several variables of same type in one
declaration
• Comma-separated list
• int integer1, integer2, sum;
• Variables must be declared before used
2
Department of Information AUGUST 6
---cont
• Variable names
Valid identifier
Series of characters (letters, digits, underscores)
Cannot begin with digit
Case sensitive
• Assignment operator =
Assigns value on left to variable on right
Binary operator (two operands)
• Example:
• sum = variable1 + variable2;
• Add the values of variable1 and variable2
• Store result in sum
2
Department of Information AUGUST 7
1 // Fig. 2.5: fig02_05.cpp
2 // Addition program that displays the sum of two numbers.
3 #include <iostream.h> // allows program to perform input and output
4
5 // function main begins program execution
6 int main()
7 {
8 // variable declarations
9 int number1; // first integer to add
10 int number2; // second integer to add
11 int sum; // sum of number1 and number2
12
13 cout << "Enter first integer: "; // prompt user for data
14 std::cin >> number1; // read first integer from user into number1
15
16 cout << "Enter second integer: "; // prompt user for data
17 cin >> number2; // read second integer from user into number2
18
19 sum = number1 + number2; // add the numbers; store result in sum
20
21 cout << "Sum is " << sum << std::endl; // display sum; end line
22
23 return 0; // indicate that program ended successfully
24
25 } // end function main
2
Department of Information AUGUST 8
Variables and Memory Concept
• Variable names
• Correspond to actual locations in computer's memory
• Every variable has name, type, size and value
• When new value placed into variable, overwrites old value
• Writing to memory is destructive
• Reading variables from memory nondestructive
• Example
• int number1= 45;
• int number2= 72;
• int sum = 0;
• sum = number1 + number2;
• Value of sum is overwritten Values of number1 and number2
remain intact
2
Department of Information AUGUST 9
Memory locations after calculating and
storing the sum of number1 and number2.
3
Department of Information AUGUST 0
Data Types
• When you define a variable in C++, you must tell
the compiler what kind of variable it is
Tell the data type
3
Department of Information AUGUST 1
Basic Data Types
• Three categories of simple data
• Integral: integers (numbers without a decimal)
3
Department of Information AUGUST 2
---Simple Data Types: int
• Type int
• Represent integers or whole numbers
• Some rules to follow:
Plus signs do not need to be written before the number
Minus signs must be written when using negative #’s
Decimal points cannot be used
Commas cannot be used
Leading zeros should be avoided (octal or base 8 #’s
• Signed - negative or positive
• Unsigned - positive
3
Department of Information AUGUST 3
--Simple Data Types: double, float
• Type double, float
• used to represent real numbers
• many programmers use type float
• avoid leading zeros, trailing zeros are ignored
• long double
3
Department of Information AUGUST 4
---Simple Data Types: char
• Type char
• used to represent character data
• a single character which includes a space
• 1 byte, enough to hold 256 values
• Must be enclosed in single quotes eg. ‘d’
• Escape sequences treated as single char
• ‘\n’ newline
• ‘\’’ apostrophe
• ‘\”’ double quote
• ‘\t’ tab
• (0-255) or as a member of the ASCII set
• E.g. the lowercase letter "a" is assigned the value 97
3
Department of Information AUGUST 5
---Simple Data Types
• Strings
• Used to represent textual information
• string constants must be enclosed in double
quotation marks eg. “Hello world!”
• empty string “”
• new line char or string “\n”
• “the word \”hello\”” (puts quotes around “hello” )
• String variables use:
#include “apstring.cpp”
• use quotes for user supplied libraries
3
Department of Information AUGUST 6
Type Size Values
int) 2,147,483,647
int
2 bytes -32,768 to 32,767
3
Department of Information AUGUST 8
3.4.1Arithmetic Operators
• Arithmetic operators perform mathematical
operations like addition, subtraction and
multiplication
• Addition +
• Subtraction -
• Multiplication *
• Division /
• Mod %
• Note
• No exponentiation operator
• Single division operator
• Operators are overloaded to work with more than one
type of object
3
Department of Information AUGUST 9
4
Department of Information AUGUST 0
Arithmetic Operators and Precedence
• Consider m*x + b which of the following is it equivalent to
• (m * x) + b
• m * (x + b)
• Operator precedence tells how to evaluate expressions
• Standard precedence order
• () Evaluate first, if nested innermost
done first
• */% Evaluate second. If there are several,
then evaluate from left-to-right
+- Evaluate third. If there are several,
then evaluate from left-to-right
4
Department of Information AUGUST 1
3.4.2 Assignment Operator
• The assignment operator is used for storing a value
at some memory location (typically denoted by a
variable).
• Assignment operators are used to store the result of
mathematical operation in one of the operand which
is at left side of the operator.
• Assignment operator =
• Assigns value on left to variable on right
• Binary operator (two operands)
• Example:
• int a= 5;
• float b= 9.66;
• char ch=‘d’;
• int m, n, p;
• m = n = p = 100;
4
Department of Information AUGUST 2
4
Department of Information AUGUST 3
Examples
4
Department of Information AUGUST 4
3.4.3 Relational Operators
• In order to evaluate a comparison between two
expressions, we can use the relational operator.
• (==, !=, > , <, >=, <=).
• The result of a relational operator is a bool value that
can only be true or false according to the result of the
comparison.
• E.g.: (7 = = 5) would return false or returns 0 (5 > 4)
would return true or returns 1
• The operands of a relational operator must evaluate to a
number.
• Characters are valid operands since they are
represented by numeric values.
• For E.g.: ‘A’ < ‘F’ would return true or 1. it is like (65 <
70)
--- cont
Operator Name Example
== Equality 5 == 5 // gives 1
!= Inequality 5 != 5 // gives 0
Relational operators
3.4.4 Logical Operators(!, &&, ||)
• Like the relational operators, logical operators
evaluate to 1 or 0.
Logical negation (!) is a unary operator, which
negates the logical value of its operand. If its operand
is non zero, it produce 0, and if it is 0 it produce 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.
4
Department of Information AUGUST 7
--- con
4
Department of Information AUGUST 8
3.4.5 Increment/Decrement Operators:
(++) and (--)
• The auto increment (++) and auto decrement (--)
operators provide a convenient way of, respectively,
adding and subtracting 1 from a numeric variable.
• E.g.: if a was 10 and if a++ is executed then a will
automatically changed to 11.
• Increment operator: increment variable by 1
• Decrement operator: decrement variable by 1
4
Department of Information AUGUST 9
Prefix and Postfix:
• The prefix type is written before the variable.
• Eg (++ myAge), whereas the postfix type appears after
the variable name (myAge ++).
• Prefix and postfix operators can not be used at
once on a single variable:
• Eg: ++age-- or --age++ or ++age++ or - - age - - is
invalid
• The prefix operator is evaluated before the
assignment, and the postfix operator is evaluated
after the assignment.
5
Department of Information AUGUST 0
--- cont
• ++count; or count++; increments the value of count
by 1
• --count; or count--; decrements the value of
count by 1
• If x = 5; and y = ++x;
After the second statement both x and y are 6
• If x = 5; and y = x++;
After the second statement y is 5 and x is 6
5
Department of Information AUGUST 1
---cont
5
Department of Information AUGUST 2
5
Department of Information AUGUST 3
5
Department of Information AUGUST 4
Type conversion
• A value in any of the built-in types can be
converted
• Called type cast
• Syntax
• (<data – type> )value; or <data – type> (value);
• E.g
• (int) 3.14 // converts 3.14 to an int to give 3
• (long) 3.14 // converts 3.14 to a long to give 3L
• (double) 2 // converts 2 to a double to give 2.0
• (char) 122 // converts 122 to a char whose code is
122
• (unsigned short) 3.14 // gives 3 as an unsigned short
5
Department of Information AUGUST 5
• Some times the compiler does the type casting – implicit
type cast
• E.g
• double d = 1; // d receives 1.0
• int i = 10.5; // i receives 10
• i = i + d;
5
Department of Information AUGUST 6
3.5 Statements
• Statements are fragments of the C++ program
that are executed in sequence. The body of any
function is a sequence of statements. For
example:
• Roughly equivalent to sentences in natural
languages
• Forms a complete unit of execution.
• Terminating the expression with a semicolon (;)
5
Department of Information AUGUST 7
----- Statements
• C++ includes the following types of
statements:
• 1) expression statements;
• 2) compound statements;
• 3) selection statements;
• 4) iteration statements;
• 5) jump statements;
• 6) declaration statements;
5
Department of Information AUGUST 8
Expression
• Combine literals, variables, and operators to form
expressions
• Expression is segments of code that perform
computations and return values .
• Expressions can contain: Example:
– a number literal, 3.14
– a variable, count
– a function call, sum(x, y)
– an operator between two expressions (binary operator), a
+b
– an operator applied to one expression (unary operator), -
discount
– expressions in parentheses. (3.14-amplitude)
5
Department of Information AUGUST 9
---cont
expression statements in c++
Null statements
Assignment expressions
Any use of ++ or –
Function calls
Object creation expressions
6
Department of Information AUGUST 0
Examples
6
Department of Information AUGUST 1
1. Write a program that asks your age
and echo it to the screen
• #include <iostream>
• using namespace std;
• int main()
• {
• int age;
• cout << "Enter your age Please: ";
• cin >> age;
• cout << "Your Age is : " << age;
• getch(); // Wait For Output Screen
• return 0;
• }
6
Department of Information AUGUST 2
2.Write a C++ program to add two
numbers.
6
Department of Information AUGUST 3
3. Program to find a perimeter
and Area of a rectangle
6
Department of Information AUGUST 4
Exercise
1. Cascading Insertion and Extraction
operators
Write a C++ program to accept 2 numbers and
display the addition of the 2 numbers. For the
output format see below:
Out put
Enter two numbers :: 23 93
23+93=116
6
Department of Information AUGUST 5
Program : Cascading and
extraction operator in c++.
6
Department of Information AUGUST 6
Exercise
2. Write a program in C++ to calculate
the volume of a cylinder.
6
Department of Information AUGUST 7
Program : in C++ to calculate the volume
of a cylinder.
6
Department of Information AUGUST 8
Exercise
3. Write a program in C++ to swap two numbers
Using Temporary Variable. For the output
format see below:
6
Department of Information AUGUST 9
Program : Swap two numbers Using
Temporary Variable
7
Department of Information AUGUST 0
Control Statements
71
Introduction
• A running program spends all of its time executing instructions or statements in
that program.
• The order in which statements in a program are executed is called flow of that
program.
• Programmers can control which instruction to be executed in a program, which is
called flow control.
• This term reflects the fact that the currently executing statement has the
control of the CPU, which when completed will be handed over (flow) to
another statement.
• Flow control in a program is typically sequential, from one statement to the
next.
• But we can also have execution that might be divided to other paths by
branching statements. Or perform a block of statement repeatedly until a
condition fails by Repetition or looping.
• Flow control is an important concept in programming because it will give all
the power to the programmer to decide what to do to execute during a run
and what is not, therefore, affecting the overall outcome of the program.
7
Department of Information AUGUST 2
1.Types of control
statment:
• C++ has a number of statements for controlling the flow of
execution in a program, like all procedural languages
• There are a number of basic types of control statments:
• Sequential statements
• Selection statements (Conditional)
• Iteration statements (or loops)
7
Department of Information AUGUST 3
1.1 Sequential
statements
Sequence: a number of statements executed
one after the other
Such kind of statements are instruction in a
program which will executed one after the
other in the order scripted in the program.
In sequential statements, the order will be
determined during program development and
can not be changed.
7
Department of Information AUGUST 4
1.2 Selection statements
• Also called conditional statements, branching statements.
• Selection statements are statements in a program where there
are points at which the program will decide at runtime whether
some part of the code should or should not be executed.
• executes different statements based upon certain
conditions.
• There are two types of selection statements in C++,
1. “if statement” and the
2. “switch statement”
7
Department of Information AUGUST 5
1.2.1 The if Statement
• It is sometimes desirable to make the execution of a
statement dependent upon a condition being satisfied.
• The different forms of the ‘If” statement will be used to
decide whether to execute part of the program based on a
condition which will be tested either for TRUE or
FALSE result.
• Make a set of instructions to be executed in alternative
way
• The different forms of the “If” statement are:
• The simple if statement
• The If else statement
• The if else if statement
• The nested if
7
Department of Information AUGUST 6
1.2.1.1 The simple “if”
statement
• 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.
The General Syntax is:
7
Department of Information AUGUST 7
----Examples
• To make multiple statements dependent on the same condition
we can use a compound statement, which will be implemented
by embracing the group of instructions within the left “{“ and
right “}” French bracket.
7
Department of Information AUGUST 9
1.2.1.2 The “if else” statement
• Another form of the “if” is the “if …else” statement.
• The “if else if” statement allows us to specify two alternative
statements:
One which will be executed if a condition is satisfied and
Another which will be executed if the condition is not satisfied.
• The General Syntax is:
8
Department of Information AUGUST 0
----examples
8
Department of Information AUGUST 1
1.2.1.3 The “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.
• The General Syntax is:
8
Department of Information AUGUST 2
---Examples
8
Department of Information AUGUST 3
1.2.1.4 Nesting If statements within another if
statement
• One or more statements can be nested with in another if statement.
• The nesting will be used to test multiple conditions to perform a task
• It is always recommended to indent nested if statements to enhance
readability of a program.
• The General Syntax might be: • Statement N will be executed if and only if
“expression 1” and “expression2” are
evaluated and if the outcome of both is
none zero (TRUE).
• Statement M will be executed if and only if
“expression1” is TRUE and “expression2”
is FALSE.
• Statement R will be executed if and only if
“expression1” is False and “expression3”
is TRUE.
• Statement T will be executed if and only if
“expression1” is False and “expression2”
is FALSE.
8
Department of Information AUGUST 4
1.2.2 The Switch Statement
• Another C++ statement that implements a selection control flow is the switch
statement (multiple-choice statement).
• The switch statement provides a way of choosing between a set of
alternatives based on the value of an expression.
• The switch statement has four components:
Switch, Case , Default and Break
• The General Syntax might be
8
Department of Information AUGUST 5
---The Switch Statement
8
Department of Information AUGUST 6
The Switch Statement
8
Department of Information AUGUST 7
switch Menu Example
• Switch statement "perfect" for menus:
switch (response)
{
case "1":
// Execute menu option 1
break;
case "2":
// Execute menu option 2
break;
case 3":
// Execute menu option 3
break;
default:
cout << "Please enter valid response.";
}
8
Department of Information AUGUST 8
1.3 Iteration statements
• Also called Repetition statements, loop statements etc.
• 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:
1) The For Statement or loop
2) The While statement or loop
3) The do…while statement or loop
8
Department of Information AUGUST 9
1.3.1The For loop
• The “for” statement (also called loop) is used to repeatedly
execute a block of instructions until a specific condition
fails.
• A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to execute a specific
number of times.
• The general syntax can be expressed as follows :
9
Department of Information AUGUST 0
Steps of execution of the for loop
1. Initialization is executed. (will be executed only once)
2. Condition is checked, if it is true the loop continues, otherwise the loop
finishes and statement is skipped.
3. Statement is executed.
4. Finally, whatever is specified in the increase or decrease field is
executed and the loop gets back to step 2.
9
Department of Information AUGUST 1
The for Loop is a Pretest Loop
• The for loop tests its test expression before each
iteration, so it is a pretest loop.
• The following loop will never iterate:
for (count = 11; count <= 10; count++)
cout << "Hello" << endl;
9
Department of Information AUGUST 2
1.3.2 The While loop
• The while statement (also called while loop) provides a way
of repeating a statement or a block as long as a condition
holds / is true.
• A while loop statement repeatedly executes a target
statement as long as a given condition is true.
• The syntax of a while loop in C++ is:
9
Department of Information AUGUST 3
The While loop
9
Department of Information AUGUST 4
The while loop in Program
9
Department of Information AUGUST 5
1.3.3 The Do…while loop
• The do statement (also called the do loop) is similar to the
while statement, except that its body is executed first and
then the loop condition is examined.
• In do…while loop, we are sure that the body of the loop will be
executed at lease once. Then the condition will be tested.
• The general form is
9
Department of Information AUGUST 7
example
9
Department of Information AUGUST 8
Thank You
? 9
Department of Information AUGUST 9