SlideShare une entreprise Scribd logo
1  sur  27
1
Abraham H.
Fundamentals of Programming I
Control Statements
2
Outline
 Introduction
 Conditional structure
 If and else
 The Selective Structure: Switch
 Iteration structures (loops)
 The while loop
 The do-while loop
 The for loop
 Jump statements
 The break statement
 The continue statement
3
Introduction
 C++ provides different forms of statements for different
purposes
 Declaration statements
 Assignment-like statements. etc
 The order in which statements are executed is called flow
control
 Branching statements
 specify alternate paths of execution, depending on the
outcome of a logical condition
 Loop statements
 specify computations, which need to be repeated until a
certain logical condition is satisfied.
4
Branching Mechanisms
 if-else statements
 Choice of two alternate statements based on condition
expression
 Example:
if (hrs > 40)
grossPay = rate*40 + 1.5*rate*(hrs-40);
else
grossPay = rate*hrs;
 if-else Statement syntax:
if (<boolean_expression>)
<yes_statement>
else
<no_statement>
 Note each alternative is only ONE statement!
 To have multiple statements execute in either branch  use
compound statement {}
5
Compound/Block Statement
 Only "get" one statement per branch
 Must use compound statement{}for multiples
 Also called a "block" statement
 Each block should have block statement
 Even if just one statement
 Enhances readability
if (myScore > yourScore)
{
cout << "I win!n";
Sum= Sum + 100;
}
else
{
cout << "I wish these were golf scores.n";
Sum= 0;
}
6
The Optional else
 else clause is optional
 If, in the false branch (else), you want "nothing" to
happen, leave it out
 Example:
if (sales >= minimum)
salary = salary + bonus;
cout << "Salary = %" << salary;
 Note: nothing to do for false condition, so there is no else
clause!
 Execution continues with cout statement
7
Nested Statements
 if-else statements contain smaller statements
 Compound or simple statements (we’ve seen)
 Can also contain any statement at all, including another if-
else stmt!
 Example:
if (speed > 55)
if (speed > 80)
cout << "You’re really speeding!";
else
cout << "You’re speeding.";
 Note proper indenting!
8
Multiway if-else: Display
 Not new, just different indenting
 Avoids "excessive" indenting
 Syntax:
9
Multiway if-else Example: Display
10
The switch Statement
 A new statement for controlling multiple branches
 Uses controlling expression which returns bool data type (T or
F)
 Syntax:
11
The switch Statement : Example
12
The switch: multiple case labels
 Execution "falls thru" until break
 switch provides a "point of entry"
 Example:
case "A":
case "a":
cout << "Excellent: you got an "A"!n";
break;
case "B":
case "b":
cout << "Good: you got a "B"!n";
break;
 Note: multiple labels provide same "entry"
13
switch Pitfalls/Tip
 Forgetting the break;
 No compiler error
 Execution simply "falls thru" other cases until break;
 Biggest use: MENUs
 Provides clearer "big-picture" view
 Shows menu structure effectively
 Each branch is one menu choice
14
switch and If-Else
switch example if-else equivalent
switch(x)
{
case 1:
cout<<"x is 1";
break;
case 2:
cout<<"x is 2";
break;
default:
cout<<"value of x unknown";
}
if(x == 1)
{
cout<<"x is 1";
}
else if(x == 2)
{
cout<<"x is 2";
}
else
{
cout<<"value of x unknown";
}
15
Iteration Structures (Loops)
 3 Types of loops in C++
 while
 Most flexible
 No "restrictions"
 do -while
 Least flexible
 Always executes loop body at least once
 for
 Natural "counting" loop
16
while Loops Syntax
// custom countdown using while
#include<iostream.h>
void main()
{
int n;
cout<<"Enter the starting number:";
cin>>n;
while(n>0)
{
cout<<n<<", ";
--n;
}
cout<<"FIRE!n";
}
Output:
Enter the starting number: 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
17
do-while Loop Syntax
//number echoer
#include <iostream.h>
void main()
{
long n;
do{
cout<<"Enter number (0 to end): ";
cin>>n;
cout<<"You entered: " << n << "n";
}while(n != 0);
}
Output:
Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0
18
While vs. do-while
 Very similar, but…
 One important difference
 Issue is "WHEN" boolean expression is checked
 while: checks BEFORE body is executed
 do-while: checked AFTER body is executed
 After this difference, they’re essentially identical!
 while is more common, due to it’s ultimate "flexibility"
19
for Loop Syntax
for (Init_Action; Bool_Exp; Update_Action)
Body_Statement
 Like if-else, Body_Statement can be a block statement
 Much more typical
// countdown using a for loop
#include <iostream.h>
void main ()
{
for(int n=10; n>0; n--)
{
cout<< n << ", ";
}
cout<< "FIRE!n";
}
Output:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
20
Converting Between For and While Loops
for (int i = 1; i < 1024; i *= 2){
cout << i << endl;
}
int i = 1;
while (i < 1024) {
cout << i << endl;
i *= 2;
}
21
Loop Pitfalls: Misplaced ;
 Watch the misplaced ; (semicolon)
 Example:
while (response != 0) ;
{
cout << "Enter val: ";
cin >> response;
}
 Notice the ";" after the while condition!
 Result here: INFINITE LOOP!
22
Loop Pitfalls: Infinite Loops
 Loop condition must evaluate to false at some iteration through
loop
 If not  infinite loop.
 Example:
while (1)
{
cout << "Hello ";
}
 A perfectly legal C++ loop  always infinite!
 Infinite loops can be desirable
 e.g., "Embedded Systems"
23
JUMP Statements -The break and continue Statements
 Flow of Control
 Recall how loops provide "graceful" and clear flow of
control in and out
 In RARE instances, can alter natural flow
 break;
 Forces loop to exit immediately.
 continue;
 Skips rest of loop body
 These statements violate natural flow
 Only used when absolutely necessary!
24
JUMP Statements -The break and continue Statements
 Break loop Example
// break loop example
#include<iostream.h>
void main()
{
int n;
for(n=10; n>0; n--)
{
cout<<n<<", ";
if(n==3)
{
cout<<"countdown aborted!";
break;
}
}
}
Output:
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
25
JUMP Statements -The break and continue Statements
 Continue loop Example
// continue loop example
#include<iostream.h>
void main ()
{
for(int n=10; n>0; n--)
{
if(n==5)
continue;
cout<<n<<", ";
}
cout<<"FIRE!n";
}
Output:
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
26
Nested Loops
 Recall: ANY valid C++ statements can be
inside body of loop
 This includes additional loop statements!
 Called "nested loops"
 Requires careful indenting:
for (outer=0; outer<5; outer++)
for (inner=7; inner>2; inner--)
cout << outer << inner;
 Notice no { } since each body is one statement
 Good style dictates we use { } anyway
27
Thank You

Contenu connexe

Similaire à 5.pptx fundamental programing one branch

Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
Loops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.pptLoops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.pptKamranAli649587
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8Programming Fundamentals lecture 8
Programming Fundamentals lecture 8REHAN IJAZ
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingNeeru Mittal
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptxAqeelAbbas94
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdfKirubelWondwoson1
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRKrishna Raj
 
Chp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptxChp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptxssuser10ed71
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.pptsanjay
 
Repetition loop
Repetition loopRepetition loop
Repetition loopAdnan Rana
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 

Similaire à 5.pptx fundamental programing one branch (20)

Control structures
Control structuresControl structures
Control structures
 
Loops c++
Loops c++Loops c++
Loops c++
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
Loops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.pptLoops_and_FunctionsWeek4_0.ppt
Loops_and_FunctionsWeek4_0.ppt
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Programming Fundamentals lecture 8
Programming Fundamentals lecture 8Programming Fundamentals lecture 8
Programming Fundamentals lecture 8
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
 
