Lecture 5_Loops
Lecture 5_Loops
[email protected]
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
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
return 0;
}
(1) for loop - Syntax
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Example: Tracing a while Loop
(count < 2) is true
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Example: Tracing a while Loop
int count = 0;
Print “Welcome to C++”
while (count < 2)
{
cout << "Welcome to C++!";
count++;
}
Example: Tracing a while Loop
int count = 0;
while (count < 2)
{ Increase count by 1
count is 1 now
cout << "Welcome to C++!";
count++;
}
Example: Tracing a while Loop
(count < 2) is still true since
int count = 0; count is 1
int count = 0;
while (count < 2) Print “Welcome to C++”
{
cout << "Welcome to C++!";
count++;
}
Example: Tracing a while Loop
int count = 0;
while (count < 2)
Increase count by 1
{ count is 2 now
int count = 0;
while (count < 2)
{
cout << "Welcome to C++!";
count++; The loop exits. Execute the next
statement after the loop.
}
Example Program
-Writea program to print character entered by user,
terminate the program when ‘z’ is pressed.
Example Program
-Writea program to print character entered by user,
terminate the program when ‘z’ is pressed.
#include <iostream>
using namespace std;
int main( )
{
char ch='0';
cout<<"Enter characters, z to terminate..\n";
while(ch!='z'){
cin>>ch;
}
cout<<“Program ended…”
}
(while loop) -- Class Exercise-1
-Writea 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
#include <iostream>
using namespace std;
int main(){
char ch;
int count=0;
cout<<"Enter characters, 0 to terminate..\n";
while(ch!='0'){
cin>>ch;
count++;
}
cout<<"total characters entered: "<<count;
cout<<"Program ended…";
}
(while loop) -- Class Exercise-3
- Writea 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”.