How to Design a Loop

How to Design a Loop with C++ Samples

What are the seven questions that must be answered to design a loop?

  • 1) What condition ends the loop?
  • 2) How should the condition be initialized?
  • 3) How should the condition be updated?
  • 4) What process is being repeated?
  • 5) How should the process be initialized?
  • 6) How should the process be updated?
  • 7) What is the state of the program on exiting the loop?

Designing the Flow of Control

  • What is the condition that ends the loop?
  • How should the condition be initialized?
  • How should the condition be updated?

The answer to the above questions depends on the type of termination conditions.

  • Count-Controlled Loops
  • Sentinel Controlled Loops
    For example: (Testing that a file opened correctly)
    int main()
    {
    ifstream inData;
    inData.open(“inData.dat”);    int sum, number;
    sum = 0;
    while (!inData) // if the inData is in fail state, sentinel loop condition
    {
    cout << “File open error!” << endl; // print error statement
    return 0;
    }
    }
  • EOF-Controlled Loops (End of File)
  • Flag Controlled Loops
    A Boolean flag variable is initialized to true or false and then updated when the condition changes.

Reference:
Dale, N. and Weems, C. (2010). Programming and Problem Solving with C++, 5th Edition, Jones and Bartlett Publishers, LLC, Sudbury, MA.

0
  Related Posts