1,105,226 Community Members

Print Prime Numbers(using for loop)

Member Avatar
john_hasan
Newbie Poster
5 posts since Apr 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-1
 

Friends i have little bit problem in making a c language program.
I have to make a program which prints prime numbers from 1 to 500.
I make this program but with while loop then i was told to make it using for loop, which i tried but failed.
So kindly help me. Thanks
from,
john(pakistan)

Member Avatar
Micko
Junior Poster
148 posts since Aug 2005
Reputation Points: 2 [?]
Q&As Helped to Solve: 10 [?]
Skill Endorsements: 0 [?]
 
0
 

No problem, just show us what you manage to do so far...

Member Avatar
john_hasan
Newbie Poster
5 posts since Apr 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
-2
 

It is my while loop program:

#include<stdio.h>
#include<conio.h>
void main()
{
int count,i=1;
int a;
clrscr();
while(i<=500)
{
count=0;
a=1;
while(a<=i)
{
if(i%a==0)
count++;
a++;
}
if(count==2)
printf("%d\t",i);
i++;
}
getch();
}
Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 

Here you go. Added for loop in place of while, and commented out the i++ at end of while loop.

Also added int variable col, to print a newline every ten numbers printed to standard out.

#include<stdio.h>
#include<conio.h>

int main(int argc, char *argv[])
{
    int count,i=1;
    int a;
    int col=0;
    
    //while(i<=500)
    for(i=1; i<501; i++)
    {
        count=0;
        a=1;
        
        while(a<=i)
        {
            if(i%a==0)
                    count++;
            a++;
        }
        
        if(count==2){
            printf("%d\t",i);
            col++;
            if(col%10==0)
                printf("\n");
        }  
        //i++;
    }
 
  system("PAUSE");	
  return 0;
}
Member Avatar
Salem
Posting Sage
7,177 posts since Dec 2005
Reputation Points: 5,138 [?]
Q&As Helped to Solve: 970 [?]
Skill Endorsements: 41 [?]
Team Colleague
 
0
 

> I make this program but with while loop then i was told to make it using for loop, which i tried but failed.

So turn

i = 0;
while ( i < 500 ) {
  // do stuff
  i++;
}

To

for ( i = 0 ; i < 500 ; i++ ) {
  // do stuff
}
Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 

DOH! Salem

Johns' while loop was: less than OR EQUAL to 500.

So change to for i < 501 NOT 500.

This is Johns' future your playing with, pay attention.

Member Avatar
Salem
Posting Sage
7,177 posts since Dec 2005
Reputation Points: 5,138 [?]
Q&As Helped to Solve: 970 [?]
Skill Endorsements: 41 [?]
Team Colleague
 
0
 

I didn't pay any attention to his program, it wasn't formatted with code tags.

All I did was illustrate the relationship between for loops and while loops, and how ridiculously easy it is to convert one into the other.

Member Avatar
shavez_israr
Newbie Poster
1 post since Apr 2006
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Friends i have little bit problem in making a c language program.
I have to make a program which prints prime numbers from 1 to 500.
I make this program but with while loop then i was told to make it using for loop, which i tried but failed.
So kindly help me. Thanks
from,
john(pakistan)

int flag=1;
for(int i=2;i<500;i++)      //since 1 and 500 are not prime
{                  
flag=1;
for(int j=2;j<i/2;j++)   //since a no. cannot be divisible by a 
{                                //no. greater than its half.
if(i%j==0)                 //if i is divisible by any no. between 2 & i/2
{
flag=0;
break;
}
}
if(flag==1)
printf("\n",i);
}
Member Avatar
Salem
Posting Sage
7,177 posts since Dec 2005
Reputation Points: 5,138 [?]
Q&As Helped to Solve: 970 [?]
Skill Endorsements: 41 [?]
Team Colleague
 
0
 

