n = int(input("Enter a number: "))
sum_numbers = 0
i = 1
while i <= n:
sum_numbers += i
i += 1
print(f"The sum of numbers from 1 to {n} is {sum_numbers}")
#source code --> clcoding.com
Code Explanation:
Take User Input:
n = int(input("Enter a number: "))
The program asks the user to enter a number n and converts it to an integer.
Initialize Variables:
sum_numbers = 0
i = 1
sum_numbers will store the total sum.
i is the counter variable, starting from 1.
Use a while Loop to Calculate the Sum:
while i <= n:
sum_numbers += i
i += 1
The loop runs as long as i is less than or equal to n.
In each iteration, i is added to sum_numbers, and i is incremented.
Print the Final Sum:
print(f"The sum of numbers from 1 to {n} is {sum_numbers}")
Displays the total sum.
0 Comments:
Post a Comment