Академический Документы
Профессиональный Документы
Культура Документы
COURSE NOTES
(PRACTICE PROBLEMS)
3. Prompt a user for input and keep adding the number until a negative
number is entered. Display the sum when the negative number is
entered.
To solve this problem, first we need to identify the variables that we need:
We need a variable for the user input (say num)
We need a variable to capture the sum (say sum)
Now we need to identify which type of control structure we need to use
(selection or repetition). Notice however that the question says we are to add
until a negative is entered. Thus we need to use a loop. In this case, we will
use the while loop.
NB: Generally, when we are using loops (or any control structure), we
initialize (set a starting value) the variables that will be used in the body
of the loop.
Now we are ready to write the pseudocode:
Declare num, sum as Integer
Initialize num, sum to zero
While num >= 0
Read num
sum = sum + num
Endwhile
PRINT sum
4. Check and display if a user entered number is a prime number. Prompt
user to try another number.
Again we need to determine the variables that we will need:
We need a variable for the user input (say userNum)
We need a variable to capture the user reply when they are prompted to
try another number (say option)
Typically when we want to prompt a user to try again, we use a do while loop.
Now, before we write our pseudocode, we need to determine how we would
check if a number is prime. Recall that a prime number has only two factors,
itself and one. Hence, if we can check that every between the number and one
is not a factor, we can conclude that the number is a prime number.
If isPrime = “yes”
PRINT “Your number is a prime number”
Else
PRINT “Your number is not a prime number”
Endif
PRINT “Enter ‘again’ to try another number or any other key to exit”
Read option