SlideShare une entreprise Scribd logo
1  sur  45
Loop constructs
(CS1123)
By
Dr. Muhammad Aleem,
Department of Computer Science,
Mohammad Ali Jinnah University, Islamabad
Fall 2013
2
Loops
• Loops cause a section of your program
to be repeated a certain number of
times
• Repeats until the condition remains true
• Terminates when the condition becomes
false
3
Loops in C++
1. for loop
2. while loop
3. do loop
Loops
Counter-controlled Loops
• Depends on the value of a variable known as counter
variable. The value of the variable is incremented or
decremented in each iteration.
Example: for loop
Sentinel-Controlled Loops / Conditional loop
• A loop that terminates when something happens inside
the loop body indicating that loop should be exited. Also
known as conditional loops
Example: while and do loops
5
(1) for loop
#include <iostream>
using namespace std;
int main()
{
int j;
for (j=0; j<10; j++)
cout << j * j <<endl;
return 0;
}
6
(1) for loop - Syntax
for (int j=0; j<10; j++)
cout << j * j <<endl;
Initialization
expression
Test Condition
Increment expression
cout << j*2 <<endl;
cout << j*j*j <<endl;
7
(for loop) -- Class Exercise-1
- Get a number form user and calculate its factorial
8
(for loop) -- Class Exercise-2
- Write a program that ask the user to enter a
number. The program should print the Cube of all
integers starting from 1 to the Number.
E.g.,
Enter a Number: 4
1 1
2 6
3 27
4 64
(for loop) -- Class Exercise-3
- Write a program that asks the user to enter two
numbers: speed1, and speed2 representing speeds
in KPH (Kilo meters per Hour). Then the program
should convert and show table of speeds in MPH
(Miles per Hour) for all the speed values between
speed1 and speed2.
MPH = KPH * 0.6214
speed1 and speed2 variables should be multiple of
10. Each table entry (in KPH) should be updated by
5 in each iteration.
Lecture (12/10/2013)
11
for loop – Multiple Expressions
for (int j=0, k=9; j<10; j++,k--)
cout << j * j <<endl;
cout<< k*k <<endl;
Multiple Initialization
expressions
Only one
Test Condition
Multiple Increment/Dec
expressions
12
(1) for loop - Variable Visibility
void main()
{
int j;
for(j=0; j<10; j++) {
int k=0;
k = j*j;
cout<<“nValue of k: “<<k;
}
// k = 23; Cannot do this!
}
(1) for loop – optional expressions
int j=0;
for(; j<10; j++)
cout<<“nHello world“;
int j=0;
for(; j<10;)
{
cout<<“nHello world“;
j++;
}
for(; ;)
cout<<“nHello world“;
Infinite loop
(it never terminates)
14
(1) for loop - Variable Visibility
void main()
{
for(int j=0; j<5; j++)
cout<<“nValue of j: “<<j;
cout<<“nValue of j: “<<j; // ERROR
}
Loop body
while loop
• for loop does something a fixed number of times.
• If you don’t know how many times you want to do
something before you start the loop?
• In this case a different kind of loop may be used:
the while loop
while loop - syntax
Loop body contain
single statement
Loop body contain
Multiple statement
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Initialize count
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
(count < 2) is true
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Print “Welcome to C++”
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Increase count by 1
count is 1 now
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
(count < 2) is still true since
count is 1
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Print “Welcome to C++”
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Increase count by 1
count is 2 now
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
(count < 2) is false since count is 2
now
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Example: Tracing a while Loop
The loop exits. Execute the next
statement after the loop.
-Write a program to print character entered by user,
terminate the program when ‘z’ is pressed.
#include <iostream>
#include <conio.h>
using namespace std;
void main( )
{
char ch='0';
cout<<"Enter characters, z to terminate..n";
while(ch!='z')
ch = _getche();
cout<<“Program ended…”
}
Example Program
-Write a program to get characters from the user. In the
end of the program should count total characters
(entered by the user). The program should stop taking
input when 0 is pressed.
(while loop) -- Class Exercise-1
-Write a program to get input in the form of characters
from the user. In the end of the program should count
total words entered by the user. The program should
stop taking input when 1 is pressed.
(while loop) -- Class Exercise-2
- Write a program that inputs a value in an integer number
from user. For this number the program returns the count
for how many times can we divide this number by 2 to
get down to 1”.
(while loop) -- Class Exercise-3
int count = 0; int num; cin>>num;
//count how many divisions we've done
while (num >= 1)
{
num = num / 2;
count++;
}
cout<<“nWe have to divide: “<<count<<“ times”;
do loop
• In while loop if condition is false it is never entered
or executed
• Sometime, requirements are that the loop should
be executed at least once….
• For that, we use do loop, that guarantees at least
on execution of the loop body
do while loop - syntax
Loop body contain
single statement
Loop body contain
Multiple statement
do loop – Example1
#include <iostream>
using namespace std;
void main( )
{
int counter, howmuch;
cin>>howmuch;
counter = 0;
do {
counter++;
cout<<counter<<'n';
} while ( counter < howmuch);
}
do loop – Example2
void main( )
{
int num1, num2; char choice;
do {
cout<<“nEnter a number:”;
cin>>num1;
cout<<“nEnter another number:”;
cin>>num2;
cout<<“nTheir sum is: “<<num1+num2;
cout<<“nDo another time (y/n):”;
ch = _getche(); // #include <conio.h>
} while(ch==„y‟);
}
“break” Statement
• break statement
– Immediate exit from while, for, do/while, (also
used in switch)
– Program continues with first statement after the loop
structure
• Common uses of break in Loop
– Escape early from a loop OR skip remainder part of the
loop
“break” Statement Syntax
for (int i=1; i<=5; i++)
{
if (i==3)
break;
cout<<“Hello”;
}
===================================================
int n;
int EvenSum=0;
while(1)
{
cin>>n;
if(n%2==1)
break;
EvenSum = EvenSum + n;
}
(using break in loops) – Class Exercise 1
• Write a program which reads an integer n from the
user, and prints square value (n*n) for that number.
Whenever ZERO is entered by the user program
should terminate by printing “Invalid Value” message.
break in loop – Concusion
• “break” immediately ends the loop that
contains it.
“continue” Statement
• “continue” statement
– Only ends the current iteration. Program control
goes to the end of the loop body.
– Skips remainder of loop body (in current iteration)
– Proceeds with next iteration of loop
• “continue” can only be inside loops (for, while, or
do-while). IT CANNOT BE USED IN “switch”
“continue” Statement - example
for (int i=1; i<=5; i++)
{
if (i==3)
continue;
cout<<“Hello”<<i;
}
===================================================
int n;
int EvenSum=0;
while(1)
{
cin>>n;
if(n%2==1)
continue;
EvenSum = EvenSum + n;
}
Nested Repetition Structures
(Nested Loops)
• In a nested repetition structure, one loop (inner
loop) is placed entirely within another loop (outer
loop)
• In nested loops any loop (for, while, or do loop)
can be placed inside another loop which can be a
for, while, or a do loop
Nested Repetition Structures
(Nested Loops) - Example
for (int i=0; i<2; i++)
{
for (int j=0; j<2;j++)
{
cout<<“nHello-”<<i<<“:“<<j;
}
}
Outer Loop
Inner Loop
(Nested Loops) – Example Program-1
- Write a program to print triangle of starts.
*
**
***
****
*****
******
*******
********
*********
(Nested Loops) – Example Program-2
- Write a program to print triangle of starts.
*********
********
*******
******
*****
****
***
**
*
(Nested Loops) – Example Program-3
- Write a program to print Rectangle based on two
triangles (One using + and other using * symbol).
+********
++*******
+++******
++++*****
+++++****
++++++***
+++++++**
++++++++*
+++++++++
(Nested Loops) – Example Program-4
- Write a program for a company to calculate total sales for
3 regions. Each region’s sales is entered by user which is
then summed in total regional sales. The program keep
accepting regional sales until it is not 0. The program
prints the final regional sum for three regions and exits.
Example Output:
Total Sales for Region 1: 87645
Total Sales for Region 2: 2312
Total Sales for Region 3: 8874

