Programming in C

(Barry) #1

64 Chapter 5 Program Looping



  1. A minus sign placed in front of a field width specification causes the field to be
    displayed left-justified. Substitute the following printfstatement for the correspon-
    ding statement in Program 5.2, run the program, and compare the outputs pro-
    duced by both programs.
    printf ("%-2i %i\n", n, triangularNumber);

  2. A decimal point before the field width specification in a printfstatement has a
    special purpose.Try to determine its purpose by typing in and running the follow-
    ing program. Experiment by typing in different values each time you are
    prompted.
    #include <stdio.h>


int main (void)
{
int dollars, cents, count;

for ( count = 1; count <= 10; ++count ) {
printf ("Enter dollars: ");
scanf ("%i", &dollars);
printf ("Enter cents: ");
scanf ("%i", ¢s);
printf ("$%i.%.2i\n\n", dollars, cents);
}
return 0;
}


  1. Program 5.5 allows the user to type in only five different numbers. Modify that
    program so that the user can type in the number of triangular numbers to be cal-
    culated.

  2. Rewrite Programs 5.2 through 5.5, replacing all uses of the forstatement by
    equivalent whilestatements. Run each program to verify that both versions are
    identical.

  3. What would happen if you typed a negative number into Program 5.8? Try it
    and see.

  4. Write a program that calculates the sum of the digits of an integer. For example,
    the sum of the digits of the number 2155 is 2 + 1 + 5 + 5 or 13.The program
    should accept any arbitrary integer typed in by the user.

Free download pdf