Loops
Loops
Loops
Topics to be covered:
The simple dictionary meaning of loop is a structure, series, or process, the end of which is connected to the
The advantage of a for loop is we know exactly how many times the loop will execute even before the actual
Syntax:
statement
// logic
Init-statement: This statement is used to initialize or assign a starting value to a variable which may be altered
over the course of the loop (we will see this while solving examples). It is used/referred only once at the start of
the loop.
Condition: This condition serves as a loop control statement. The loop block is executed until the condition
evaluates to true.
Final-expression: It is evaluated after each iteration of the loop. It is generally to update the values of the loop
variables.
Example:
Output: 1 2 3 4 5
Java
C++ &+ DSA
DSA
The while loop
A while loop is a loop that runs through its body, known as a while statement, as long as a predetermined
condition is evaluated as true.
Syntax:
while (condition)
statement;
Example:
int i = 1;
while (i <= 5)
i = i + 1;
Output: 1 2 3 4 5
Do-while loop tests the condition at the end of each execution for the next iteration. In other words, the loop is
executed at least once before the condition is checked. Rest everything is the same as while loop.
Syntax:
do
statement;
} while (condition);
Example:
int idx = 1;
do
idx++;
Output: 1 2 3 4 5
Q1. Print hello world ‘n’ times. Take ‘n’ as input from user
Solution:
#include<iostream>
Java
C++ &+ DSA
DSA
int main()
int n;
cin>>n;
for(int i=1;i<=n;i++){
cout<<”hello world”<<endl;
#include<iostream>
int main()
for(int i=1;i<=100;i++){
cout<<i<<endl;
#include<iostream>
int main()
for(int i=2;i<=100;i+=2){
cout<<i<<endl;
#include<iostream>
int main()
for(int i=1;i<=10;i++){
cout<<19*i<<endl;
Java
C++ &+ DSA
DSA
Q5. Display this AP - 1,3,5,7,9.. upto ‘n’ terms.
#include<iostream>
int main()
int n;
cin>>n;
for(int i=1;i<=n;i+=2){
cout<<i<<endl;
Solution:
#include<iostream>
int main()
int n;
cin>>n;
for(int i=1;i<=n;i*=2){
cout<<i<<endl;
#include<iostream>
int main()
for(int i=100;i>0;i-=3){
cout<<i<<endl;
Java
C++ &+ DSA
DSA
THANK
YOU !