Contenu connexe

Tendances

LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)Wang Hsiangkai
 
Instruction Combine in LLVM
Instruction Combine in LLVMInstruction Combine in LLVM
Instruction Combine in LLVMWang Hsiangkai
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library designLeonardo Borges
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in goborderj
 
JavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJanlay Wu
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"OdessaJS Conf
 
Debug Line Issues After Relaxation.
Debug Line Issues After Relaxation.Debug Line Issues After Relaxation.
Debug Line Issues After Relaxation.Wang Hsiangkai
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)jahanullah
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in RustChih-Hsuan Kuo
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.UA Mobile
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loopsbsdeol28
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in GeckoChih-Hsuan Kuo
 
JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements IIReem Alattas
 

Tendances (20)

LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)LLVM Register Allocation (2nd Version)
LLVM Register Allocation (2nd Version)
 
Instruction Combine in LLVM
Instruction Combine in LLVMInstruction Combine in LLVM
Instruction Combine in LLVM
 
The algebra of library design
The algebra of library designThe algebra of library design
The algebra of library design
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Machine Trace Metrics
Machine Trace MetricsMachine Trace Metrics
Machine Trace Metrics
 
JavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak Typing
 
Joel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMDJoel Falcou, Boost.SIMD
Joel Falcou, Boost.SIMD
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
Debug Line Issues After Relaxation.
Debug Line Issues After Relaxation.Debug Line Issues After Relaxation.
Debug Line Issues After Relaxation.
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Nested loops
Nested loopsNested loops
Nested loops
 
