Â
In this, we are going to see for loop, the program is based on for loop which basically, finds all the Prime Numbers from 1 to the number specified by the user.
The code given below can be used for TURBO C++ Compiler:-
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i,flag;
cout <<"Enter the Number to print all Prime numbers till it from 1: ";
cin >>n;
cout<<"Prime numbers between 1 and "<<n<<"are:\n";
for (i = 2; i <= n; i++)
{
flag=0;
for(int j=2; j<=i/2;j++){
if(i%j==0){
flag++;
break;
}
}
if(flag==0)
cout<<i<<" ";
}
getch();
}
The code given below can be used for g++/gcc Compiler:-
#include<iostream>
using namespace std;
int main()
{
int n, i,flag;
cout <<"Enter the Number to print all Prime numbers till it from 1: ";
cin >>n;
cout<<"Prime numbers between 1 and "<<n<<"are:\n";
for (i = 2; i <= n; i++)
{
flag=0;
for(int j=2; j<=i/2;j++){
if(i%j==0){
flag++;
break;
}
}
if(flag==0)
cout<<i<<" ";
}
return 0;
}
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP