Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Loops in C++: For Loop

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Loops in C++

A loop is used for executing a block of statements repeatedly until a particular


condition is satisfied. A loop consists of an initialization statement, a test
condition and an increment statement.

for loop

The syntax of the for loop is

for (initialization; condition; update) {


// body of-loop
}

#include<iostream>
using namespace std;

int main(){

for(int i=1;i<=5;i++){
cout<<i<<" ";
}

return 0;
}

Output –
The for loop is initialized by the value 1, the test condition is i<=5 i.e the loop is
executed till the value of i remains lesser than or equal to 5. In each iteration
the value of i is incremented by one by doing i++.

while loop

The syntax for while loop is

while (condition) {
// body of the loop
}

#include<iostream>
using namespace std;

int main(){

int i=1;

while(i<=5){
cout<<i<<" ";
i++;
}
return 0;
}

Output-
The while loop is initialized by the value 1, the test condition is i<=5 i.e the loop
is executed till the value of i remains lesser than or equal to 5. In each iteration
the value of i is incremented by one by doing i++.

do hile loop

The syntax for while loop is

do {
// body of loop;
}
while (condition);

#include<iostream>
using namespace std;

int main(){

int i=1;

do
{
cout<<i<<" ";
i++;
} while (i<=5);

return 0;
}
Output-

The do while loop variable is initialized by the value 1, in each iteration the
value of i is incremented by one by doing i++, the test condition is i<=5 i.e the
loop is executed till the value of i remains lesser than or equal to 5. Since the
testing condition is checked only once the loop has already run so a do while
loop runs at least once.

Examples

Ques1. Program to find sum of natural numbers till n.

#include<iostream>
using namespace std;

int main(){

int n;
cin>>n;

int sum=0;
for(int counter=1;counter<=n;counter++){
sum=sum+counter;
}

cout<<sum<<endl;

return 0;
}
Ques2. Program to display multiplication table upto 10.

#include <iostream>
using namespace std;

int main()
{
int n;

cout << "Enter a positive integer: ";


cin >> n;

for (int i = 1; i <= 10; ++i) {


cout << n << " * " << i << " = " << n * i << endl;
}

return 0;
}

Ques3. Program to add only positive numbers.

#include <iostream>
using namespace std;

int main() {
int number;
int sum = 0;

cout << "Enter a number: ";


cin >> number;
while (number >= 0) {

sum += number;
cout << "Enter a number: ";
cin >> number;
}

cout << "\nThe sum is " << sum << endl;

return 0;
}

You might also like