> for(int j=2;j<i/2;j++) //since a no. cannot be divisible by a
> { //no. greater than its half.
It's square root of actually, but hey what the heck.

At least it's not the only mistake in your code.

Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 

Ok here's my best shot. The key rule for a prime number is:

It has precisely two positive integer factors.

So the neatest solution I can think of counts those and quits the for loop as soon as it's found more than 2 or reached half way to n.

Can anyone better it?

#include <iostream>

using namespace std;

static const int MAX = 500;
static const int MIN = 0;
static const int MAXCOL = 10;

bool isPrime(int r);

int main(int argc, char *argv[])
{
    int col = 0;
    int n;
    
    for(n=MIN; n<=MAX; n++)
      if(isPrime(n)){
          cout << n << '\t';
          col++;
          if(col == MAXCOL){
              cout << '\n';
              col = 0;
          }
      }  
      
  system("PAUSE");	
  return 0;
  
}

bool isPrime(int n)
{
    if((n == 0)||(n == 1))
        return false;
        
    int factors = 2;
            
    for(int i=2; i<=((int)n/2); i++){
        if(n%i == 0){
            factors++;
            break;
        }
    }
            
    if(factors == 2)
        return true;
    
   return false;
}
Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 

Ah it's just occured to me what Salem meant by square root !

A revised edition:

#include <iostream>
#include <cmath>

using namespace std;

static const int MAX = 500;
static const int MIN = 0;
static const int MAXCOL = 10;

bool isPrime(int r);

int main(int argc, char *argv[])
{
    int col = 0;
    int n;
    
    for(n=MIN; n<=MAX; n++)
      if(isPrime(n)){
          cout << n << '\t';
          col++;
          if(col == MAXCOL){
              cout << '\n';
              col = 0;
          }
      }  
      
  system("PAUSE");	
  return 0;
  
}

bool isPrime(int n)
{
    if((n == 0)||(n == 1))
        return false;
        
    int factors = 2;
            
    for(int i=2; i<=((int)sqrt((double)n)); i++){
        if(n%i == 0){
            factors++;
            break;
        }
    }
            
    if(factors == 2)
        return true;
    
   return false;
}

Now if only I could make i++ step in primes!

Member Avatar
iamthwee
Posting Sage
7,051 posts since Aug 2005
Reputation Points: 1,307 [?]
Q&As Helped to Solve: 593 [?]
Skill Endorsements: 74 [?]
Featured
 
0
 

>can anyone better it?

Yes, there are more faster prime number finding Al-Gore-it-hims out there.
http://en.wikipedia.org/wiki/Sieve_of_Atkin

Note I said faster as opposed to efficient. An efficient prime number list finding strategy would be rather elusive.

Also, I'm sure you can think of a much better way to pause the program than using system("PAUSE"); ?

:lol:

Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 


Also, I'm sure you can think of a much better way to pause the program than using system("PAUSE"); ?

:lol:

Ok whats wrong with system("PAUSE") ?

I

Member Avatar
dude543
Light Poster
26 posts since Apr 2006
Reputation Points: 2 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
1
 

I dont know that high math, but I think I can do better.

bool isPrime(int n)
{
bool prime ;
int  lim;
 
if ( n == 0 || n == 1 || n % 2 == 0)
   return(false);

prime = true;
lim = (int)sqrt(n); 
 
for(int i=3; i<= lim && prime ; i+=2)
       prime =  n % i;
return(prime);
}
Member Avatar
Salem
Posting Sage
7,177 posts since Dec 2005
Reputation Points: 5,138 [?]
Q&As Helped to Solve: 970 [?]
Skill Endorsements: 41 [?]
Team Colleague
 
1
 

> for(int i=2; i<=((int)sqrt((double)n)); i++)
And it would be so much quicker if you didn't call sqrt() on every iteration of the loop!
n is constant (in this function), so it's root is constant also. Calculate it once and store in another variable to compare against.

Also, since 2 is prime, that's an easy case to get rid of, and you can start at 3.

Also, if you start at 3, then you can do i+=2 to only check all the odd numbers from there on.

Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 

Dude543 yes I like that very much.

Salem good feedback.


So system("PAUSE") then, what gives ? I havn't found anything negative on the internet yet.

Ok I've found it:

http://www.gidnetwork.com/b-61.html

Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 

Actually dud543 I think this is wrong: || n % 2 == 0) That would return false for 2 which is prime.

Member Avatar
dude543
Light Poster
26 posts since Apr 2006
Reputation Points: 2 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Well. I also think that it is wrong.
But poor me, does'nt know wheter 0,1,2 are prime.
I know that prime will divide by himself and one only.
I Guess you are right.
Anyway. is there someway for me to edit the post ?

Member Avatar
hollystyles
Veteran Poster
1,179 posts since Feb 2005
Reputation Points: 113 [?]
Q&As Helped to Solve: 78 [?]
Skill Endorsements: 0 [?]
 
0
 

you can't edit a post more than 30 minutes after you posted in this forum.

0 and 1 are not prime. Yes 1 is divisible by 1 and itself, but that's the same thing it's only one factor not two factors so it's not prime.

2 is a special case, it is the only even number that is a prime.

Member Avatar
Bench
Posting Pro
575 posts since Feb 2006
Reputation Points: 212 [?]
Q&As Helped to Solve: 64 [?]
Skill Endorsements: 0 [?]
 
0
 

I wouldn't call 2 a special case - it fits the general description perfectly; A number evenly divisible only by 1 and itself. :)

You
Post:
Start New Discussion
Tags Related to this Article