I am trying to write a program to find nearest prime to a number to its left...using for loop
i just don't seem to get it right

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n1,flag=0;
cout<<"Enter The Number"<<endl;
cin>>n1;
for(int i=n1;i>0;i--)
{
for(int j=2;j<(i/2);j++)
{
if(i%j==0)
{
flag=0;
}
else if(flag=1)
{
cout<<i<<endl;
}
}
}
getch();
}
if(flag=1)
{
cout<<i<<endl;
}

You seem to be assigning 1 to flag but not checking.

if(flag==1)
{
cout<<i<<endl;
}

Secondly, Because you only need to find one prime number. return 0; after the cout statement, would stop it.

This is the syntactical part. I would not tend to give the answer away. But would give down the algorithm.

Checking Prime Numbers

1. Set flag to 0.
2. for i runs from 2 to n.
3. check if n divided by i gives out 0.
4. If yes, set flag to 1 and break.
5. in the outer loop check if flag == 0
6. If yes, print the number is prime. and return.
7. Else do nothing.

I am trying to write a program to find nearest prime to a number to its left...using for loop
i just don't seem to get it right

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n1,flag=0;
cout<<"Enter The Number"<<endl;
cin>>n1;
for(int i=n1;i>0;i--)
{
for(int j=2;j<(i/2);j++)
{
if(i%j==0)
{
flag=0;
}
else if(flag=1)
{
cout<<i<<endl;
}
}
}
getch();
}

^^first of all, stick to "INT MAIN()" instead of void main, besides, try using logically named variables and incprporation what Sky said, and you'll have something like this:

#include<iostream>
#include<conio.h>
using namespace std;

int main()
   {
   int SeachNumber=0, TestNumber=1, ModuloNumber=0;
   bool IsPrime=1;

   cout << "Enter The Number" << endl;
   cin >> SeachNumber;
   
   for (int a=1; a<SeachNumber; a++)
      {
      TestNumber++;
      IsPrime=true;
      for (ModuloNumber=2; ModuloNumber<TestNumber; ModuloNumber++)
          {if ((TestNumber%ModuloNumber)==0){IsPrime=false;}} 
      
      if(IsPrime==true)
          {
          cout << a << ". " << "Prime:\t"<< TestNumber << endl; 
          }
        }
   system("PAUSE");
   }

However, if you're interrested in finding like, prime numbers above 100mil, try incorporating "The Sieve of Eratosthenes":
http://upload.wikimedia.org/wikipedia/commons/c/c8/Animation_Sieve_of_Eratosth-2.gif

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.