Programming in C

(Barry) #1
The forStatement 51

The primary change made to the printfstatement was the inclusion of a field width
specification.The characters %2itell the printfroutine that not only do you want to dis-
play the value of an integer at that particular point, but you also want the size of the
integer to be displayed to take up two columns in the display. Any integer that would
normally take up less than two columns (that is, the integers 0 through 9) are displayed
with a leadingspace.This is known as right justification.
Thus, by using a field width specification of %2i,you guarantee that at least two
columns are used for displaying the value of nand, therefore, you ensure that the values
of triangularNumberare lined up.
If the value that is to be displayed requires more columns than are specified by the
field width,printfsimply ignores the field width specification and uses as many
columns as are necessary to display the value.
Field width specifications can also be used for displaying values other than integers.
You will see some examples of this in programs that are coming up shortly.


Program Input


Program 5.2 calculates the 200th triangular number—and nothing more. If you want to
calculate the 50th or the 100th triangular number instead, you have to go back and
change the program so that the forloop is executed the correct number of times.You
also have to change the printfstatement to display the correct message.
An easier solution might be if you could somehow have the program ask which tri-
angular number you want to calculate.Then, after you provide your answer, the program
could calculate the desired triangular number for you. Such a solution can be effected in
C by using a routine called scanf.The scanfroutine is very similar in concept to the
printfroutine.Whereas the printfroutine is used to display values at the terminal, the
scanfroutine enables you to type values intothe program. Program 5.4 asks the user
which triangular number should be calculated, proceeds to calculate that number, and
then displays the results.


Program 5.4 Asking the User for Input


#include <stdio.h>


int main (void)
{
int n, number, triangularNumber;


printf ("What triangular number do you want? ");
scanf ("%i", &number);

triangularNumber = 0;

for ( n = 1; n <= number; ++n )
triangularNumber += n;
Free download pdf