2 - Loops
2 - Loops
2 - Loops
– “Hello world “
– “Hello world “
– “Hello world “
– “Hello world “
– “Hello world “
– “Hello world “
– “Hello world “
– “Hello world “
– “Hello world “
– “Hello world “
Loops
• If we want to print “Hello world“ 1000 times ?
It's too boring, right ?
}
return 0;
}
Loops
While loops: While loops have only a condition in its syntax
“while the condition is true, go in the loop”.
Syntax :
while( condition ) {
// Statement
}
int main() {
int i = 0;
while(i < 100){
cout << "Hello world" << endl;
i++;
}
return 0;
}
Loops
• do-while loop : The do-while loop is a very
similar loop,
whose syntax is:
do {
// Statements
} while (condition);
Loops
A simple do-while loop code
int main() {
int i = 0;
do {
cout << "Hello world" << endl;
i++;
}while(i < 100);
return 0;
}
Problems
1. Write a program to print numbers from 1 to 10
int sum = 0;
● Continue statement for(int i = 0; i < 10; i++){
when the compiler read this int a;
statement, it ignore the cin >> a;
remainder statements and go to if(a % 2 == 0){
the next time in the loop continue;
}
sum = sum + i;
In this code, sum will have the
}
summation of odd numbers
Problems
1. Write a program take a numbers from user
until enter 0.
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
}