SlideShare a Scribd company logo
1 of 27
Loop constructs
Department of Software Engineering,
Capital University of Science and Technology, Islamabad
2
Loops
• Loops cause a section of your program to be
repeated a certain number of times
• loops are used to repeat a block of code.
• Repeats until the condition remains true
• Terminates when the condition becomes
false
• For example, let's say we want to show a
message 100 times. Then instead of writing the
print statement 100 times, we can use a loop.
3
Loops in C++
1. for loop
2. while loop
3. do while 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
• OR
• A condition controlled loop is programming structure
that. causes a statement or set of statements to repeat as
long as a. condition evaluates to True.
Example: while and do while loops
for loop - Syntax
5
6
Example: 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;
for loop – Flow Chart
7
Example 1: for loop
Printing Numbers From 1 to 5
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << i << " ";
}
return 0;
}
8
Example 2: for loop
// C++ Program to display a
text 5 times
#include <iostream>
using namespace std;
int main()
{
for (int i = 1; i <= 5; ++i)
{
cout << "Hello World! " <<
endl;
}
return 0;
}
9
Example 3: for loop
Find the sum of first n Natural Numbers
#include <iostream>
using namespace std;
int main()
{
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i)
{
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}
10
11
Example 4: for loop
#include <iostream>
using namespace std;
int main()
{
int j;
for (j=0; j<10; j++)
cout << j * j <<endl;
return 0;
}
12
Example 5: for loop
- Get a number from user and calculate its factorial:
For any positive number n, it's factorial is given by:
• factorial = 1*2*3...*n
• Factorial of negative number cannot be found and
factorial of 0 is 1.
In this program below, user is asked to enter a
positive integer. Then the factorial of that number is
computed and displayed in the screen.
Cont…
13
14
for loop - Variable Visibility
int 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!
}
for loop - Variable Visibility
int main()
{
for(int j=0; j<5; j++)
cout<<“nValue of j: “<<j;
cout<<“nValue of j: “<<j; // ERROR
}
Loop body
15
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) 16
Infinite for loop
17
If the condition in a for loop is always true, it runs forever (until memory is full).
For example,
In the above program, the condition is always true which will then run the code
for infinite times.
While Loop- Syntax
18
• A while loop evaluates the condition
• If the condition evaluates to true, the code inside the while loop is executed.
• The condition is evaluated again.
• This process continues until the condition is false.
• When the condition evaluates to false, the loop terminates.
Flowchart of while Loop
19
Example 1: Display Numbers from 1
to 5
// C++ Program to print numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
// while loop from 1 to 5
while (i <= 5) {
cout << i << " ";
++i;
}
return 0;
}
20
Example 2: Sum of Positive Numbers Only
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "nThe sum is " << sum << endl;
return 0;
} 21
Example 3: Write a program to print the table of 10
using a while loop
22
#include<iostream>
using namespace std;
int main()
{
int t=1;
cout<<"Table of 10"<<endl;
while(t!=11)
{
cout<<"10 X "<<t<<"="<<10*t<<endl;
t=t+1;
}
return(0);
}
do...while Loop - Syntax
23
• The body of the loop is executed at first. Then the condition is evaluated.
• If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
• The condition is evaluated once again.
• If the condition evaluates to true, the body of the loop inside the do statement is
executed again.
• This process continues until the condition evaluates to false. Then the loop
stops.
Flowchart of do...while Loop
24
Example 4: Display Numbers from 1 to 5
// C++ Program to print numbers from 1 to 5
#include <iostream>
using namespace std;
int main() {
int i = 1;
// do...while loop from 1 to 5
do {
cout << i << " ";
++i;
}
while (i <= 5);
return 0;
}
25
Example 5: Sum of Positive Numbers Only
#include <iostream>
using namespace std;
int main() {
int number = 0;
int sum = 0;
do {
sum += number;
// take input from the user
cout << "Enter a number: ";
cin >> number;
}
while (number >= 0);
// display the sum
cout << "nThe sum is " << sum << endl;
return 0;
}
26
Infinite while Loop/ Do…While Loop
27

More Related Content

Similar to Lec7 - Loops updated.pptx

Loops in c language
Loops in c languageLoops in c language
Loops in c languagetanmaymodi4
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languageTanmay Modi
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while LoopJayBhavsar68
 
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
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and loopingaprilyyy
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1Mohamed Ahmed
 
5.pptx fundamental programing one branch
5.pptx fundamental programing one branch5.pptx fundamental programing one branch
5.pptx fundamental programing one branchssuserdde43b
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kimkimberly_Bm10203
 
loops and iteration.docx
loops and iteration.docxloops and iteration.docx
loops and iteration.docxJavvajiVenkat
 

Similar to Lec7 - Loops updated.pptx (20)

C++ programming
C++ programmingC++ programming
C++ programming
 
C++ loop
C++ loop C++ loop
C++ loop
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Loop and while Loop
Loop and while LoopLoop and while Loop
Loop and while Loop
 
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
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
Loops c++
Loops c++Loops c++
Loops c++
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 
C++ Course - Lesson 1
C++ Course - Lesson 1C++ Course - Lesson 1
C++ Course - Lesson 1
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
 
