Loops in C++: For Loop
Loops in C++: For Loop
Loops in C++: For Loop
for 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
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
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
#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;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
sum += number;
cout << "Enter a number: ";
cin >> number;
}
return 0;
}