06 Loops
06 Loops06 Loops
06 Loops
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
CODEsign 2015
CODEsign 2015CODEsign 2015
CODEsign 2015
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
JavaScript Control Statements II
JavaScript Control Statements IIJavaScript Control Statements II
JavaScript Control Statements II
 

En vedette

En vedette (12)

Datatype introduction- JAVA
Datatype introduction- JAVADatatype introduction- JAVA
Datatype introduction- JAVA
 
Aae oop xp_04
Aae oop xp_04Aae oop xp_04
Aae oop xp_04
 
6 java - loop
6  java - loop6  java - loop
6 java - loop
 
Java Datatypes
Java DatatypesJava Datatypes
Java Datatypes
 
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
 
1 Introduction To Java Technology
1 Introduction To Java Technology 1 Introduction To Java Technology
1 Introduction To Java Technology
 
Basic Computer Skills Seminar
Basic Computer Skills Seminar Basic Computer Skills Seminar
Basic Computer Skills Seminar
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Java packages
Java packagesJava packages
Java packages
 
Java essentials for hadoop
Java essentials for hadoopJava essentials for hadoop
Java essentials for hadoop
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 

Similaire à Cs1123 6 loops

FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptxNaumanRasheed11
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.Farooq Mian
 
12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptxAqeelAbbas94
 
Control structures.ppt
Control structures.pptControl structures.ppt
Control structures.pptRahul Borate
 
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
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.pptsanjay
 
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
 

Similaire à Cs1123 6 loops (20)

FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
Iteration
IterationIteration
Iteration
 
Lec7 - Loops updated.pptx
Lec7 - Loops updated.pptxLec7 - Loops updated.pptx
Lec7 - Loops updated.pptx
 
Basic C concepts.
Basic C concepts.Basic C concepts.
Basic C concepts.
 
C++ control loops
C++ control loopsC++ control loops
C++ control loops
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
 
Loops
LoopsLoops
Loops
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx12-Lec - Repetition For Loop.pptx
12-Lec - Repetition For Loop.pptx
 
Control structures.ppt
Control structures.pptControl structures.ppt
Control structures.ppt
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
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
 
Control Statement.ppt
Control Statement.pptControl Statement.ppt
Control Statement.ppt
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
 
Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020
 
Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020
 
Ch4
Ch4Ch4
Ch4
 
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
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 

Plus de TAlha MAlik

Data file handling
Data file handlingData file handling
Data file handlingTAlha MAlik
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structuresTAlha MAlik
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointersTAlha MAlik
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_ifTAlha MAlik
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constantsTAlha MAlik
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_progTAlha MAlik
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 stringsTAlha MAlik
 

Plus de TAlha MAlik (12)

Data file handling
Data file handlingData file handling
Data file handling
 
Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Cs1123 7 arrays
Cs1123 7 arraysCs1123 7 arrays
Cs1123 7 arrays
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_prog
 
Cs1123 1 intro
Cs1123 1 introCs1123 1 intro
Cs1123 1 intro
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
 

