Programming in C

(Barry) #1

52 Chapter 5 Program Looping


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

return 0;
}

In Program 5.4 Output, the number typed in by the user (100) is set in bold type to
distinguish it from the output displayed by the program.

Program 5.4 Output
What triangular number do you want? 100
Triangular number 100 is 5050

According to the output, the number 100 was typed in by the user.The program then
proceeded to calculate the 100th triangular number and displayed the result of 5050 at
the terminal.The user could have instead typed in the number 10, or 30, if he desired to
calculate those particular triangular numbers.
The first printfstatement in Program 5.4 is used to prompt the user to type in a
number. Of course, it is always nice to remind the user what it is you want entered. After
the message is printed, the scanfroutine is called.The first argument to scanfis the
format string and is very similar to the format string used by printf. In this case, the
format string doesn’t tell the system what types of values are to be displayed but rather
what types of values are to be read in from the terminal. Like printf,the %icharacters
are used to specify an integer value.
The second argument to the scanfroutine specifies wherethe value that is typed in
by the user is to be stored.The &character before the variable numberis necessary in this
case. Don’t worry about its function here, though. Chapter 11, “Pointers,” discusses this
character, which is actually an operator, in great detail. Always remember to put the lead-
ing &in front of the variable name in the scanffunction call. If you forget, it causes
unpredictable results and might cause your program to terminate abnormally.
Given the preceding discussion, you can now see that the scanfcall from Program
5.4 specifies that an integer value is to be read from the terminal and stored in the vari-
able number.This value represents the particular triangular number that the user wants to
calculate.
After this number has been typed in (and the “Return” or “Enter” key on the key-
board pressed to signal that typing of the number is completed), the program then pro-
ceeds to calculate the requested triangular number.This is done in the same way as in
Program 5.2—the only difference being that instead of using 200 as the limit,numberis
used.
After the desired triangular number has been calculated, the results are displayed, and
execution of the program is then complete.

Program 5.4 Continued
Free download pdf