Thread: Newbie with trouble

  1. #1
    Unregistered
    Guest

    Exclamation Newbie with trouble

    I am stuck on this problem that I am trying to solve in this book tha I am reading on C programming. I am new to C and I could use some help to understand how to solve this ....thanks in advance.

    The problem has these requirements.
    1. Prompt user for a limit.
    2. start from 1.....limit.
    3. for each number test to see if it retruns a remainder
    from dividing by 2...3...4...5...until half of the number.
    4. if after any division ...it returns a 0 remainder....skip it
    5. otherwise print it as a prime number.

    This probably seems very simple to most of you but I have a headache from thinking about it for so long.

    I have so far :

    #include <stdio.h>

    int i,
    j,
    num;

    int main()
    {

    printf("Enter your Limit:");
    scanf("%d",&num);
    for(i=1; i<num;i++)
    {
    for(j = 1;j<(i/2);j++)
    {
    if((i % j) != 0)
    continue;
    }
    printf("\n%d is prime",i);
    }
    return(0);
    }

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    752
    Your code is basically right except for two points...
    3. for each number test to see if it retruns a remainder
    from dividing by 2...3...4...5...until half of the number
    This means you need to start the j loop with j = 2, not j = 1, since i%1 == 0 for all i.

    Also, your use of continue inside that for loop is going to cause problems... that is, it's going to make the loop do nothing. Here's what I suggest...
    Code:
    for(j = 2; j < (i / 2); j++)
    {
     if ((i % j) == 0) break; // Terminate loop if factor of j is found.
    }
    if (j == i / 2) // If loop was terminated due to 
                        //  j going beyong loop limits...
    printf("\n%d is prime",i);
    Continue does not terminate a loop. All it does is force the next iteration of a loop.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie function trouble
    By Swerve in forum C++ Programming
    Replies: 6
    Last Post: 03-04-2008, 04:33 AM
  2. Replies: 7
    Last Post: 05-25-2006, 12:51 PM
  3. Linux newbie - trouble with installing a IDE
    By geek@02 in forum Linux Programming
    Replies: 4
    Last Post: 09-10-2005, 10:09 AM
  4. qsort - newbie trouble with pointers
    By aze in forum C Programming
    Replies: 4
    Last Post: 03-10-2003, 03:38 PM
  5. newbie - copy constructor - trouble
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 02-19-2002, 09:56 PM