Description
The purpose of this challenge is to various flow control structures. This challenge displays a menu and asks the user to perform various tasks.
Requirements
- Ask the user to enter two numbers, n1 and n2, using the int data type.
- Show a menu to the user with the following choices: a, b, c, q (Show the menu once and use a do-while statement to prompt the user for a menu command):
- a – Display all odd numbers between n1 and n2
- b – Display all prime numbers between n1 and n2. To test this part, it may be good to select larger numbers for n2. You will need to use a nested loop here.
- Recall from math that a number is prime if it is NOT evenly divisible (remainder of division is 0) by any number other than itself and 1.
- The outer loop will count from n1 to n2, keeping track of the number that you are currently testing for “prime-ness”. The inner loop will actually test if a number is evenly divisible by numbers smaller than it (e.g. 2 to number-1 where number is the number you are testing for “prime-ness”).
- The modulo operation (num1 % num2) will be useful here since it returns the remainder. If the remainder is ever 0, the number is not a prime so you can skip it and continue on to testing the next number.
- Display the number when it is a prime (e.g. the inner loop tested all possible factors and the remainder was never 0). You may find Boolean flags useful for tracking “prime-ness” in the inner loop.
- c – The sum of all integers between n1 and n2 inclusively
- q – Quit the program
- Make sure your switch statement contains a default statement to cover the case when the user selects an unsupported menu option
Sample Interaction / Output
Enter a number: 1 Enter a number: 10 a - Display all odd b - Display all prime c - Sum of numbers between 1 and 10 q - Quit Enter a command: f <Unknown command> Enter a command: a ALL ODD: 1 3 5 7 9 Enter a command: b ALL PRIME: 1 2 3 5 7 9 Enter a command: c SUM: 55 Enter a command: q
LEGEND
PROGRAM OUTPUT
USER INPUT
FROM INPUT
CATALOG ID: CPP-CHAL0001
Print Requirements