Python Program to Print Triangular Number up to Given Number Using While Loop

In this tutorial, we are going to discuss how to print all triangular number up to given number of n in python uisng while loop.

In mathematics, triangular is important concept.

Triangular numbers are the numbers that can be represented in the form of the sum of consecutive integers starting from 1.

In this program, we will generate all triangular up to a given number using while loops in Python.

Code to generate triangular numbers using while loop.

Simple Code:

n = int(input("Enter the value of n: "))
i = 1
sum = 0
while i <= n:
    sum += i
    print(sum, end=" ")
    i += 1

Output:

Enter the value of n: 5
1 3 6 10 15 

Code with Comments:

# take input from user for the value of n
n = int(input("Enter the value of n: "))

# initialize i to 1 and sum to 0
i = 1
sum = 0

# use a while loop to generate triangular numbers up to n
while i <= n:
    # add i to the sum
    sum += i
    # print the current value of the sum
    print(sum, end=" ")
    # increment i by 1
    i += 1

Explanation:

We first take input from the user for the value of n, up to which we want to generate triangular numbers.

We initialize i to 1 and sum to 0.

Then, we use a while loop to generate triangular numbers up to n.

In each iteration of the loop, we add i to the sum and print the current value of the sum.

We also increment i by 1 in each iteration of the loop.


Discover more from Python Mania

Subscribe to get the latest posts sent to your email.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Related Articles:

Recent Articles:

0
Would love your thoughts, please comment.x
()
x

Discover more from Python Mania

Subscribe now to keep reading and get access to the full archive.

Continue reading