Janakiram web
Janakiram webJanakiram web
Janakiram web
 
Iterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop workingIterative control structures, looping, types of loops, loop working
Iterative control structures, looping, types of loops, loop working
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx
 
Chapter 3 - Flow of Control Part II.pdf
Chapter 3  - Flow of Control Part II.pdfChapter 3  - Flow of Control Part II.pdf
Chapter 3 - Flow of Control Part II.pdf
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
 
Chp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptxChp4_C++_Control Structures-Part2_Iteration.pptx
Chp4_C++_Control Structures-Part2_Iteration.pptx
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
Loops
LoopsLoops
Loops
 
Iteration
IterationIteration
Iteration
 
Repetition loop
Repetition loopRepetition loop
Repetition loop
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 

Dernier

247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...Call Girls in Nagpur High Profile
 

Dernier (20)

247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
High Profile Call Girls Nashik Megha 7001305949 Independent Escort Service Na...
 

5.pptx fundamental programing one branch

  • 1. 1 Abraham H. Fundamentals of Programming I Control Statements
  • 2. 2 Outline  Introduction  Conditional structure  If and else  The Selective Structure: Switch  Iteration structures (loops)  The while loop  The do-while loop  The for loop  Jump statements  The break statement  The continue statement
  • 3. 3 Introduction  C++ provides different forms of statements for different purposes  Declaration statements  Assignment-like statements. etc  The order in which statements are executed is called flow control  Branching statements  specify alternate paths of execution, depending on the outcome of a logical condition  Loop statements  specify computations, which need to be repeated until a certain logical condition is satisfied.
  • 4. 4 Branching Mechanisms  if-else statements  Choice of two alternate statements based on condition expression  Example: if (hrs > 40) grossPay = rate*40 + 1.5*rate*(hrs-40); else grossPay = rate*hrs;  if-else Statement syntax: if (<boolean_expression>) <yes_statement> else <no_statement>  Note each alternative is only ONE statement!  To have multiple statements execute in either branch  use compound statement {}
  • 5. 5 Compound/Block Statement  Only "get" one statement per branch  Must use compound statement{}for multiples  Also called a "block" statement  Each block should have block statement  Even if just one statement  Enhances readability if (myScore > yourScore) { cout << "I win!n"; Sum= Sum + 100; } else { cout << "I wish these were golf scores.n"; Sum= 0; }
  • 6. 6 The Optional else  else clause is optional  If, in the false branch (else), you want "nothing" to happen, leave it out  Example: if (sales >= minimum) salary = salary + bonus; cout << "Salary = %" << salary;  Note: nothing to do for false condition, so there is no else clause!  Execution continues with cout statement
  • 7. 7 Nested Statements  if-else statements contain smaller statements  Compound or simple statements (we’ve seen)  Can also contain any statement at all, including another if- else stmt!  Example: if (speed > 55) if (speed > 80) cout << "You’re really speeding!"; else cout << "You’re speeding.";  Note proper indenting!
  • 8. 8 Multiway if-else: Display  Not new, just different indenting  Avoids "excessive" indenting  Syntax:
  • 10. 10 The switch Statement  A new statement for controlling multiple branches  Uses controlling expression which returns bool data type (T or F)  Syntax:
  • 12. 12 The switch: multiple case labels  Execution "falls thru" until break  switch provides a "point of entry"  Example: case "A": case "a": cout << "Excellent: you got an "A"!n"; break; case "B": case "b": cout << "Good: you got a "B"!n"; break;  Note: multiple labels provide same "entry"
  • 13. 13 switch Pitfalls/Tip  Forgetting the break;  No compiler error  Execution simply "falls thru" other cases until break;  Biggest use: MENUs  Provides clearer "big-picture" view  Shows menu structure effectively  Each branch is one menu choice
  • 14. 14 switch and If-Else switch example if-else equivalent switch(x) { case 1: cout<<"x is 1"; break; case 2: cout<<"x is 2"; break; default: cout<<"value of x unknown"; } if(x == 1) { cout<<"x is 1"; } else if(x == 2) { cout<<"x is 2"; } else { cout<<"value of x unknown"; }
  • 15. 15 Iteration Structures (Loops)  3 Types of loops in C++  while  Most flexible  No "restrictions"  do -while  Least flexible  Always executes loop body at least once  for  Natural "counting" loop
  • 16. 16 while Loops Syntax // custom countdown using while #include<iostream.h> void main() { int n; cout<<"Enter the starting number:"; cin>>n; while(n>0) { cout<<n<<", "; --n; } cout<<"FIRE!n"; } Output: Enter the starting number: 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
  • 17. 17 do-while Loop Syntax //number echoer #include <iostream.h> void main() { long n; do{ cout<<"Enter number (0 to end): "; cin>>n; cout<<"You entered: " << n << "n"; }while(n != 0); } Output: Enter number (0 to end): 12345 You entered: 12345 Enter number (0 to end): 160277 You entered: 160277 Enter number (0 to end): 0 You entered: 0
  • 18. 18 While vs. do-while  Very similar, but…  One important difference  Issue is "WHEN" boolean expression is checked  while: checks BEFORE body is executed  do-while: checked AFTER body is executed  After this difference, they’re essentially identical!  while is more common, due to it’s ultimate "flexibility"
  • 19. 19 for Loop Syntax for (Init_Action; Bool_Exp; Update_Action) Body_Statement  Like if-else, Body_Statement can be a block statement  Much more typical // countdown using a for loop #include <iostream.h> void main () { for(int n=10; n>0; n--) { cout<< n << ", "; } cout<< "FIRE!n"; } Output: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
  • 20. 20 Converting Between For and While Loops for (int i = 1; i < 1024; i *= 2){ cout << i << endl; } int i = 1; while (i < 1024) { cout << i << endl; i *= 2; }
  • 21. 21 Loop Pitfalls: Misplaced ;  Watch the misplaced ; (semicolon)  Example: while (response != 0) ; { cout << "Enter val: "; cin >> response; }  Notice the ";" after the while condition!  Result here: INFINITE LOOP!
  • 22. 22 Loop Pitfalls: Infinite Loops  Loop condition must evaluate to false at some iteration through loop  If not  infinite loop.  Example: while (1) { cout << "Hello "; }  A perfectly legal C++ loop  always infinite!  Infinite loops can be desirable  e.g., "Embedded Systems"
  • 23. 23 JUMP Statements -The break and continue Statements  Flow of Control  Recall how loops provide "graceful" and clear flow of control in and out  In RARE instances, can alter natural flow  break;  Forces loop to exit immediately.  continue;  Skips rest of loop body  These statements violate natural flow  Only used when absolutely necessary!
  • 24. 24 JUMP Statements -The break and continue Statements  Break loop Example // break loop example #include<iostream.h> void main() { int n; for(n=10; n>0; n--) { cout<<n<<", "; if(n==3) { cout<<"countdown aborted!"; break; } } } Output: 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
  • 25. 25 JUMP Statements -The break and continue Statements  Continue loop Example // continue loop example #include<iostream.h> void main () { for(int n=10; n>0; n--) { if(n==5) continue; cout<<n<<", "; } cout<<"FIRE!n"; } Output: 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
  • 26. 26 Nested Loops  Recall: ANY valid C++ statements can be inside body of loop  This includes additional loop statements!  Called "nested loops"  Requires careful indenting: for (outer=0; outer<5; outer++) for (inner=7; inner>2; inner--) cout << outer << inner;  Notice no { } since each body is one statement  Good style dictates we use { } anyway