Write a pseudo code algorithm which will input a series of people's ages (as integers between 1 and 120 inclusive) and calculate the maximum and average age. The average age should be calculated as a real number. Your algorithm should continue to input age values until the user inputs a value of zero. This is a signal for the algorithm to stop inputting the age, and to then output the average and maximum ages. If the user enters an age that is invalid then your algorithm should continue to re-prompt the user until they enter a valid age. Your algorithm should make good use of sub modules. Note zero should not be included when determining the average or maximum age.
this is my practice question
i have come up with
main
FOR
age = inputAge <-prompt "enter age"
max = getMax <- age
sum = sum + age
average = getAverage <- sum, number of times input
END FOR
OUTPUT max, average
END MAIN
METHOD inputAge
IMPORT prompt
EXPORT age
INPUT age
WHILE age >= 120 AND age <= 0 DO
OUTPUT "enter valid age"
INPUT age
END WHILE
END
METHOD getMax
IMPORT age
EXPORT max
IF max < 0 THEN
max = age
END
METHOD getAverage
IMPORT sum, number of times input
EXPORT average
average = sum / number of times input
END
my problem is that im not quite sure how to input 1 to 120 and stop loop when 0 is input and getting number of times input so i can calculate the average. the for loop in the main is also a problem. i get what the question is asking but its just not getting together in my head. could i get help with this question?
Well, for starters, it would be far simpler to calculate the average after collecting all inputs and saving the biggest value until then as the maximum value. So, setting the sum and the max to 0 and creating a variable to count the number of inputs would be a nice start. I would do something like this:
main
max = 0
sum = 0
count = 0
WHILE true
age = inputAge <-prompt "enter age"
IF age == 0 THEN
BREAK
END IF
IF age > max THEN
max = age
END IF
sum = sum + age
count = count + 1
END WHILE
average = getAverage <- sum, count
IF count == 0 THEN
OUTPUT "There was no input"
ELSE
OUTPUT max, average
END IF
END MAIN
METHOD inputAge
IMPORT prompt
EXPORT age
INPUT age
WHILE age >= 120 AND age <= 0 DO
OUTPUT "enter valid age"
INPUT age
END WHILE
END
METHOD getAverage
IMPORT sum, number of times input
EXPORT average
average = sum / number of times input
END
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.