SlideShare a Scribd company logo
1 of 54
Flow Of Control
MADE BY :
TANUJ
In This Chapter
• Introduction
• Statements
• Statement Flow Control
• Selection Statement
• Iteration Statement
• Jump Statement
Introduction
•In a program statement may be executed
sequentially, selectively or iteratively.
•Every program language provides
constructs to support sequence, selection
or iteration.
Statements
• Statement are the instructions given to the computer to perform any
kind of action, be it data movements, be it making decisions or be it
repeating actions.
• Statements form the smallest executable unit within C++ program.
• Statements are terminated with a semicolon (;).
Compound Statements (Block)
• A compound statement in C++ is a sequence of statements enclosed
by a pair of braces { }.
• A compound statement is equivalently called a block.
• For instance,
{
statement 1;
statement 2;
:
:
}
Statement Flow Control
• In a program, Statements may be executed Sequentially, Selectively
or Iteratively.
Sequence
• The sequence construct means the statements are being executed
sequentially.
THE SEQUENCE
CONSTRUCT Statement
1
Statement
2
Statement
3
Selection
• The Selection construct means the execution of statements
depending upon a condition-test
In C++, the program execution starts
with the first statement of main ( ) and
ends with last statement of main ( ) .
Therefore, the main ( ) is also called
driver function as it drives the
program.
Condition ?
Statement 1
Statement 2
One Course-of-action
False
Statement 1 Statement 2
Another
Course-of-action
The Selection Construct
Iteration
• Iteration construct means repetition of set of statements depending
upon a condition test.Till the time of condition is true. ( or false
depending upon the loop). A set of statements are repeated again
and again. As soon as the condition become false (or true), the
repetition stops.The iteration condition is also called ”Looping
Construct”.
Condition ?
Statement 1
Statement 2
False
The Loop Body
The Exit
Condition
True
The Iteration
Construct
Selection Statement
• The selection statement allow to choose the set of instruction for
execution depending upon an expression’s truth .C++ provides two
types of selection statements
The “if ” Statement of C++
• An if statement test a particular condition, if the condition evaluated to
true, a course of action is followed, i.e., a statement or a set of statement is
executed. Otherwise if the condition evaluated to false then the course of
action is ignored.
Syntax of “if” Statement
• if (condition)
statement 1;
The statement may consist of single or compound. If the condition
evaluates non zero value that is true then the statement 1 is executed
otherwise if the condition evaluates zero i.e., false then the statement 1 is
ignored.
Example of “if” statement
• if (grade == ‘A’) // comparison with a literal
cout<<“You did well”;
• if (a > b) // comparing two variables
cout<<“A is more than B has”;
• if ( x ) // testing truth value of a variable
{
cout<<“x is non – zero n”;
cout<<“hence it result into true”;
}
• if (condition)
statement 1;
else
statement 2;
• If the expression evaluates to true i.e., a nonzero value, the
statement-1 is executes, otherwise, statement-2 is executed.
• In an if-else statement, only the code associated with if or the code
associated with else executes, never both
Syntax of “if-else” Statement
Example of “if-else” statement
if ( x )
{
cout<<“x is non – zero n”;
cout<<“hence it result into true”;
}
else
{
cout<<“x is a zero n”;
cout<<“hence it result into false”;
}
Test
Expression
?
Body of if
True
False
The if statement’s
operation
Test
Expression
?
Body of if
True
False
The if-else statement’s
operation
Body of else
Nested ifs
A nested if is an if that has another if in its body or in its else body.
The nested if can have one of the following three forms
Program to create the equivalent of a four
function calculator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch;
float a,b,result;
cout<<“Enter your choice [+,*,/,-] :”;
cin>>ch;
if (ch==’+’)
{
cout<<”Enter first no. - ”;
cin>>a;
cout<<”Enter another no. -”;
cin>>b;
result=a+b;
cout<<”Sum is ”<<result;
getch();
}
else
if(ch==’-‘)
{
cout<<”Enter first no. - ”;
cin>>a;
cout<<”Enter another no. -”;
cin>>b;
result=a-b;
cout<<”Subtraction is ”<<result;
getch();
}
else
•
getch();
}
else
cout<<”Unknown operator!!!!”;
return(0);
}
The if-else ladder
• A common programming
construct in C++ is the if-
else-if ladder, which is
often also called as the if-
else-if ladder because of its
appearance. It takes the
following general form.
if (expression 1) statement 1;
else
if (expression 2) statement 2;
else
if (expression 3) statement 3;
:
else statement 4;
Example :
The ‘ ? ’ Alternative to ‘if’
• C++ has an operator that can be alternative to if statement. The conditional
operator ? :
• This operator can be used to replace the if statement of C++.
Conditional Operator ‘ ? ’
• The above form of if else statement
can be replaced as,
expression1?expression2:expressio
n3;
if (expression 1)
statement
2;
else
statement 3;
Comparing ‘if’ and ‘?’
1. Compared to if – else sequence, ?: offers more concise, clean and
compact code, but it is less obvious as compared to if.
2. Another difference is that the conditional operator ?: produces an
expression, and hence a single value can be assigned or incorporated into
a larger expression, where as if is more flexible. if can have multiple
statements multiple assignments and expressions (in the form of
compound statement) in its body.
3. When ?: operator is used in its nested form it becomes complex and
difficult to understand. Generally ?: is used to conceal (hide) the purpose
of the code.
The ‘switch’ Statement
• C++ provides multiple- branch selection statement known as
switch.
• This selection statement successively tests the value of an expression
against the list of integer or character constants. When a match is
found, the statements associated with that construct are executed.
FallThrough -The fall of control to
the following cases, is called Fall-
Through
The syntax of ‘switch’
switch(expression)
{
case constant 1 : statement sequence 1;
break;
case constant 2 : statement sequence 2;
break;
case constant n-1 : statement sequence n-1;
break;
[default: statement sequence n];
}
The switch Vs. if-else
• The switch and if-else are selection statements and they both let you select
an alternative out of many alternatives by testing an expression. However
there are some differences in their operation and they
1. The switch statement differs from the if statement in that switch can only
test for equality where as if can evaluate a relational or logical expressions
i.e multiple conditions.
2. The switch statement selects its branches by testing the value of same
variable (against the set of constants) where as the if else construction
lets you to use a series of expressions that may involve unrelated variables
and complex expressions.
The switch Vs. if-else (Cont.…)
3. The if-else is more versatile of two statements where as
switch cannot. Each switch case label must be a single
value.
4. The if-else statement can handle floating point tests also
apart from integer and character tests where as switch
cannot handle floating point tests. The case labels of
switch must be an integer or character.
The Nested switch
• Like if statement, switch can also be nested. For example following
code fragment is perfectly all right in C++.
switch ( a )
{
case 1 : switch ( b )
{
case 0 : cout<<“Divide by Zero Error !! ”;
break ;
case 1 : res = a/b
}
break;
case 2: ……………………;
}
ITERATION STATEMENTS
The iteration statement allows instructions to
be executed until a certain condition is to be
fulfilled.
Iteration Statements
• The iteration statements are also called as loops or Looping
statements.
• C++ provides three kinds of loops
1. for
2. while
3. do-while
Elements of Loop
1. Initialization Expression : Before entering in a loop, its control variable
must be initialized. The initialization expression executed at only once in
the beginning of the loop.
2. Test Expression : The test expression is an expression whose truth
values decides weather the loop- body will be executed or not. If the test
expression evaluates to true I.e., the loop gets executed, otherwise the
loop terminated.
3. Update Expression : The update expression change the value of loop
variable. The update expression is executed; at the end of loop after the
loop-body is executed.
Elements of Loop (Cont.….)
4. The Body-of-the-loop : The statement that are executed
repeatedly as long as the test expression is nonzero . If it evaluates
to zero then the loop is terminates.
The ‘for’ loop
• In for loop we know all the elements of loop like initialization expression ,
test expression and update expression.
The syntax of the for loop :
for (initialization expression(s) ; test-expression ; update expression(s))
body-of-the-loop;
Example for ‘for’ loop
• If we want to print Hello printed 4 times using for loop.
#include<iostream.h>
#include<conio.h>
void main ( )
{
clrscr();
for(int i=1;i<=4;++i) //do not give semicolon’s here
{
cout<<“Hello”<<endl;
}
getch();
}
Test
Expression
?
Body of the
loop
True
False
The execution of a for
loop
Initialization
Expression
Update
Expression
Exit
The ‘while’ loop
• The ‘while’ loop is an entry controlled loop.
• In a ‘while’ loop, a lop control variable should be initialised before the loop
begins as an uninitialized variable can be used in an expression.
• The loop variable should be updated inside the body of the ‘while’.
The syntax of the while loop :
while (expression)
loop-body
Printing a Table using while loop
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n;
cout<<"Enter a no.";
cin>>n;
int i=1;
while (i<=10)
{
cout<<n<<"x"<<i<<"="<<n*i<<endl;
i++;
}
getch();
}
The ‘do-while’ loop
• The ‘do-while’ loop executes at least once even when the test – expression
is false initially.
The syntax of the do-while loop :
do {
statement ;
}
while (test-expression) ;
Example for ‘do-while’ loop
• The code prints character from ‘A’ onwards until the condition ch<=‘Z’
becomes false
char ch = ‘A’;
do { cout<<“n”<<ch;
ch++;
} while (ch <= ‘Z’) ;
Nested loops
• A loop can contain another loop in its body.This form of a loop is
called nested loop. In nested loop the inner loop must terminate
before the outer loop.
:
for ( i = 1 ; i < 5 ; ++i)
{
cout<< “  n ” ;
}
for ( j = 1 ; j<= I ; ++j)
cout<< “ * “ ;
• The code prints following :
*
* *
* * *
* * * *
Comparison Of Loops
• The for loop is appropriate when you know in advance how many
times the loop will be executed.
• The other two loops while and do-while are more suitable in the
situations where it is known before –hand when the loop will
terminate.
• The while should be preferred when you may not want to execute the
loop body even once (in case test condition is false).
• The do-while loop should be preferred when you are sure you want to
execute the loop body at least once.
Jump Statements
Jump statements unconditionally transfer program
control within a function
Types of Jump Statement
1. return
2. goto
3. break
4. continue
• In addition to four statements C++ library function provides exit() that
helps you break out of the program.
The ‘goto’ Statement
• The goto statement is rarely used in the programming.
• A goto statement can transfer the program control anywhere in the
program.The target destination of a goto statement is marked by the
label.
• lable is a user supplied identifier and can either before or after goto.
• The syntax is,
goto label ;
:.
lable :
Example for ‘goto’ statement
a = 0 ;
start :
cout << “  n ” << ++a ;
if ( a < 50 ) goto start ;
NOTE :
• lable may not immediately precede a closing right brace .
• For example :
:.
{
goto last :
:.
last : //wrong ! A lable is preceding the closing brace }
}
NOTE :
• For example :
:.
{
goto last :
:.
last : ; // now correct
}
The ‘break’ Statement
• The break statement enables a program to skip over part of the code.
A break statement terminates the smallest enclosing while, do-while,
for or switch statement.
The ‘continue’ Statement
• The continue statement is the another jump statement like the break
as the both the statements skips over the part of code but the
continue statement is some what different than the break. Instead of
forcing for termination it forces for the next iteration of the loop to
take place, skipping any code in between.
The ‘exit ( ) ’ Function
• The exit ( ) function causes the program to
terminate as soon as it is encountered.
• The exit ( ) function is a C++ standard library
function defined in process.h file which must be
included in the program to uses exit ( )
function.
Example for ‘exit ( )’ function
#include<iostream.h>
#include<conio.h>
#include<process.h>
void main()
{
clrscr();
int n;
cout<<"Enter no.:";
cin>>n;
for(int i=2;i<=n/2;++i)
{
if (n%i==0)
cout<<"Not prime";
getch();
exit(0);
}
cout<<"Prime";
getch();
}
Thank You

