C++ Loops and File Handling: A Deep Dive

Classified in Computers

Written at on English with a size of 4.31 KB.

C++ Loops: While, Do-While, and For

While Loop Format

while (condition)
{
    statements(s);
}

How While Loop Works

If the condition is true, the statement(s) are evaluated again. If false, the loop is exited.

While Loop Example

int val = 5;
while (val >= 0)
{
    cout << val << " ";
    val = val - 1;
}

A while loop is a pretest loop (the condition is evaluated before the loop executes).

  • If the condition is initially false, the statement(s) in the body of the loop are never executed.
  • If the condition is initially true, the statement(s) in the body will continue to be executed until the condition becomes false.

The loop must contain code to allow the condition to eventually become false so the loop can be exited. Otherwise, you have an infinite loop. See the example below:

x = 5;
while (x > 0)
{
    cout << x;
}

Input Validation Example

cout << "Enter a number between 1-100 and I will guess it";
cin >> number;
while (number < 1 || number > 100)
{
    cout << "Number must be between 1 and 100. Re-enter your number";
    cin >> number;
}

Prefix and Postfix Modes

  • Prefix mode: ++val/--val increments/decrements the variable, then returns the new value of the variable.
  • Postfix mode: val++/val-- returns the old value, then increments or decrements the variable.

Do-While Loop

A do-while loop is a post-test loop (the condition is evaluated after the loop executes). It is always executed at least once.

Do-While Loop Format

do
{
    1 or more statements;
} while (condition);

Menu-Driven Program Example

do
{
    // Code to display menu and perform actions
    cout << "Another choice? (y/n)";
    cin >> choice;
} while (choice == 'Y' || choice == 'y');

For Loop Format

for (initialization; test; update)
{
    1 or more statements;
}

For Loop Example

int sum = 0, num;
for (num = 1; num <= 10; num++)
{
    sum += num;
    cout << "Sum of numbers 1 - 10 is " << sum << endl;
}

If the test is false the first time it's evaluated, the body of the loop won't be executed.

Deciding Which Loop to Use

  • While: Pretest loop (loop body may not be executed at all).
  • Do-while: Post-test loop (loop body will always be executed at least once).
  • For: Pretest loop (body may not be executed at all), has initialization and update code, is useful with counters or if the precise number of repetitions is known).

Nested Loops

A nested loop is a loop inside the body of another loop.

Nested Loop Example

for (row = 1; row <= 3; row++) // Outer loop
{
    for (col = 1; col <= 3; col++) // Inner loop
    {
        cout << row * col << endl;
    }
}

C++ File Handling

What is Needed to Use Files

  1. Include the fstream header file: #include
  2. Define a file stream object:
    • ifstream for input from a file. Example: ifstream inFile;
    • ofstream for output to a file. Example: ofstream outFile;
  3. Open the file:
    • inFile.open("name.txt");
    • outFile.open("name.txt");
  4. Use the file:
    • outFile << "Inventory report"; - Sends data to the file.
    • inFile >> partNum; - Copies data from the file to variables.
  5. Close the file:
    • inFile.close();
    • outFile.close();

Using Loops to Process Files Example

while (inFile >> score)
{
    sum += score;
}

File Open Errors

File open errors occur if the file doesn't exist, the filename is misspelled, or the file exists but it's in a different place.

if (inFile)
{
    // Process data from file
} else
{
    cout << "Error on file open";
}

Entradas relacionadas: