SlideShare a Scribd company logo
1 of 30
Computer Programming
Conditions, loops
Prof. Dr. Mohammad Haseeb Zafar
haseeb@uetpeshawar.edu.pk
Today’s lecture
• Introduction to program control
– Conditional controls
• if, if … else, ?:, switch-case
– Loop controls
• for, while, do … while, if … break,
if … continue
• Typesetting of source code
• Use of indentation to keep track of nested conditions and loops
• Use of whitespace to group actions together
• Use of comments
• Log books
The need for program control
• Not all C++ programs execute from the first line, linearly to
the last,
– Most involve repetition, skipping and conditional branching
• In most programs, the program control path through the
code depends on the values of variables at different points in
the program
– The values of variables can be changed as the program proceeds
• Conditional statements can be used to selectively execute
either:
– A single line of code,
• Braces { } not required around the executable statement
– Multiple lines of related code (called a block)
• Braces { } REQUIRED around the executable statement
Flowchart: Hot drink example
(refer to Lecture 1) Start
Kettle water
level == 0?
Want milk?
Put teabag in mug
Tea
Drink!
NoExtract teabag
Yes
Add milk
Yes
Heat kettle
Yes
Fill kettle
Yes
Put instant coffee in mug
Coffee
Teabag in mug?
No
Want tea
or coffee?
No
Water
temp < 100?
No
If statement
A loop
Test condition for the loop
(whether or not to do an
iteration)
A switch
If statement
If statement
• The if keyword is used to test a given expression for a value of true or
false
– if the result is true, then a specified series of statements is executed
• the series of statements is specified within braces after the test
• the execution of these statements is conditional on the result of the test
– otherwise, those conditional statements are skipped
• The else keyword is used with an if statement to specify an alternative
path to be executed when the test expression is false
• Syntax:
if (test-expression)
{
code-to-be-executed-when-true;
}
Conditionals: if and if … else
Each
statement
ends with a
semi
colon!!
Conditional if statement
• Example program section:
int main(int argc, char* argv[])
{
int x=0, y=0;
cin >> x ;
cin >> y ;
if ( x > y )
cout << “true, x > yn“ ;
return 0;
}
Nested if statement
• if statements can be nested inside other if blocks to
express multiple tests, e.g. x < y, x == y, x != y
• Indentation applied for nested if blocks to keep track of
nested blocks
if (test1_expression)
{
if (test2_expression)
{
test2_true_action;
}
} Indentation
if-else statement
• This is called ‘conditional branching’ because the program
will choose a certain route depending on the test result.
• The syntax:
if (test-expression)
{
test_true_action1;
test_true_action2;
test_true_action3;
}
else
test_false_action;
if-else statement
• Example:
int main(int argc, char* argv[])
{
int int1;
cin >> int1;
if ( int1 > 1 )
cout << “yes, int1 is > 1n “ ;
else
cout << “ no, int1 is not > 1n “;
return 0;
}
Indentation
The ?: Conditional operator
• Unique to C/C++
• The ?: conditional operator provides a quick way to write a
test condition.
• Associated actions are performed depending on whether the
test_expression evaluates to true or false.
• The operator can be used to replace an equivalent if-else
statement.
• Syntax:
test_expression ? true_action : false_action ;
• Using example in previous slide:
(int1 > 1) ? cout << “yes, int1 is > 1n “ : cout << “
no, int1 is not > 1n “;
switch statement
• Multiple if-else statements
– conditional branching can often be more efficiently programmed by
using a switch statement
• switch uses a given integer/string/float… value then finds a
matching value among a series of case statements.
• default instructions can be specified for the case of no
match being found.
• Each case statement ends with a break instruction
– causes the remaining set of switch statements to be skipped.
switch statement
• Syntax
switch (integral_expression)
{
case constant1:
statements1;
break;
case constant2:
statements2;
break;
default:
statements;
}
No need for braces.
Statements execute until
break is encountered.
Never forget to
include break!
If integral_expression
is neither constant1 nor
constant2, execute the
following statements
switch statement
• Example:
int main(int argc, char* argv[])
{
int int1;
cout << “enter an integer: “;
cin >> int1;
switch (int1)
{ case 1 : cout << “1 foundn “ ; break;
case 2 : cout << “2 foundn “; break;
case 3 : cout << “3 foundn “; break;
default : cout << “ int1 is not 1, 2 or 3n “;
}
return 0;
}
Try choice of hot drink
example, e.g. hot drink
dispensing machine
Loops
• for, while and do-while loops
• The basic difference between a for loop and a while or
do-while loop has to do with the “known” number of
repetitions
– for loops are used whenever the required number of repetitions is
defined
• the required number of repetitions could be given by a constant or the
value of a variable
– while and do-while are used for an unknown number of
repetitions. (good for interrupt based codes or code that is invoked
on status changes)
for loops
• The loop iterates while the tested expression is true, repetitions
or iterations stop when the test-expression is found false.
• Syntax:
for(initialization_exp; test-exp; operation)
{
statements
}
• Example:
int i;
for(i=0; i < 2; i++)
{
cout << “iteration “ << i << endl;
} The operation doesn’t
need to be an increment
If i were initially 2, the cout
would never be executed
Only execute the statements inside the
braces if this condition is satisfied
Each time around the loop, perform this operation
Output:
iteration 0
iteration 1
Nested for-loops example
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
//note: indentation applied to keep track of nested loops
int i, j;
for(i = 1; i < 4; i++)
{
cout << “outer loop iteration” << i << endl;
for(j = 1; j < 4; j++)
{
cout << “t inner loop iteration” << j << endl;
}
}
return 0;
}
while loops
• The while keyword is combined with an expression to be
tested for a true or false value.
– If the tested expression is true, iteration around the loop will
continue,
– If the tested expression is false, iteration will stop.
• The while loop is a pre-test loop just like the for loop,
– the program evaluates the test_expression before entering the
statement(s) within the body of the loop.
– Pre-test loops can be executed from zero to many times.
while loops
• Syntax: while(test_expression) {statements}
• Example:
int i;
i = 0;
while(i < 2)
{
cout << “ iteration “ << i << endl;
i = i + 1;
}
Make sure the test_expression
comes to an end to avoid infinite looping
Equivalent to i+
+;
Output:
iteration 0
iteration 1This is equivalent to the first for example
do-while loops
• The do-while loop differs from the for and while loops in
that it is a post-test loop
– the loop is at least entered at least once
– the loop condition is tested at the end of the 1st
iteration.
• do-while loops are best used when there is no doubt the
statement(s) within the loop need to be executed at least
once
– e.g. presenting a menu to the user even if the user wants to exit
immediately after.
do-while loops
• The do keyword is followed by a statement block within
braces to be executed on each iteration.
• Then, the while keyword and an expression to be tested for
a true or false value.
– If the tested expression is true the loop will continue,
– If the tested expression is false, the loop will be exited.
– At least one execution of the statement block will occur.
• Syntax:
do {
statements
} while (test-expression);
do-while example
int i;
i = 0;
do
{
cout << “iteration “ << i << endl;
i = i + 1;
} while( i<2 );
As it stands, this produces the same result
as the previous while example
Output:
iteration 0
iteration 1
i is initially 0
No test on whether or not to
enter the do block
Execute the cout
First time through, i=1 so do the do block again
Second time through, i<2 is false so do not do the
do block again
do-while example
int i;
i = 2;
do
{
cout << “iteration “ << i << endl;
i = i + 1;
} while( i<2 );
• If i were initially 2 in the previous while example, the cout would not
have been executed
• In the do-while example above, however, the statements inside the
braces are executed at least once
• The test is applied only afterwards Output:
iteration 0
i is initially 2
if-break statement
• The break keyword was used to exit case statements inside a
switch. It can also be used to break out of a loop.
• A break statement can be used inside any loop statement block,
combined with a conditional test.
– When the test is found to be true the loop terminates (no more
iterations).
• Example/syntax:
int i = 0;
while( i < 4 )
{
i = i + 1;
cout << “ iteration “ << i;
if(i > 2) break;
cout << “go to the nextn“ ;
}
cout << “Go on through the programn”;
Output
iteration 1 go to the next
iteration 2 go to the next
iteration 3
Go on through the program
When i>2, the
program jumps out
of the loop
• go to the next
is not written
if-continue statement
• continue is used to go immediately to the start of the next iteration
• continue can be used inside any type of loop, combined with a
conditional test.
– When the test result is true
• current iteration is immediately terminated and the next iteration begins.
– Be careful to avoid infinite loops.
• It must be possible for the test result to be false
int i = 0;
while( i < 4 ) {
i = i + 1;
if(i == 2) continue;
cout << “ iteration “ << i;
cout << “go to the nextn“ ;
}
cout << “Go on through the programn”;
Output
iteration 1 go to the next
iteration 3 go to the next
Go on through the program
Review of syntax - 1
•if (test-expression)
{
code-to-be-executed-when-true
}
•if (test-expression)
{
do-this-if-true
}
else
{
do-this
}
•(test-expression)? if-true-do-this : if-false-do-this ;
Review of syntax - 2
•switch (a)
{
case a1 : s1; break;
case a2 : s2; break;
case a3 : s3; break;
default : s4;
}
•for(initializer; test-expression; operation)
{
statements
}
•while(test-expression) {statements}
•do{statements} while (test-expression);
•if(test) break ;
•if(test) continue;
Review of syntax - 3
•while(test-expression)
{
statements
}
•do
{
statements
} while (test-expression);
•if(test) break ;
•if(test) continue;
++,-- operators
• The ++ increment operator and -- decrement operator
change the given value by 1
– commonly used to count iterations in loops.
• Postfix increment operator, e.g. a++, uses the value of the
variable in an expression first and then increments its value.
• Prefix increment operator, e.g. ++a, increments the value of
the variable first and then uses the value in an expression.
• Examples:
int i=3, j, k=0;
• k = ++i; //i=4, k=4
• k = i++; //i=4, k=3
• i = j = k--; //i=0, j=0, k=-1
• TAKE CARE!
Whitespace, comments, endl,
n, indentation
• Some lines left blank, called whitespace, make it easier to
read your program,
– separate sections of code into related statements (grouping actions
together)
• The double-slash // comment is a C++ style comment
– tells the compiler to ignore everything that follows the slashes until
the end of the line.
• The c-style slash-star /* comment mark
– tells the compiler to ignore everything that follows until it finds a star-
slash */ comment mark
• n indicates the newline escape sequence,
– endl is a C++ alternative to n
• Use indentation to keep track of nested loops or conditions
Log books
• You must keep a log book
– The log book should be handed in once each semester
– 10% of the final marks will be based on your log book
• What should go in a log book?
– print outs of working source code you have written for
each lab
– notes of results of testing of code in each lab
– evidence of your own reflection on programming, e.g.
• annotation of source code to note important points
• aide memoires to yourself

More Related Content

What's hot

Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...whileJayfee Ramos
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Control Structure in C
Control Structure in CControl Structure in C
Control Structure in CNeel Shah
 
Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C pptMANJUTRIPATHI7
 
Switch statement, break statement, go to statement
Switch statement, break statement, go to statementSwitch statement, break statement, go to statement
Switch statement, break statement, go to statementRaj Parekh
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingDeeptiJava
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming LanguageMahantesh Devoor
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsIt Academy
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statementsjyoti_lakhani
 
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 ConceptsTech
 

What's hot (20)

Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Decision making and looping
Decision making and loopingDecision making and looping
Decision making and looping
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Control statements
Control statementsControl statements
Control statements
 
Control Structure in C
Control Structure in CControl Structure in C
Control Structure in C
 
Flow Control (C#)
Flow Control (C#)Flow Control (C#)
Flow Control (C#)
 
Control structures i
Control structures i Control structures i
Control structures i
 
Flow of control ppt
Flow of control pptFlow of control ppt
Flow of control ppt
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Java Control Statements
Java Control StatementsJava Control Statements
Java Control Statements
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Decision Making Statement in C ppt
Decision Making Statement in C pptDecision Making Statement in C ppt
Decision Making Statement in C ppt
 
Switch statement, break statement, go to statement
Switch statement, break statement, go to statementSwitch statement, break statement, go to statement
Switch statement, break statement, go to statement
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Loops in C Programming Language
Loops in C Programming LanguageLoops in C Programming Language
Loops in C Programming Language
 
Chapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java StatementsChapter 2 : Programming with Java Statements
Chapter 2 : Programming with Java Statements
 
java programming- control statements
 java programming- control statements java programming- control statements
java programming- control statements
 
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
 

Similar to Computer Programming Conditions and Loops

C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxSKUP1
 
C-Programming Control statements.pptx
C-Programming Control statements.pptxC-Programming Control statements.pptx
C-Programming Control statements.pptxLECO9
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in CSowmya Jyothi
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statementsVladislav Hadzhiyski
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxLikhil181
 
Chapter05-Control Structures.pptx
Chapter05-Control Structures.pptxChapter05-Control Structures.pptx
Chapter05-Control Structures.pptxAdrianVANTOPINA
 
Control statements anil
Control statements anilControl statements anil
Control statements anilAnil Dutt
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingChaAstillas
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdfsantosh147365
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while LoopJayBhavsar68
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesJason J Pulikkottil
 
Control structures.ppt
Control structures.pptControl structures.ppt
Control structures.pptRahul Borate
 

Similar to Computer Programming Conditions and Loops (20)

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
 
Ch6 Loops
Ch6 LoopsCh6 Loops
Ch6 Loops
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Unit II chapter 4 Loops in C
Unit II chapter 4 Loops in CUnit II chapter 4 Loops in C
Unit II chapter 4 Loops in C
 
Operators loops conditional and statements
Operators loops conditional and statementsOperators loops conditional and statements
Operators loops conditional and statements
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Iteration
IterationIteration
Iteration
 
Condition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptxCondition Stmt n Looping stmt.pptx
Condition Stmt n Looping stmt.pptx
 
Chapter05-Control Structures.pptx
Chapter05-Control Structures.pptxChapter05-Control Structures.pptx
Chapter05-Control Structures.pptx
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Programming loop
Programming loopProgramming loop
Programming loop
 
Control statements anil
Control statements anilControl statements anil
Control statements anil
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf3. Flow Controls in C (Part II).pdf
3. Flow Controls in C (Part II).pdf
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
Repetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniquesRepetition, Basic loop structures, Loop programming techniques
Repetition, Basic loop structures, Loop programming techniques
 
Control structures.ppt
Control structures.pptControl structures.ppt
Control structures.ppt
 

More from Manzoor ALam

8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkarManzoor ALam
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cppManzoor ALam
 
03a control structures
03a   control structures03a   control structures
03a control structuresManzoor ALam
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 

More from Manzoor ALam (6)

8085 microprocessor ramesh gaonkar
8085 microprocessor   ramesh gaonkar8085 microprocessor   ramesh gaonkar
8085 microprocessor ramesh gaonkar
 
01 introduction to cpp
01   introduction to cpp01   introduction to cpp
01 introduction to cpp
 
03b loops
03b   loops03b   loops
03b loops
 
03a control structures
03a   control structures03a   control structures
03a control structures
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 

Recently uploaded

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
 
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
 
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
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
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
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
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
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 

Recently uploaded (20)

Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
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
 
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
 
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
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
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...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
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)
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 

Computer Programming Conditions and Loops

  • 1. Computer Programming Conditions, loops Prof. Dr. Mohammad Haseeb Zafar haseeb@uetpeshawar.edu.pk
  • 2. Today’s lecture • Introduction to program control – Conditional controls • if, if … else, ?:, switch-case – Loop controls • for, while, do … while, if … break, if … continue • Typesetting of source code • Use of indentation to keep track of nested conditions and loops • Use of whitespace to group actions together • Use of comments • Log books
  • 3. The need for program control • Not all C++ programs execute from the first line, linearly to the last, – Most involve repetition, skipping and conditional branching • In most programs, the program control path through the code depends on the values of variables at different points in the program – The values of variables can be changed as the program proceeds • Conditional statements can be used to selectively execute either: – A single line of code, • Braces { } not required around the executable statement – Multiple lines of related code (called a block) • Braces { } REQUIRED around the executable statement
  • 4. Flowchart: Hot drink example (refer to Lecture 1) Start Kettle water level == 0? Want milk? Put teabag in mug Tea Drink! NoExtract teabag Yes Add milk Yes Heat kettle Yes Fill kettle Yes Put instant coffee in mug Coffee Teabag in mug? No Want tea or coffee? No Water temp < 100? No If statement A loop Test condition for the loop (whether or not to do an iteration) A switch If statement If statement
  • 5. • The if keyword is used to test a given expression for a value of true or false – if the result is true, then a specified series of statements is executed • the series of statements is specified within braces after the test • the execution of these statements is conditional on the result of the test – otherwise, those conditional statements are skipped • The else keyword is used with an if statement to specify an alternative path to be executed when the test expression is false • Syntax: if (test-expression) { code-to-be-executed-when-true; } Conditionals: if and if … else Each statement ends with a semi colon!!
  • 6. Conditional if statement • Example program section: int main(int argc, char* argv[]) { int x=0, y=0; cin >> x ; cin >> y ; if ( x > y ) cout << “true, x > yn“ ; return 0; }
  • 7. Nested if statement • if statements can be nested inside other if blocks to express multiple tests, e.g. x < y, x == y, x != y • Indentation applied for nested if blocks to keep track of nested blocks if (test1_expression) { if (test2_expression) { test2_true_action; } } Indentation
  • 8. if-else statement • This is called ‘conditional branching’ because the program will choose a certain route depending on the test result. • The syntax: if (test-expression) { test_true_action1; test_true_action2; test_true_action3; } else test_false_action;
  • 9. if-else statement • Example: int main(int argc, char* argv[]) { int int1; cin >> int1; if ( int1 > 1 ) cout << “yes, int1 is > 1n “ ; else cout << “ no, int1 is not > 1n “; return 0; } Indentation
  • 10. The ?: Conditional operator • Unique to C/C++ • The ?: conditional operator provides a quick way to write a test condition. • Associated actions are performed depending on whether the test_expression evaluates to true or false. • The operator can be used to replace an equivalent if-else statement. • Syntax: test_expression ? true_action : false_action ; • Using example in previous slide: (int1 > 1) ? cout << “yes, int1 is > 1n “ : cout << “ no, int1 is not > 1n “;
  • 11. switch statement • Multiple if-else statements – conditional branching can often be more efficiently programmed by using a switch statement • switch uses a given integer/string/float… value then finds a matching value among a series of case statements. • default instructions can be specified for the case of no match being found. • Each case statement ends with a break instruction – causes the remaining set of switch statements to be skipped.
  • 12. switch statement • Syntax switch (integral_expression) { case constant1: statements1; break; case constant2: statements2; break; default: statements; } No need for braces. Statements execute until break is encountered. Never forget to include break! If integral_expression is neither constant1 nor constant2, execute the following statements
  • 13. switch statement • Example: int main(int argc, char* argv[]) { int int1; cout << “enter an integer: “; cin >> int1; switch (int1) { case 1 : cout << “1 foundn “ ; break; case 2 : cout << “2 foundn “; break; case 3 : cout << “3 foundn “; break; default : cout << “ int1 is not 1, 2 or 3n “; } return 0; } Try choice of hot drink example, e.g. hot drink dispensing machine
  • 14. Loops • for, while and do-while loops • The basic difference between a for loop and a while or do-while loop has to do with the “known” number of repetitions – for loops are used whenever the required number of repetitions is defined • the required number of repetitions could be given by a constant or the value of a variable – while and do-while are used for an unknown number of repetitions. (good for interrupt based codes or code that is invoked on status changes)
  • 15. for loops • The loop iterates while the tested expression is true, repetitions or iterations stop when the test-expression is found false. • Syntax: for(initialization_exp; test-exp; operation) { statements } • Example: int i; for(i=0; i < 2; i++) { cout << “iteration “ << i << endl; } The operation doesn’t need to be an increment If i were initially 2, the cout would never be executed Only execute the statements inside the braces if this condition is satisfied Each time around the loop, perform this operation Output: iteration 0 iteration 1
  • 16. Nested for-loops example #include <iostream> using namespace std; int main(int argc, char* argv[]) { //note: indentation applied to keep track of nested loops int i, j; for(i = 1; i < 4; i++) { cout << “outer loop iteration” << i << endl; for(j = 1; j < 4; j++) { cout << “t inner loop iteration” << j << endl; } } return 0; }
  • 17. while loops • The while keyword is combined with an expression to be tested for a true or false value. – If the tested expression is true, iteration around the loop will continue, – If the tested expression is false, iteration will stop. • The while loop is a pre-test loop just like the for loop, – the program evaluates the test_expression before entering the statement(s) within the body of the loop. – Pre-test loops can be executed from zero to many times.
  • 18. while loops • Syntax: while(test_expression) {statements} • Example: int i; i = 0; while(i < 2) { cout << “ iteration “ << i << endl; i = i + 1; } Make sure the test_expression comes to an end to avoid infinite looping Equivalent to i+ +; Output: iteration 0 iteration 1This is equivalent to the first for example
  • 19. do-while loops • The do-while loop differs from the for and while loops in that it is a post-test loop – the loop is at least entered at least once – the loop condition is tested at the end of the 1st iteration. • do-while loops are best used when there is no doubt the statement(s) within the loop need to be executed at least once – e.g. presenting a menu to the user even if the user wants to exit immediately after.
  • 20. do-while loops • The do keyword is followed by a statement block within braces to be executed on each iteration. • Then, the while keyword and an expression to be tested for a true or false value. – If the tested expression is true the loop will continue, – If the tested expression is false, the loop will be exited. – At least one execution of the statement block will occur. • Syntax: do { statements } while (test-expression);
  • 21. do-while example int i; i = 0; do { cout << “iteration “ << i << endl; i = i + 1; } while( i<2 ); As it stands, this produces the same result as the previous while example Output: iteration 0 iteration 1 i is initially 0 No test on whether or not to enter the do block Execute the cout First time through, i=1 so do the do block again Second time through, i<2 is false so do not do the do block again
  • 22. do-while example int i; i = 2; do { cout << “iteration “ << i << endl; i = i + 1; } while( i<2 ); • If i were initially 2 in the previous while example, the cout would not have been executed • In the do-while example above, however, the statements inside the braces are executed at least once • The test is applied only afterwards Output: iteration 0 i is initially 2
  • 23. if-break statement • The break keyword was used to exit case statements inside a switch. It can also be used to break out of a loop. • A break statement can be used inside any loop statement block, combined with a conditional test. – When the test is found to be true the loop terminates (no more iterations). • Example/syntax: int i = 0; while( i < 4 ) { i = i + 1; cout << “ iteration “ << i; if(i > 2) break; cout << “go to the nextn“ ; } cout << “Go on through the programn”; Output iteration 1 go to the next iteration 2 go to the next iteration 3 Go on through the program When i>2, the program jumps out of the loop • go to the next is not written
  • 24. if-continue statement • continue is used to go immediately to the start of the next iteration • continue can be used inside any type of loop, combined with a conditional test. – When the test result is true • current iteration is immediately terminated and the next iteration begins. – Be careful to avoid infinite loops. • It must be possible for the test result to be false int i = 0; while( i < 4 ) { i = i + 1; if(i == 2) continue; cout << “ iteration “ << i; cout << “go to the nextn“ ; } cout << “Go on through the programn”; Output iteration 1 go to the next iteration 3 go to the next Go on through the program
  • 25. Review of syntax - 1 •if (test-expression) { code-to-be-executed-when-true } •if (test-expression) { do-this-if-true } else { do-this } •(test-expression)? if-true-do-this : if-false-do-this ;
  • 26. Review of syntax - 2 •switch (a) { case a1 : s1; break; case a2 : s2; break; case a3 : s3; break; default : s4; } •for(initializer; test-expression; operation) { statements } •while(test-expression) {statements} •do{statements} while (test-expression); •if(test) break ; •if(test) continue;
  • 27. Review of syntax - 3 •while(test-expression) { statements } •do { statements } while (test-expression); •if(test) break ; •if(test) continue;
  • 28. ++,-- operators • The ++ increment operator and -- decrement operator change the given value by 1 – commonly used to count iterations in loops. • Postfix increment operator, e.g. a++, uses the value of the variable in an expression first and then increments its value. • Prefix increment operator, e.g. ++a, increments the value of the variable first and then uses the value in an expression. • Examples: int i=3, j, k=0; • k = ++i; //i=4, k=4 • k = i++; //i=4, k=3 • i = j = k--; //i=0, j=0, k=-1 • TAKE CARE!
  • 29. Whitespace, comments, endl, n, indentation • Some lines left blank, called whitespace, make it easier to read your program, – separate sections of code into related statements (grouping actions together) • The double-slash // comment is a C++ style comment – tells the compiler to ignore everything that follows the slashes until the end of the line. • The c-style slash-star /* comment mark – tells the compiler to ignore everything that follows until it finds a star- slash */ comment mark • n indicates the newline escape sequence, – endl is a C++ alternative to n • Use indentation to keep track of nested loops or conditions
  • 30. Log books • You must keep a log book – The log book should be handed in once each semester – 10% of the final marks will be based on your log book • What should go in a log book? – print outs of working source code you have written for each lab – notes of results of testing of code in each lab – evidence of your own reflection on programming, e.g. • annotation of source code to note important points • aide memoires to yourself