More Related Content

What's hot

What's hot (20)

Presentation of control statement
Presentation of control statement  Presentation of control statement
Presentation of control statement
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Control statements
Control statementsControl statements
Control statements
 
C programming decision making
C programming decision makingC programming decision making
C programming decision making
 
Control statement-Selective
Control statement-SelectiveControl statement-Selective
Control statement-Selective
 
Control statement
Control statementControl statement
Control statement
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C ppt
 
Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Control structures i
Control structures i Control structures i
Control structures i
 
Cse lecture-6-c control statement
Cse lecture-6-c control statementCse lecture-6-c control statement
Cse lecture-6-c control statement
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Conditional statement
Conditional statementConditional statement
Conditional statement
 
Conditional statement c++
Conditional statement c++Conditional statement c++
Conditional statement c++
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
C# conditional branching statement
C# conditional branching statementC# conditional branching statement
C# conditional branching statement
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
Control statement in c
Control statement in cControl statement in c
Control statement in c
 

Similar to Flow of control C ++ By TANUJ

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 

Similar to Flow of control C ++ By TANUJ (20)

Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Control structure
Control structureControl structure
Control structure
 
CONTROL STMTS.pptx
CONTROL STMTS.pptxCONTROL STMTS.pptx
CONTROL STMTS.pptx
 
