Programming in C

(Barry) #1
Arguments and Local Variables 123

program results to be displayed.These values, called arguments,greatly increase the useful-
ness and flexibility of a function. Unlike your printMessageroutine, which displays the
same message each time it is called, the printffunction displays whatever you tell it to
display.
You can define a function that accepts arguments. In Chapter 5, “Program Looping,”
you developed an assortment of programs for calculating triangular numbers. Here, you
define a function to generate a triangular number, called appropriately enough,
calculateTriangularNumber. As an argument to the function, you specify which trian-
gular number to calculate.The function then calculates the desired number and displays
the results at the terminal. Program 8.4 shows the function to accomplish this task and a
mainroutine to try it out.


Program 8.4 Calculating the nth Triangular Number


// Function to calculate the nth triangular number


#include <stdio.h>


void calculateTriangularNumber (int n)
{
int i, triangularNumber = 0;


for ( i = 1; i <= n; ++i )
triangularNumber += i;

printf ("Triangular number %i is %i\n", n, triangularNumber);
}


int main (void)
{
calculateTriangularNumber (10);
calculateTriangularNumber (20);
calculateTriangularNumber (50);


return 0;
}


Program 8.4 Output


Triangular number 10 is 55
Triangular number 20 is 210
Triangular number 50 is 1275

Free download pdf