Click here to Skip to main content
15,031,941 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have wrote a simple program to determine a prime number using a do while loop but am having trouble getting the correct output. Any help would be appreciated. I have a feeling it is something to do with the updates in my loops?

What I have tried:

C#
public class DoWhile{
    public static void main(String[]args)
    {
        int num=13;
        do
        {
            System.out.println(num + " is a prime number");
            num++;
        }
        while(num%2==1);
        
        if(num%2==1)
        {
        do
        { 
            System.out.println(num+ " is NOT a prime number");
            num++;
        }
        while (num%2==0);
    }
}
}
Posted
Updated 11-May-21 9:17am

No, it has to do with that not being a prime number detector algorithm, or even close.
Have a look at this: Sieve of Eratosthenes - Wikipedia[^] and consider trying to implement that.
   
No, with some corrections this program will tell if a number is odd or even.
This how your program should look:
Java
public class DoWhile{
    public static void main(String[]args)
    {
        int num=13;
        int last=100;
        do
        {
            if(IsPrime(num))
            {
                System.out.println(num + " is a prime number");

            }
            else
            {
                System.out.println(num+ " is NOT a prime number");

            }
            num++;
        }
        while(num <==last);
    }
}

You need to define the function IsPrime that will check if a number is prime or not.

If you have difficulties to understand what you program do, use the debugger, it will show you.

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900