In: Computer Science
I have to write an initial algorithm and a refined algorithm for the following problem:
Display the square of numbers from 0 to some user inputted value. For example if the user enters 3 then the program will need to display the square of 0, 1, 2 and 3. Must use a counter loop. Must use 2 methods. One method that gets the number from the user and returns it. A second method is passed that number as a parameter then the method display the squares. So all main does is call the methods and gets the data from one method and passes it to the other.
I'm also suppose to use modules for this. I guess I'm just not sure how to even begin writing the initial algorithm down to the refined algorithm. Any help or explanation would be much appreciated, thank you!
This is what I have written so far:
Initial Algorithm:
Declare variables
Get user input
Set counter equal to 0
Initiate counter loop
Get squares of all numbers up until user’s input number
Display squares
Data Requirements:(I/O)
Input – user number
Output – square of numbers up until user’s input number
Formulas:
User input + user input * user input
Refined Algorithm:
Module Main()
Declare int userNumber
Get the user number
Display “Enter a number”
Input userNumber
Calculate square of numbers up to user input number
Call CalculateSquares
Calculate square of user input one number at a time
Call CalculateSquare
End Module Main
Module CalculateSquares
Counter = 1
While counter <= userNumber
End Module CalculateSquares
Module CalculateSquare
The initial algorithm what you have mentioned is seems to be correct.
The refined algorithm is as follows:
Module Main()
DECLARE int num
SET num = call getUserInput()
call computeSquares(num)
End Module
Module getUserInput()
Display "Enter a number"
Input number
return number
End Module
Module computeSquares(int inputNumber)
DECLARE int counter
SET counter = 0
WHILE counter <= inputNumber
call computeIndividualSquare(counter)
INCREMENT counter
ENDWHILE
End Module
Module computeIndividualSquare(int counter)
Display "The square of "+counter+" is "+(counter*counter)
End Module
Explanation:
There are four functions in the refined algorithm: