The code is written using Python language as it is one of the programming languages introduced by the Edhesive courses.
Answer (Question 1):
- num = int(input("Input an integer: "))
- for i in range(1, 4):
- print(num + i)
Explanation (Question 1):
<u>Line 1 : </u>
Prompt user for input an integer. In Python we can easily use <em>input </em>method to ask user for an input.
However the default data type of the input is a string and therefore we need to enclose our input value within <em>int()</em> to convert the value from string to integer.
<u>Line 3 - 4:</u>
Create a for-loop to loop though the code in Line 4 for three times using the <em>range() </em>function. The <em>range(1, 4) </em>will return a list of numbers, [1, 2, 3] .
In each round of the loops, one number from the list will be taken sequentially and total up with the input number, num and display using <em>print()</em> function.
Answer (Question 2):
- counter = 3
- sum = 0
- while (counter > 0):
- num = float(input("Enter a decimal number: "))
- sum += num
- counter = counter - 1
- print("The sum is " + str(sum))
Explanation (Question 2):
<u>Line 1 - 2 :</u>
Create a <em>counter</em> variable and a <em>sum</em> variable and initialize them with 3 and 0, respectively.
<u>Line 4:</u>
Create a <em>while </em>loop and set a condition while counter is bigger than zero, the loop should keep running the code from Line 5-7.
<u>Line 5:</u>
Use <em>input</em> function again to prompt user for a decimal number. This time we need to use<em> float </em>function to convert the input value from string to decimal data type.
<u>Line 6:</u>
Every time when a decimal number is input, the number is added to the <em>sum</em> variable.
<u>Line 7:</u>
Decrement the counter variable by 1. This step is important to ensure the while loop will only be repeated for three times and each loop will only accept one input value from user.
<u>Line 9</u>
Display the sum.