Dernier

Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Dernier (20)

Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Cs1123 6 loops

  • 1. Loop constructs (CS1123) By Dr. Muhammad Aleem, Department of Computer Science, Mohammad Ali Jinnah University, Islamabad Fall 2013
  • 2. 2 Loops • Loops cause a section of your program to be repeated a certain number of times • Repeats until the condition remains true • Terminates when the condition becomes false
  • 3. 3 Loops in C++ 1. for loop 2. while loop 3. do loop
  • 4. Loops Counter-controlled Loops • Depends on the value of a variable known as counter variable. The value of the variable is incremented or decremented in each iteration. Example: for loop Sentinel-Controlled Loops / Conditional loop • A loop that terminates when something happens inside the loop body indicating that loop should be exited. Also known as conditional loops Example: while and do loops
  • 5. 5 (1) for loop #include <iostream> using namespace std; int main() { int j; for (j=0; j<10; j++) cout << j * j <<endl; return 0; }
  • 6. 6 (1) for loop - Syntax for (int j=0; j<10; j++) cout << j * j <<endl; Initialization expression Test Condition Increment expression cout << j*2 <<endl; cout << j*j*j <<endl;
  • 7. 7 (for loop) -- Class Exercise-1 - Get a number form user and calculate its factorial
  • 8. 8 (for loop) -- Class Exercise-2 - Write a program that ask the user to enter a number. The program should print the Cube of all integers starting from 1 to the Number. E.g., Enter a Number: 4 1 1 2 6 3 27 4 64
  • 9. (for loop) -- Class Exercise-3 - Write a program that asks the user to enter two numbers: speed1, and speed2 representing speeds in KPH (Kilo meters per Hour). Then the program should convert and show table of speeds in MPH (Miles per Hour) for all the speed values between speed1 and speed2. MPH = KPH * 0.6214 speed1 and speed2 variables should be multiple of 10. Each table entry (in KPH) should be updated by 5 in each iteration.
  • 11. 11 for loop – Multiple Expressions for (int j=0, k=9; j<10; j++,k--) cout << j * j <<endl; cout<< k*k <<endl; Multiple Initialization expressions Only one Test Condition Multiple Increment/Dec expressions
  • 12. 12 (1) for loop - Variable Visibility void main() { int j; for(j=0; j<10; j++) { int k=0; k = j*j; cout<<“nValue of k: “<<k; } // k = 23; Cannot do this! }
  • 13. (1) for loop – optional expressions int j=0; for(; j<10; j++) cout<<“nHello world“; int j=0; for(; j<10;) { cout<<“nHello world“; j++; } for(; ;) cout<<“nHello world“; Infinite loop (it never terminates)
  • 14. 14 (1) for loop - Variable Visibility void main() { for(int j=0; j<5; j++) cout<<“nValue of j: “<<j; cout<<“nValue of j: “<<j; // ERROR } Loop body
  • 15. while loop • for loop does something a fixed number of times. • If you don’t know how many times you want to do something before you start the loop? • In this case a different kind of loop may be used: the while loop
  • 16. while loop - syntax Loop body contain single statement Loop body contain Multiple statement
  • 17. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Initialize count Example: Tracing a while Loop
  • 18. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } (count < 2) is true Example: Tracing a while Loop
  • 19. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Print “Welcome to C++” Example: Tracing a while Loop
  • 20. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Increase count by 1 count is 1 now Example: Tracing a while Loop
  • 21. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } (count < 2) is still true since count is 1 Example: Tracing a while Loop
  • 22. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Print “Welcome to C++” Example: Tracing a while Loop
  • 23. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Increase count by 1 count is 2 now Example: Tracing a while Loop
  • 24. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } (count < 2) is false since count is 2 now Example: Tracing a while Loop
  • 25. int count = 0; while (count < 2) { cout << "Welcome to C++!"; count++; } Example: Tracing a while Loop The loop exits. Execute the next statement after the loop.
  • 26. -Write a program to print character entered by user, terminate the program when ‘z’ is pressed. #include <iostream> #include <conio.h> using namespace std; void main( ) { char ch='0'; cout<<"Enter characters, z to terminate..n"; while(ch!='z') ch = _getche(); cout<<“Program ended…” } Example Program
  • 27. -Write a program to get characters from the user. In the end of the program should count total characters (entered by the user). The program should stop taking input when 0 is pressed. (while loop) -- Class Exercise-1
  • 28. -Write a program to get input in the form of characters from the user. In the end of the program should count total words entered by the user. The program should stop taking input when 1 is pressed. (while loop) -- Class Exercise-2
  • 29. - Write a program that inputs a value in an integer number from user. For this number the program returns the count for how many times can we divide this number by 2 to get down to 1”. (while loop) -- Class Exercise-3 int count = 0; int num; cin>>num; //count how many divisions we've done while (num >= 1) { num = num / 2; count++; } cout<<“nWe have to divide: “<<count<<“ times”;
  • 30. do loop • In while loop if condition is false it is never entered or executed • Sometime, requirements are that the loop should be executed at least once…. • For that, we use do loop, that guarantees at least on execution of the loop body
  • 31. do while loop - syntax Loop body contain single statement Loop body contain Multiple statement
  • 32. do loop – Example1 #include <iostream> using namespace std; void main( ) { int counter, howmuch; cin>>howmuch; counter = 0; do { counter++; cout<<counter<<'n'; } while ( counter < howmuch); }
  • 33. do loop – Example2 void main( ) { int num1, num2; char choice; do { cout<<“nEnter a number:”; cin>>num1; cout<<“nEnter another number:”; cin>>num2; cout<<“nTheir sum is: “<<num1+num2; cout<<“nDo another time (y/n):”; ch = _getche(); // #include <conio.h> } while(ch==„y‟); }
  • 34. “break” Statement • break statement – Immediate exit from while, for, do/while, (also used in switch) – Program continues with first statement after the loop structure • Common uses of break in Loop – Escape early from a loop OR skip remainder part of the loop
  • 35. “break” Statement Syntax for (int i=1; i<=5; i++) { if (i==3) break; cout<<“Hello”; } =================================================== int n; int EvenSum=0; while(1) { cin>>n; if(n%2==1) break; EvenSum = EvenSum + n; }
  • 36. (using break in loops) – Class Exercise 1 • Write a program which reads an integer n from the user, and prints square value (n*n) for that number. Whenever ZERO is entered by the user program should terminate by printing “Invalid Value” message.
  • 37. break in loop – Concusion • “break” immediately ends the loop that contains it.
  • 38. “continue” Statement • “continue” statement – Only ends the current iteration. Program control goes to the end of the loop body. – Skips remainder of loop body (in current iteration) – Proceeds with next iteration of loop • “continue” can only be inside loops (for, while, or do-while). IT CANNOT BE USED IN “switch”
  • 39. “continue” Statement - example for (int i=1; i<=5; i++) { if (i==3) continue; cout<<“Hello”<<i; } =================================================== int n; int EvenSum=0; while(1) { cin>>n; if(n%2==1) continue; EvenSum = EvenSum + n; }
  • 40. Nested Repetition Structures (Nested Loops) • In a nested repetition structure, one loop (inner loop) is placed entirely within another loop (outer loop) • In nested loops any loop (for, while, or do loop) can be placed inside another loop which can be a for, while, or a do loop
  • 41. Nested Repetition Structures (Nested Loops) - Example for (int i=0; i<2; i++) { for (int j=0; j<2;j++) { cout<<“nHello-”<<i<<“:“<<j; } } Outer Loop Inner Loop
  • 42. (Nested Loops) – Example Program-1 - Write a program to print triangle of starts. * ** *** **** ***** ****** ******* ******** *********
  • 43. (Nested Loops) – Example Program-2 - Write a program to print triangle of starts. ********* ******** ******* ****** ***** **** *** ** *
  • 44. (Nested Loops) – Example Program-3 - Write a program to print Rectangle based on two triangles (One using + and other using * symbol). +******** ++******* +++****** ++++***** +++++**** ++++++*** +++++++** ++++++++* +++++++++
  • 45. (Nested Loops) – Example Program-4 - Write a program for a company to calculate total sales for 3 regions. Each region’s sales is entered by user which is then summed in total regional sales. The program keep accepting regional sales until it is not 0. The program prints the final regional sum for three regions and exits. Example Output: Total Sales for Region 1: 87645 Total Sales for Region 2: 2312 Total Sales for Region 3: 8874