Decision Making and Branching in C
Decision Making and Branching  in CDecision Making and Branching  in C
Decision Making and Branching in C
 
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow controlIntroduction to computer programming (C)-CSC1205_Lec5_Flow control
Introduction to computer programming (C)-CSC1205_Lec5_Flow control
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptx
 
Btech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statementsBtech i pic u-3 handling input output and control statements
Btech i pic u-3 handling input output and control statements
 
Mca i pic u-3 handling input output and control statements
Mca i pic u-3 handling input output and control statementsMca i pic u-3 handling input output and control statements
Mca i pic u-3 handling input output and control statements
 
handling input output and control statements
 handling input output and control statements handling input output and control statements
handling input output and control statements
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
Diploma ii cfpc u-3 handling input output and control statements
Diploma ii  cfpc u-3 handling input output and control statementsDiploma ii  cfpc u-3 handling input output and control statements
Diploma ii cfpc u-3 handling input output and control statements
 
Bsc cs pic u-3 handling input output and control statements
Bsc cs  pic u-3 handling input output and control statementsBsc cs  pic u-3 handling input output and control statements
Bsc cs pic u-3 handling input output and control statements
 
Do While Repetition Structure
Do While Repetition StructureDo While Repetition Structure
Do While Repetition Structure
 
