CS 111: Introduction to Computer Science

Triangular numbers

Your program should be called tri.py. Please submit it by copying it to your hand-in folder (Courses/f07/cs/cs111-00-f07/Student Work/yourusername/hand-in/).

The problem

If you add up the numbers 1 + 2 + 3 + ... + N, you get the Nth triangular number. The 5th triangular number, for example, is 1 + 2 + 3 + 4 + 5 = 15. (Why are these numbers called triangular? Think of the usual layout of 1 + 2 + 3 + 4 bowling pins.)

For this assignment, you will write a function called triangularNumber that accepts one integer parameter n and returns the nth triangular number.

A little more detail

Your program should contain both the triangularNumber function and some code for testing it. For example:

def triangularNumber(n): ''' This function returns the nth triangular number. ''' [your code goes here...] # This code tests the function print 'Here are the first ten triangular numbers:' for k in range(10): print triangularNumber(k + 1)

Once you write the body of triangularNumber, this test code should print:

Here are the first ten triangular numbers: 1 3 6 10 15 21 28 36 45 55

Note that there is a formula for computing triangular numbers that does not require the use of a loop. The point of this exercise, however, is to get you to practice writing functions and writing while-loops. So write the loop, not the fancy formula.