PF For Loops
PF For Loops
Fundamentals
(PF)
Asma Khalid
Control Structures
(Repetition)
Programming Fundamentals
Objectives
In this Lecture, you will:
Learn about repetition (looping) control
structures
Explore how to construct and use counter-
controlled and sentinel-controlled repetition
structures
Examine break and continue statements
Discover how to form and use nested
repetition structures
3
Why Is Repetition Needed?
Repetitionstatements allow us to execute
statement/s multiple times
Often they are referred to as loops
Loopscause 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
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
Introduction to Computer Programming 5
Types of Loops in C++
Problem Statement:
Write a program which displays “Hello world” on
screen 10 times.
}
Solution 2 (with for loop)
int main()
{
int i;
for( i=1; i<=10; i++)
{
cout<<“Hello World”<<endl;
}
return 0;
}
Introduction to Computer Programming 14
Another Example
int main(){
for(int i=1; i<=6; i++){
/* This statement would be executed
* repeatedly until the condition
* i<=6 returns false.
*/
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
Introduction to Computer Programming 15
Another Example
int main(){
for(int i=1; i<=6; i++){ Output:
/* This statement would be executed Value of variable i is: 1
* repeatedly until the condition Value of variable i is: 2
* i<=6 returns false. Value of variable i is: 3
*/ Value of variable i is: 4
cout<<"Value of variable i is: Value of variable i is: 5
"<<i<<endl;
Value of variable i is: 6
}
return 0;
}
Introduction to Computer Programming 16
Infinite for loop
When it executes repeatedly and never stops
Cause:
When you set the condition in for loop in such a way that it
never return false, it becomes infinite loop.
Example
int main(){
for(int i=1; i>=1; i++){
cout<<"Value of variable i is: "<<i<<endl;
}
return 0;
}
Introduction to Computer Programming 17
for loop – Multiple Expressions
Multiple Initialization Only one Multiple Increment/Dec
expressions Test Condition expressions
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!
return 0;
}
Introduction to Computer Programming 19
The for Loop
Optional Expressions
The for Loop (Syntax)
j++;
for Loop – Optional Expression
Option 4
int j=0;
for(; ; )
{
cout<<“\nHello world“;
j++;
}
Infinite loop