2.6k views
0 votes
Write definitions for the following two functions:______

A. SumN (n) returns the sum of the first n natural numbers.
B. SumNCubes (n) returns the sum of the cubes of the first n natural numbers.
Then use these functions in a program that prompts a user for an n and prints out the sum of the first n natural numbers and the sum of the cubes of the first n natural numbers.

User Arpan
by
5.0k points

1 Answer

3 votes

Answer:

Written in Python

def SumN(n):

total = 0

for i in range(1,n+1):

total = total + i

print("Total: ",total)

def SumNCubes(n):

total = 0

for i in range(1,n+1):

total = total + i**3

print("Cube: ",total)

n = int(input("User Input: "))

if n > 0:

SumN(n)

SumNCubes(n)

Step-by-step explanation:

The SumN function is defined here

def SumN(n):

This line initializes the total to 0

total = 0

The following iteration compute the required sum

for i in range(1,n+1):

total = total + i

This line outputs the calculated sum

print("Total: ",total)

The SumNCubes function is defined here

def SumNCubes(n):

This line initializes the total to 0

total = 0

The following iteration compute the required sum of cubes

for i in range(1,n+1):

total = total + i**3

This line outputs the calculated sum of cubes

print("Cube: ",total)

The main starts here; The first line prompts user for input

n = int(input("User Input: "))

The next line checks if input is greater than 0; If yes, the two defined functions are called

if n > 0:

SumN(n)

SumNCubes(n)

User Vldmrrdjcc
by
4.9k points