Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,303 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,482 people online right now. Registration is fast and FREE... Join Now!




Using loops to display prime numbers

 
Reply to this topicStart new topic

Using loops to display prime numbers, Using loops to show prime numbers

kylera
14 Oct, 2008 - 11:17 PM
Post #1

New D.I.C Head
*

Joined: 14 Oct, 2008
Posts: 2

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).

CODE

#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: 14 Oct, 2008 - 11:18 PM
User is offlineProfile CardPM
+Quote Post

AmitTheInfinity
RE: Using Loops To Display Prime Numbers
14 Oct, 2008 - 11:37 PM
Post #2

C Surfing ∞
Group Icon

Joined: 25 Jan, 2007
Posts: 1,025



Thanked: 35 times
Dream Kudos: 125
My Contributions
There were very small mistakes in your code. See the code for my comments.

cpp


#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;
}



I hope this will help you. smile.gif
User is online!Profile CardPM
+Quote Post

kylera
RE: Using Loops To Display Prime Numbers
15 Oct, 2008 - 12:10 AM
Post #3

New D.I.C Head
*

Joined: 14 Oct, 2008
Posts: 2

Mother of God...small mistakes blow things to high heaven. Much much thanks!
User is offlineProfile CardPM
+Quote Post

David W
RE: Using Loops To Display Prime Numbers
15 Oct, 2008 - 01:36 AM
Post #4

D.I.C Regular
Group Icon

Joined: 20 Sep, 2008
Posts: 315



Thanked: 16 times
Dream Kudos: 275
My Contributions
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


User is offlineProfile CardPM
+Quote Post

David W
RE: Using Loops To Display Prime Numbers
15 Oct, 2008 - 03:41 AM
Post #5

D.I.C Regular
Group Icon

Joined: 20 Sep, 2008
Posts: 315



Thanked: 16 times
Dream Kudos: 275
My Contributions
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 .... biggrin.gif

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

CODE
/*  
    '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 Oct, 2008 - 11:10 AM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/2/08 06:27AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month