Programming Fundamentals in C++ structures
Programming Fundamentals in  C++ structuresProgramming Fundamentals in  C++ structures
Programming Fundamentals in C++ structures
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Flow of control
Flow of controlFlow of control
Flow of control
 
Control statements
Control statementsControl statements
Control statements
 

Recently uploaded

Recently uploaded (20)

On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
latest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answerslatest AZ-104 Exam Questions and Answers
latest AZ-104 Exam Questions and Answers
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 

Flow of control C ++ By TANUJ

  • 1. Flow Of Control MADE BY : TANUJ
  • 2. In This Chapter • Introduction • Statements • Statement Flow Control • Selection Statement • Iteration Statement • Jump Statement
  • 3. Introduction •In a program statement may be executed sequentially, selectively or iteratively. •Every program language provides constructs to support sequence, selection or iteration.
  • 4. Statements • Statement are the instructions given to the computer to perform any kind of action, be it data movements, be it making decisions or be it repeating actions. • Statements form the smallest executable unit within C++ program. • Statements are terminated with a semicolon (;).
  • 5. Compound Statements (Block) • A compound statement in C++ is a sequence of statements enclosed by a pair of braces { }. • A compound statement is equivalently called a block. • For instance, { statement 1; statement 2; : : }
  • 6. Statement Flow Control • In a program, Statements may be executed Sequentially, Selectively or Iteratively.
  • 7. Sequence • The sequence construct means the statements are being executed sequentially. THE SEQUENCE CONSTRUCT Statement 1 Statement 2 Statement 3
  • 8. Selection • The Selection construct means the execution of statements depending upon a condition-test In C++, the program execution starts with the first statement of main ( ) and ends with last statement of main ( ) . Therefore, the main ( ) is also called driver function as it drives the program.
  • 9. Condition ? Statement 1 Statement 2 One Course-of-action False Statement 1 Statement 2 Another Course-of-action The Selection Construct
  • 10. Iteration • Iteration construct means repetition of set of statements depending upon a condition test.Till the time of condition is true. ( or false depending upon the loop). A set of statements are repeated again and again. As soon as the condition become false (or true), the repetition stops.The iteration condition is also called ”Looping Construct”.
  • 11. Condition ? Statement 1 Statement 2 False The Loop Body The Exit Condition True The Iteration Construct
  • 12. Selection Statement • The selection statement allow to choose the set of instruction for execution depending upon an expression’s truth .C++ provides two types of selection statements
  • 13. The “if ” Statement of C++ • An if statement test a particular condition, if the condition evaluated to true, a course of action is followed, i.e., a statement or a set of statement is executed. Otherwise if the condition evaluated to false then the course of action is ignored. Syntax of “if” Statement • if (condition) statement 1; The statement may consist of single or compound. If the condition evaluates non zero value that is true then the statement 1 is executed otherwise if the condition evaluates zero i.e., false then the statement 1 is ignored.
  • 14. Example of “if” statement • if (grade == ‘A’) // comparison with a literal cout<<“You did well”; • if (a > b) // comparing two variables cout<<“A is more than B has”; • if ( x ) // testing truth value of a variable { cout<<“x is non – zero n”; cout<<“hence it result into true”; }
  • 15. • if (condition) statement 1; else statement 2; • If the expression evaluates to true i.e., a nonzero value, the statement-1 is executes, otherwise, statement-2 is executed. • In an if-else statement, only the code associated with if or the code associated with else executes, never both Syntax of “if-else” Statement
  • 16. Example of “if-else” statement if ( x ) { cout<<“x is non – zero n”; cout<<“hence it result into true”; } else { cout<<“x is a zero n”; cout<<“hence it result into false”; }
  • 17. Test Expression ? Body of if True False The if statement’s operation Test Expression ? Body of if True False The if-else statement’s operation Body of else
  • 18. Nested ifs A nested if is an if that has another if in its body or in its else body. The nested if can have one of the following three forms
  • 19. Program to create the equivalent of a four function calculator #include<iostream.h> #include<conio.h> void main() { clrscr(); char ch; float a,b,result; cout<<“Enter your choice [+,*,/,-] :”; cin>>ch; if (ch==’+’) { cout<<”Enter first no. - ”;
  • 20. cin>>a; cout<<”Enter another no. -”; cin>>b; result=a+b; cout<<”Sum is ”<<result; getch(); } else if(ch==’-‘) { cout<<”Enter first no. - ”; cin>>a; cout<<”Enter another no. -”; cin>>b; result=a-b; cout<<”Subtraction is ”<<result; getch(); } else
  • 21.
  • 23. The if-else ladder • A common programming construct in C++ is the if- else-if ladder, which is often also called as the if- else-if ladder because of its appearance. It takes the following general form. if (expression 1) statement 1; else if (expression 2) statement 2; else if (expression 3) statement 3; : else statement 4; Example :
  • 24. The ‘ ? ’ Alternative to ‘if’ • C++ has an operator that can be alternative to if statement. The conditional operator ? : • This operator can be used to replace the if statement of C++. Conditional Operator ‘ ? ’ • The above form of if else statement can be replaced as, expression1?expression2:expressio n3; if (expression 1) statement 2; else statement 3;
  • 25. Comparing ‘if’ and ‘?’ 1. Compared to if – else sequence, ?: offers more concise, clean and compact code, but it is less obvious as compared to if. 2. Another difference is that the conditional operator ?: produces an expression, and hence a single value can be assigned or incorporated into a larger expression, where as if is more flexible. if can have multiple statements multiple assignments and expressions (in the form of compound statement) in its body. 3. When ?: operator is used in its nested form it becomes complex and difficult to understand. Generally ?: is used to conceal (hide) the purpose of the code.
  • 26. The ‘switch’ Statement • C++ provides multiple- branch selection statement known as switch. • This selection statement successively tests the value of an expression against the list of integer or character constants. When a match is found, the statements associated with that construct are executed. FallThrough -The fall of control to the following cases, is called Fall- Through
  • 27. The syntax of ‘switch’ switch(expression) { case constant 1 : statement sequence 1; break; case constant 2 : statement sequence 2; break; case constant n-1 : statement sequence n-1; break; [default: statement sequence n]; }
  • 28. The switch Vs. if-else • The switch and if-else are selection statements and they both let you select an alternative out of many alternatives by testing an expression. However there are some differences in their operation and they 1. The switch statement differs from the if statement in that switch can only test for equality where as if can evaluate a relational or logical expressions i.e multiple conditions. 2. The switch statement selects its branches by testing the value of same variable (against the set of constants) where as the if else construction lets you to use a series of expressions that may involve unrelated variables and complex expressions.
  • 29. The switch Vs. if-else (Cont.…) 3. The if-else is more versatile of two statements where as switch cannot. Each switch case label must be a single value. 4. The if-else statement can handle floating point tests also apart from integer and character tests where as switch cannot handle floating point tests. The case labels of switch must be an integer or character.
  • 30. The Nested switch • Like if statement, switch can also be nested. For example following code fragment is perfectly all right in C++. switch ( a ) { case 1 : switch ( b ) { case 0 : cout<<“Divide by Zero Error !! ”; break ; case 1 : res = a/b } break; case 2: ……………………; }
  • 31. ITERATION STATEMENTS The iteration statement allows instructions to be executed until a certain condition is to be fulfilled.
  • 32. Iteration Statements • The iteration statements are also called as loops or Looping statements. • C++ provides three kinds of loops 1. for 2. while 3. do-while
  • 33. Elements of Loop 1. Initialization Expression : Before entering in a loop, its control variable must be initialized. The initialization expression executed at only once in the beginning of the loop. 2. Test Expression : The test expression is an expression whose truth values decides weather the loop- body will be executed or not. If the test expression evaluates to true I.e., the loop gets executed, otherwise the loop terminated. 3. Update Expression : The update expression change the value of loop variable. The update expression is executed; at the end of loop after the loop-body is executed.
  • 34. Elements of Loop (Cont.….) 4. The Body-of-the-loop : The statement that are executed repeatedly as long as the test expression is nonzero . If it evaluates to zero then the loop is terminates.
  • 35. The ‘for’ loop • In for loop we know all the elements of loop like initialization expression , test expression and update expression. The syntax of the for loop : for (initialization expression(s) ; test-expression ; update expression(s)) body-of-the-loop;
  • 36. Example for ‘for’ loop • If we want to print Hello printed 4 times using for loop. #include<iostream.h> #include<conio.h> void main ( ) { clrscr(); for(int i=1;i<=4;++i) //do not give semicolon’s here { cout<<“Hello”<<endl; } getch(); }
  • 37. Test Expression ? Body of the loop True False The execution of a for loop Initialization Expression Update Expression Exit
  • 38. The ‘while’ loop • The ‘while’ loop is an entry controlled loop. • In a ‘while’ loop, a lop control variable should be initialised before the loop begins as an uninitialized variable can be used in an expression. • The loop variable should be updated inside the body of the ‘while’. The syntax of the while loop : while (expression) loop-body
  • 39. Printing a Table using while loop #include<iostream.h> #include<conio.h> void main() { clrscr(); int n; cout<<"Enter a no."; cin>>n; int i=1; while (i<=10) { cout<<n<<"x"<<i<<"="<<n*i<<endl; i++; } getch(); }
  • 40. The ‘do-while’ loop • The ‘do-while’ loop executes at least once even when the test – expression is false initially. The syntax of the do-while loop : do { statement ; } while (test-expression) ;
  • 41. Example for ‘do-while’ loop • The code prints character from ‘A’ onwards until the condition ch<=‘Z’ becomes false char ch = ‘A’; do { cout<<“n”<<ch; ch++; } while (ch <= ‘Z’) ;
  • 42. Nested loops • A loop can contain another loop in its body.This form of a loop is called nested loop. In nested loop the inner loop must terminate before the outer loop. : for ( i = 1 ; i < 5 ; ++i) { cout<< “ n ” ; } for ( j = 1 ; j<= I ; ++j) cout<< “ * “ ; • The code prints following : * * * * * * * * * *
  • 43. Comparison Of Loops • The for loop is appropriate when you know in advance how many times the loop will be executed. • The other two loops while and do-while are more suitable in the situations where it is known before –hand when the loop will terminate. • The while should be preferred when you may not want to execute the loop body even once (in case test condition is false). • The do-while loop should be preferred when you are sure you want to execute the loop body at least once.
  • 44. Jump Statements Jump statements unconditionally transfer program control within a function
  • 45. Types of Jump Statement 1. return 2. goto 3. break 4. continue • In addition to four statements C++ library function provides exit() that helps you break out of the program.
  • 46. The ‘goto’ Statement • The goto statement is rarely used in the programming. • A goto statement can transfer the program control anywhere in the program.The target destination of a goto statement is marked by the label. • lable is a user supplied identifier and can either before or after goto. • The syntax is, goto label ; :. lable :
  • 47. Example for ‘goto’ statement a = 0 ; start : cout << “ n ” << ++a ; if ( a < 50 ) goto start ;
  • 48. NOTE : • lable may not immediately precede a closing right brace . • For example : :. { goto last : :. last : //wrong ! A lable is preceding the closing brace } }
  • 49. NOTE : • For example : :. { goto last : :. last : ; // now correct }
  • 50. The ‘break’ Statement • The break statement enables a program to skip over part of the code. A break statement terminates the smallest enclosing while, do-while, for or switch statement.
  • 51. The ‘continue’ Statement • The continue statement is the another jump statement like the break as the both the statements skips over the part of code but the continue statement is some what different than the break. Instead of forcing for termination it forces for the next iteration of the loop to take place, skipping any code in between.
  • 52. The ‘exit ( ) ’ Function • The exit ( ) function causes the program to terminate as soon as it is encountered. • The exit ( ) function is a C++ standard library function defined in process.h file which must be included in the program to uses exit ( ) function.
  • 53. Example for ‘exit ( )’ function #include<iostream.h> #include<conio.h> #include<process.h> void main() { clrscr(); int n; cout<<"Enter no.:"; cin>>n; for(int i=2;i<=n/2;++i) { if (n%i==0) cout<<"Not prime"; getch(); exit(0); } cout<<"Prime"; getch(); }