5.pptx fundamental programing one branch
5.pptx fundamental programing one branch5.pptx fundamental programing one branch
5.pptx fundamental programing one branch
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
Switch case and looping kim
Switch case and looping kimSwitch case and looping kim
Switch case and looping kim
 
loops and iteration.docx
loops and iteration.docxloops and iteration.docx
loops and iteration.docx
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Oop object oriented programing topics
Oop object oriented programing topicsOop object oriented programing topics
Oop object oriented programing topics
 

Recently uploaded

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
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
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
 
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
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
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
 
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
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
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
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 

Recently uploaded (20)

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
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
★ 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
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
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 )
 
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
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
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
 
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
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
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...
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 

Lec7 - Loops updated.pptx

  • 1. Loop constructs Department of Software Engineering, Capital University of Science and Technology, Islamabad
  • 2. 2 Loops • Loops cause a section of your program to be repeated a certain number of times • loops are used to repeat a block of code. • Repeats until the condition remains true • Terminates when the condition becomes false • For example, let's say we want to show a message 100 times. Then instead of writing the print statement 100 times, we can use a loop.
  • 3. 3 Loops in C++ 1. for loop 2. while loop 3. do while 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 • OR • A condition controlled loop is programming structure that. causes a statement or set of statements to repeat as long as a. condition evaluates to True. Example: while and do while loops
  • 5. for loop - Syntax 5
  • 6. 6 Example: 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 – Flow Chart 7
  • 8. Example 1: for loop Printing Numbers From 1 to 5 #include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; ++i) { cout << i << " "; } return 0; } 8
  • 9. Example 2: for loop // C++ Program to display a text 5 times #include <iostream> using namespace std; int main() { for (int i = 1; i <= 5; ++i) { cout << "Hello World! " << endl; } return 0; } 9
  • 10. Example 3: for loop Find the sum of first n Natural Numbers #include <iostream> using namespace std; int main() { int num, sum; sum = 0; cout << "Enter a positive integer: "; cin >> num; for (int i = 1; i <= num; ++i) { sum += i; } cout << "Sum = " << sum << endl; return 0; } 10
  • 11. 11 Example 4: for loop #include <iostream> using namespace std; int main() { int j; for (j=0; j<10; j++) cout << j * j <<endl; return 0; }
  • 12. 12 Example 5: for loop - Get a number from user and calculate its factorial: For any positive number n, it's factorial is given by: • factorial = 1*2*3...*n • Factorial of negative number cannot be found and factorial of 0 is 1. In this program below, user is asked to enter a positive integer. Then the factorial of that number is computed and displayed in the screen.
  • 14. 14 for loop - Variable Visibility int 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! }
  • 15. for loop - Variable Visibility int main() { for(int j=0; j<5; j++) cout<<“nValue of j: “<<j; cout<<“nValue of j: “<<j; // ERROR } Loop body 15
  • 16. 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) 16
  • 17. Infinite for loop 17 If the condition in a for loop is always true, it runs forever (until memory is full). For example, In the above program, the condition is always true which will then run the code for infinite times.
  • 18. While Loop- Syntax 18 • A while loop evaluates the condition • If the condition evaluates to true, the code inside the while loop is executed. • The condition is evaluated again. • This process continues until the condition is false. • When the condition evaluates to false, the loop terminates.
  • 20. Example 1: Display Numbers from 1 to 5 // C++ Program to print numbers from 1 to 5 #include <iostream> using namespace std; int main() { int i = 1; // while loop from 1 to 5 while (i <= 5) { cout << i << " "; ++i; } return 0; } 20
  • 21. Example 2: Sum of Positive Numbers Only #include <iostream> using namespace std; int main() { int number; int sum = 0; // take input from the user cout << "Enter a number: "; cin >> number; while (number >= 0) { // add all positive numbers sum += number; // take input again if the number is positive cout << "Enter a number: "; cin >> number; } // display the sum cout << "nThe sum is " << sum << endl; return 0; } 21
  • 22. Example 3: Write a program to print the table of 10 using a while loop 22 #include<iostream> using namespace std; int main() { int t=1; cout<<"Table of 10"<<endl; while(t!=11) { cout<<"10 X "<<t<<"="<<10*t<<endl; t=t+1; } return(0); }
  • 23. do...while Loop - Syntax 23 • The body of the loop is executed at first. Then the condition is evaluated. • If the condition evaluates to true, the body of the loop inside the do statement is executed again. • The condition is evaluated once again. • If the condition evaluates to true, the body of the loop inside the do statement is executed again. • This process continues until the condition evaluates to false. Then the loop stops.
  • 25. Example 4: Display Numbers from 1 to 5 // C++ Program to print numbers from 1 to 5 #include <iostream> using namespace std; int main() { int i = 1; // do...while loop from 1 to 5 do { cout << i << " "; ++i; } while (i <= 5); return 0; } 25
  • 26. Example 5: Sum of Positive Numbers Only #include <iostream> using namespace std; int main() { int number = 0; int sum = 0; do { sum += number; // take input from the user cout << "Enter a number: "; cin >> number; } while (number >= 0); // display the sum cout << "nThe sum is " << sum << endl; return 0; } 26
  • 27. Infinite while Loop/ Do…While Loop 27