Saturday, September 19, 2015

Lab 4x Hello Python - Calculate sum of integers from 1 to N (1+2+3+...+N) using loop (not recursive function)

def setup():
    numbers=10
    print("N = " ,numbers)
    cal_sum_1_to_N(numbers)
 
def cal_sum_1_to_N(n):
    sum=0
    while(n>0):
        if(n>1):
            print(n, "+",end="")
         
        else:
            print("1 = ",end="")
         
        sum=sum+n
        n=n-1
 
    print(sum)
    print("Sum of 1 to N = " ,sum)

setup()

No comments:

Post a Comment