COMP2243 - Programming and Problem Solving

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Repetitions/Loops WhileLoop.java LoopWithCounter.java LoopWithSentinel.java LoopWithFlag.java SimpleInterest.java Factorial.java Fibnonacci.java PrimeNumber.java GCD.java PopulationGrowth.java ForLoop.java DoWhileLoop.java FileIO_Tickets.java FileIO_Salary.java NestedLoop.java



PrimeNumber Program


Description

A prime number is a positive integer that has exactly two positive integer factors, 1 and itself.

This program inputs a positive integer n and determines whether or not n is a prime number.

Associated Concepts:

while loop

Algorithm:

Declare variables and initialize the boolean variable flag to true

Input an integer n from the keyboard

Set the control variable i to 2

Use a while loop to check the control variable i (as long as i is less than or equal to n/2)

    If n is divisible by i

         Print a message to indicate n is not a prime number

         Set flag to false

         Break the loop

    Otherwise

        Increment i by 1

Once the loop is ended, if the flag is true

    Print a message to indicate that n is a prime number

Source Code



Sample Run



Video