Before writing a program to solve a problem, you must have a thorough understanding of the problem and a carefully planned solution approach. Chapters 3 and 4 discuss developing structured computer programs. In Section 4.11, we summarize the structured programming techniques developed here and in Chapter 4.

Algorithms

The solution to any computing problem involves executing a series of actions in a specific order. An algorithm is a procedure for solving a problem in terms of:

  1. the actions to be executed, and
  2. the order in which to execute them

Pseudocode

Pseudocode is an informal artificial language similar to everyday English that helps you develop algorithms before converting them to structured C programs. It's convenient and user friendly, allowing you to think out a program before writing it.

Control Structures

Normally statements in a program execute one after the other in the order in which you write them. This is called sequential execution. As you'll soon see, various C statements enable you to specify that the next statement to execute may be other than the next one in sequence. This is called transfer of control.

The if Selection Statement

Selection statements choose among alternative courses of action. For example, suppose the passing grade on an exam is 60. The following pseudocode statement determines whether the condition “student’s grade is greater than or equal to 60” is true or false:

If student’s grade is greater than or equal to 60 
    Print “Passed”

If true, then “Passed” is printed, and the next pseudocode statement in order is “performed.” Remember that pseudocode isn’t a real programming language. If false, the printing is ignored, and the next pseudocode statement in order is performed. The preceding pseudocode is written in C as

if (grade >= 60) {
    puts("Passed");
}

Of course, you’ll also need to declare the int variable grade, but the C if statement code corresponds closely to the pseudocode. This is one of the properties of pseudocode that makes it such a useful program-development tool.

The while Iteration Statement

An iteration statement (also called a repetition statement or loop) repeats an action while some condition remains true. The pseudocode statement

While there are more items on my shopping list 
    Purchase next item and cross it off my list

describes the iteration that occurs during a shopping trip. The condition “there are more items on my shopping list” may be true or false. If it’s true, the shopper performs the action “Purchase next item and cross it off my list” repeatedly while the condition remains true. Eventually, the condition will become false (when the last item on the shopping list has been purchased and crossed off the list). At this point, the iteration terminates, and the first pseudocode statement after the iteration statement “executes.”

Calculating the first power of 3 greater than 100

As a while statement example, consider a program segment that finds the first power of 3 larger than 100. The integer variable product is initialized to 3. When the following code segment finishes executing, product will contain the desired answer:

int product = 3;

while(product <= 100) {
    product = 3 * product;
}

The loop repeatedly multiplies product by 3, so it takes on the values 9, 27 and 81 successively. When product becomes 243, the condition product <= 100 becomes false, terminating the iteration—product’s final value is 243. Execution continues with the next statement after the while. An action in the while statement’s body must eventually cause the condition to become false; otherwise, the loop will never terminate—a logic error called an infinite loop. The statement(s) contained in a while iteration statement constitute its body, which may be a single statement or a compound statement.

Formulating Algorithms Case Study 1: Counter-Controlled Iteration

Consider the following problem statement:

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

The class average is the sum of the grades divided by the number of students. The algorithm to solve this problem must input the grades, then calculate and display the class average.

Pseudocode for the Class-Average Problem

Let’s use pseudocode to list the actions to execute and specify the order in which they should execute. We use counter-controlled iteration to input the grades one at a time. This technique uses a variable called a counter to specify the number of times a set of statements should execute. In this example, we know that ten students took a quiz, so we need to input 10 grades. Iteration terminates when the counter exceeds 10.

Set total to zero
Set grade counter to one

While grade counter is less than or equal to ten
    Input the next grade
    Add the grade into the total
    Add one to the grade counter

Set the class average to the total divided by ten
Print the class average

The C code implementation:

#include <stdio.h>

int main(void) {
    int total = 0; // Initialize total to zero
    int counter = 1; // Initialize grade counter to one

    while (counter <= 10) { // Loop 10 times
        printf("%s", "Enter Grade: "); // Prompt user
        int grade = 0; // Define grade variable
        scanf("%d", &grade); // Read grade from user
        total = total + grade; // Add grade to total
        counter = counter + 1; // Increment counter
    }

    int average = total / 10; // Calculate average
    printf("Class average is %d\n", average); // Print average
    return 0;
}

Formulating Algorithms with Top-Down, Stepwise Refinement Case Study 2: Sentinel-Controlled Iteration

Consider the following problem:

Develop a class-averaging program that will process an arbitrary number of grades each time the program is run.

In the first class-average example, we knew there were 10 grades in advance. In this example, no indication is given of how many grades the user might input. The program must process an arbitrary number of grades. How can the program determine when to stop inputting grades? How will it know when to calculate and print the class average?

// fig03_04.c
// Class-average program with sentinel-controlled iteration.
#include <stdio.h>

// function main begins program execution
int main(void) {
   // initialization phase
   int total = 0; // initialize total
   int counter = 0; // initialize loop counter

   // processing phase
   // get first grade from user
   printf("%s", "Enter grade, -1 to end: "); // prompt for input
   int grade = 0; // grade value
   scanf("%d", &grade); // read grade from user                 

   // loop while sentinel value not yet read from user
   while (grade != -1) {
      total = total + grade; // add grade to total
      counter = counter + 1; // increment counter

      // get next grade from user
      printf("%s", "Enter grade, -1 to end: "); // prompt for input
      scanf("%d", &grade); // read next grade                  
   } // end while

   // termination phase
   // if user entered at least one grade
   if (counter != 0) {

      // calculate average of all grades entered
      double average = (double) total / counter; // avoid truncation

      // display average with two digits of precision
      printf("Class average is %.2f\n", average);
   } // end if   
   else { // if no grades were entered, output message
      puts("No grades were entered");
   } // end else
} // end function main

Secure C Programming