For loop in C++
For loop:
The for is an entery entrolled loop and is used when an action is to be repeated for a predetermined number of times. Similarly When we have executes same line of statement repetitively is done by LOOP.
Syntax:
for(initial value; test; increment)
{
action1;
}
action2;
Program: Write a program to print 1 to 10 number using for loop .
Code:
#include<iostream>
using namespace std;
int main()
{
int i;
for(i=1;i<=10;i++)
{
printf("%d\n",i);
}
}
OUTPUT:
1
2
3
4
5
6
7
8
9
10
--------------------------------
Program2Write a Program in C++ to Print all natural numbers upto N without using semi- colon(;) using for loop.
Code:
#include<iostream>
using namespace std;
int main()
{
int i , no;
cout<<"Enter the number to print ";
cin>>no;
for(i=1;i<=no;i++)
{
if(cout<<i<<"\n")
{}
}
return 0;
}
OUTPUT:
Enter the number to print 5
1
2
3
4
5
----------------------------------------------------------------
Program: Write a C++ Program to display the cube of the numbers upto a given integer using for loop .
Code:
#include<iostream>
using namespace std;
int main()
{
int no,i, cube;
cout<<"Enter number to find cube up to that number ";
cin>>no;
for(i=1;i<=no;i++)
{
cube=i*i*i;
cout<<"\n cube of "<<i<<" is "<<cube;
}
}
OUPUT:
Enter number to find cube up to that number 5
cube of 1 is 1
cube of 2 is 8
cube of 3 is 27
cube of 4 is 64
cube of 5 is 125
--------------------------------------
Program: Write a program in C++ that takes a number as input and prints its multiplication table upto 10 using for loop.
Code:
#include<iostream>
using namespace std;
int main()
{
int num,i;
cout<<"Enter a number";
cin>>num;
for(i=1;i<=10;i++)
{
cout<<num*i;
cout<<"\n";
}
}
OUPUT:
Enter a number19
19
38
57
76
95
114
133
152
171
190
--------------------------------
Program: Write a program in C++ to check given number is prime or not
Code:
#include<iostream>
using namespace std;
int main()
{ int i=0,num,count=0;
cout<<"Enter a number: ";
cin>>num;
//cout<<i;
for(i=2;i<num;i++)
{
if(num%i==0)
{
count++;
break;
}
}
if(count==1)
{
cout<<"The number is not prime ";
}
else
cout<<"The number is prime";
return 0;
}
OUTPUT:
Enter a number: 19
The number is prime
------------------------------------
Comments
Post a Comment