Introduction to Programming in C

Index   |   Using VC++
 
Introduction
Basic Output
Variables
Conditionals
Loops
Example 1
More on Conditionals
Further Exploration
9 Algorithm Design
10 Arrays
 
< Previous

Algorithm Design

Next >

As programming projects get more complicated, it becomes worthwhile to plan before you start coding. Start by developing a plan, then implement and test it.

Problem-solving phase:

  1. Analyze -- understand and define the problem; ask questions, state assumptions.
  2. Develop an algorithm -- determine the steps necessary to solve the problem; use scratch paper.
  3. Test -- follow the exact steps to make sure that the algorithm works. Try specific cases and see how your algorithm reacts.

Definition

algorithm
A step-by-step procedure for solving a problem.

Implementation phase:

  1. Write code -- translate the algorithm into a programming language.
  2. Test -- have the computer follow the steps (execute the program).
  3. Debug -- check the results and make corrections until the answers are correct.
  4. Use the program.

Example

Assignment: for a given number of cents, print the number of quarters, dimes, nickels, and pennies needed to reach that value (with minimal coins).

  • Think about how you would do it in real life.
    • Which coin do you start with?
    • How do you know how many you need?
    • How do you figure out how much money is left after that coin?
  • Use scratch paper to organize your thoughts; list the steps you will need to perform.
  • Brainstorm with a friend if you like!
  • Create a new project.
  • Work in stages, for example just working on calculating and printing the result for the first coin. Get that part compiling and working correctly, then move on to the next coin.
  • Think about interesting test cases, e.g. results that don't need any of a specific coin. On paper, list the things you want to try, and what you expect the answer to be for each.
  • Test your program, and correct it as necessary.

Exercises

Here are some other ideas for programs you can write:

  • Modify the "count to 100 by 5's" program to show 5 to 50 on one line and 55 to 100 on the next line.
  • Write a new program to print the squares of numbers from 1 to 10, inclusive.
  • Write a new program to input 5 numbers and print their average.
  • Write a new program to input 5 numbers and print the largest value. Make sure that it works correctly if you enter all negative numbers!
  • Write a new program to input numbers until the user enters 0, and then print the average of all the numbers, not including the 0.
  • Write a new program to show the Fibonacci numbers less than 100. The Fibonacci sequence starts with two ones and each number is the sum of the two numbers before it:
    1 1 2 3 5 8 13 21 ...
< Previous Next >