# Using loops to display prime numbers

Page 1 of 1

## 4 Replies - 25507 Views - Last Post: 15 October 2008 - 04:41 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=67644&amp;s=aebe73ed2e8787bc05b3a98b3c723609&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 kylera

• New D.I.C Head

Reputation: 0
• Posts: 8
• Joined: 15-October 08

# Using loops to display prime numbers

Posted 15 October 2008 - 12:17 AM

Hi, I have an assignment using C to write a program that will take a value greater than two and display all prime numbers between 2 and that value. I've gotten as far as compiling my code, which compiles just fine, but when I run it and type in a number, the whole thing goes haywire. Code is as follows:

Oh, and I'm explicitly forbidden to use concepts that haven't been learned in class yet (a friend suggested using custom functions, for example. We've only covered up to loops, scanf, printf and different data types. What you see is what's been more or less covered).

```#include <stdio.h>

void main()
{
int InputNumber = 0; // Create a variable to input a number.
int i, j, k = 0; // Create variables for looping.
int PreviousNumber = 0; // Create a variable that will act as numbers adding up to the input number.

printf("Input number greater than two >> ");
scanf("%d", InputNumber);

/** The following 'for' loop is supposed to take every single number between two and the given
and calculate to see whether it is a prime or not. **/
for(PreviousNumber = 2; PreviousNumber <= InputNumber; PreviousNumber++)
{
for(j = 2; j <= PreviousNumber; j++) // this loop is to bring every number between two and the divisor
{
if(PreviousNumber % j == 0 && j != PreviousNumber)
{
k++;
}
}
if(k == 0)
{
printf("%d ", PreviousNumber); // This prints the number if it's a prime, be it the given or something before it.
}
}
}

```

I hope the comments on the code explain things well enough. Much thanks in advance.

This post has been edited by kylera: 15 October 2008 - 12:18 AM

Is This A Good Question/Topic? 0

## Replies To: Using loops to display prime numbers

### #2 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

## Re: Using loops to display prime numbers

Posted 15 October 2008 - 12:37 AM

There were very small mistakes in your code. See the code for my comments.

```#include <stdio.h>

int main()
{
int InputNumber = 0; // Create a variable to input a number.
int i, j, k = 0; // Create variables for looping.
int PreviousNumber = 0; // Create a variable that will act as numbers adding up to the input number.

printf("Input number greater than two >> ");
scanf("%d", &InputNumber); // You forgot ampersand there.

/** The following 'for' loop is supposed to take every single number between two
and calculate to see whether it is a prime or not. **/
for(PreviousNumber = 2; PreviousNumber <= InputNumber; PreviousNumber++)
{
//the number is prime if it is not divisible by any number except 1 and the number itself. so loop should be from 2 till number-1
//so condition is j<PreviousNumber and not j<=PreviousNumber
for(j = 2; j < PreviousNumber; j++) // this loop is to bring every number between two and the divisor
{
if(PreviousNumber % j == 0)
{
k++;
}
}
if(k == 0)
{
printf("%d ", PreviousNumber); // This prints the number if it's a prime, be it the given or something before it.
}
k=0; // always reset your check flags before going into new iteration.
}
getch();
return 0;
}

```

### #3 kylera

• New D.I.C Head

Reputation: 0
• Posts: 8
• Joined: 15-October 08

## Re: Using loops to display prime numbers

Posted 15 October 2008 - 01:10 AM

Mother of God...small mistakes blow things to high heaven. Much much thanks!

### #4 David W

• DIC supporter

Reputation: 298
• Posts: 1,839
• Joined: 20-September 08

## Re: Using loops to display prime numbers

Posted 15 October 2008 - 02:36 AM

Quote

.small mistakes blow things to high heaven. Much much thanks!

Programming may teach one ... that often ... there exits a very vital importance to each 'jot or tittle' ...

We must be exact in some things.

For example, you said 'Mother of God' ... but God has no mother or father. He is both father and mother and became big brother freely to all who accept His provided Salvation offered freely, but at GREAT personal COST, by Yeshua (Jesus), His first born ... and much beloved ... and only begotten Son.

Shalom,

David

### #5 David W

• DIC supporter

Reputation: 298
• Posts: 1,839
• Joined: 20-September 08

## Re: Using loops to display prime numbers

Posted 15 October 2008 - 04:41 AM

See this re-worked example. The goal was to more optimize the code and show some crash proofing, data validation, etc. ... for you to keep for future reference if needed ....

First you get the code working and tested out with some real test inputs ...
Then you look and see if some things can be 'optimized' a little (if you like.)

Here, one can skip over all even numbers, since we know in advance that they are not 'prime' ...

(They are other things that can be done to improve the code .... One only needs to divide by divisors up to (about?) the square root of the top number, for example ... Code can be very personal at times. Clear code is preferred by many, to tricky code, if the time gained is not really a big deal.)

One could simply test for all divisors in a loop ... but once we have established that a number is not prime, there is no further need to feed it test divisors, and we may then 'break' out of that loop.

Shalom,

David

``` /*
'C' all primes greater than 2,
up to, and including a 'top'
number that the user inputs.

The user may ask for another
'top' number to test repeatedly ...

A careful choice of variable names
may also assist solving a problem .
*/

#include <stdio.h>

void showPrimesUpTo( int num );

int main()
{
int c, max; /* 'c' is used as a character 'scratch' pad here */
for(;;) /* loop for ever ... until break or exit or return */
{
printf("Input 'top prime' number to test (greater than 1) : ");
scanf("%d", &max);
while( (c=getchar()) != '\n' ); /* 'flush' stdin buffer */

if (max < 2)
{
printf( "\nIs %d greater than 1 ?\n\n", max  );
continue; /* from top of the for loop ... */
}

printf( "\nPrimes are 1 2 ...\n" );
showPrimesUpTo( max );
printf("\nMore y/n ? ");
c=getchar();
if ( c=='n' || c=='N' ) return 0;
while( (c=getchar()) != '\n' ); /* 'flush' stdin buffer */
}
}

void showPrimesUpTo( int topNum )
{
/*
A number IS 'prime' if it IS divisible by ONLY 1 and the
number ITSELF. Some times we may go like this { 1, 2, 3, 5, 7, 11 ... }
(So here ... NO need to divide by 1, 2, or self  ...we need ONLY
to check ODD numbers beyond 2 to see if they divide with NO remainder ?
*/

/* 'j' is used as a counter, 'k' is used as a flag */
int testNum, i=0, j, k; /* i is used to limit numbers printed on a line */

/* only NEED to test ODD numbers; All EVEN beyond 2 are NOT prime. */
for(testNum = 3; testNum <= topNum; testNum += 2)
{
/* always 're-set' or 'initial' flags before each new iteration */
k=0;

/* this loop is to try every ODD number from 3 up to top as a divisor */
for(j = 3; j < testNum; j += 2)
{
if(testNum % j == 0)
{
/* Set k ... We have a divisor and testNum is NOT a prime. */
k=1;
break; /* So can EXIT INNER 'for loop' right NOW. */
}
}

/*  When we reach hear, if k==0, then that 'testNum' was a prime. */
if(k == 0)
{
printf("%4d ", testNum);
if( ++i == 15 ) { i=0; printf("\n"); }

}
// end of inner 'trial divisor' loop

} // end of outer 'for testNum ...' loop

}
```

This post has been edited by David W: 15 October 2008 - 12:10 PM