C++ while Loop

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What fundamental characteristic defines a loop in programming?

  • It's a section of code that executes only once.
  • It's a function that always returns a value.
  • It's a part of a program that has the potential to execute more than one time. (correct)
  • It's a conditional statement that can only be true or false.

A while loop is categorized as which type of loop?

  • Pretest loop (correct)
  • End test loop
  • Midtest loop
  • Posttest loop

In a while loop, what happens if the condition is initially false?

  • The loop executes once, then terminates.
  • The program throws an exception.
  • The loop is skipped entirely, and the program continues with the next statement after the loop. (correct)
  • The loop becomes an infinite loop.

Which of the following is a potential consequence of a missing update expression in a while loop?

<p>The loop may become an infinite loop if the condition never becomes false. (D)</p> Signup and view all the answers

What is the primary purpose of using a while loop for input validation?

<p>To ensure the user enters valid data before proceeding with the program. (C)</p> Signup and view all the answers

During input validation using a while loop, under what condition should the loop's body (containing the error message and re-prompt) be executed?

<p>When the entered data is not valid. (A)</p> Signup and view all the answers

Given the variable int count = 5;, what is the value of count after executing count++;?

<p>6 (A)</p> Signup and view all the answers

Given the variable int num = 10;, what is the value of num after executing --num;?

<p>9 (B)</p> Signup and view all the answers

What is the key difference between prefix and postfix increment/decrement operators in C++?

<p>Prefix operators modify the variable before its value is used in the expression; postfix operators modify after. (D)</p> Signup and view all the answers

What is a counter variable primarily used for within a loop?

<p>To count the number of times the loop iterates. (A)</p> Signup and view all the answers

When must a counter variable be initialized?

<p>Before entering the loop. (D)</p> Signup and view all the answers

What is a running total?

<p>An accumulated sum of numbers from each iteration of a loop. (B)</p> Signup and view all the answers

What is the role of an accumulator variable?

<p>To store a running total. (D)</p> Signup and view all the answers

What is a sentinel value used for in a loop?

<p>To mark the end of the loop. (D)</p> Signup and view all the answers

What is a critical characteristic of a sentinel value?

<p>It must be a value that cannot be confused with valid data. (B)</p> Signup and view all the answers

Which loop type is guaranteed to execute its loop body at least once?

<p><code>do-while</code> loop (B)</p> Signup and view all the answers

What is the correct syntax for a do-while loop in C++?

<p><code>do { // statements } while (condition);</code> (C)</p> Signup and view all the answers

What header file is required to use the toupper() and tolower() functions in C++?

<p><code>cctype</code> (A)</p> Signup and view all the answers

You have a menu-driven program that should continue running until the user enters 'N' or 'n' to quit. Which loop structure is MOST suitable for this scenario?

<p><code>do-while</code> loop (B)</p> Signup and view all the answers

What are the three expressions inside the parentheses of for loop, and in what order should they appear?

<p>Initialization, condition, update (C)</p> Signup and view all the answers

In a for loop, when is the initialization expression executed?

<p>Before the first iteration. (D)</p> Signup and view all the answers

Inside a for loop, what is the purpose of the 'test' expression?

<p>To determine whether to execute another iteration of the loop. (B)</p> Signup and view all the answers

Which of the following best describes the purpose of the update expression in a for loop?

<p>It is used to modify the loop counter variable after each iteration. (C)</p> Signup and view all the answers

When should a for loop be preferred over a while loop?

<p>When the initialization, condition, and update steps are closely related. (A)</p> Signup and view all the answers

What happens if the test condition in a for loop is false the first time it is evaluated?

<p>The loop is skipped entirely. (A)</p> Signup and view all the answers

In a for loop, can the loop variable be declared within the initialization expression?

<p>Yes, and the variable's scope is limited to the loop. (D)</p> Signup and view all the answers

What distinguishes a nested loop?

<p>It's a loop that contains another loop within its body. (D)</p> Signup and view all the answers

In a nested loop scenario, how many times does the inner loop typically execute for each iteration of the outer loop?

<p>Until its condition is met, potentially multiple times. (C)</p> Signup and view all the answers

What does the break statement do in a loop?

<p>It terminates the loop entirely. (C)</p> Signup and view all the answers

If a break statement is located within an inner loop of a nested loop structure, what is its effect?

<p>It terminates only the inner loop, and the program continues with the outer loop. (A)</p> Signup and view all the answers

What is the purpose of the continue statement in a loop?

<p>To skip the remaining statements in the current iteration and proceed to the next iteration. (B)</p> Signup and view all the answers

If a continue statement is executed in a for loop, what happens next?

<p>The loop's update expression is executed, and then the test condition is evaluated. (B)</p> Signup and view all the answers

What is a text file?

<p>A file containing information encoded as text, such as letters, digits, and punctuation. (B)</p> Signup and view all the answers

What is the primary difference between sequential access and random (direct) access in file handling?

<p>Random access allows accessing any piece of data directly, while sequential access requires accessing data in order. (C)</p> Signup and view all the answers

To use file input/output in C++, which header file(s) must be included?

<p><code>fstream</code> (C)</p> Signup and view all the answers

What is the purpose of the open() member function when working with files in C++?

<p>To associate a file stream object with a physical file on the disk. (A)</p> Signup and view all the answers

What happens if you try to open an input file using ifstream and the specified file does not exist?

<p>The file stream object will be set to a false-like value. (A)</p> Signup and view all the answers

What steps can you take to ensure that your program robustly handles file open errors?

<p>Check the file stream object's state after attempting to open the file. (A)</p> Signup and view all the answers

When testing a program, why is the quality of the test data more important than its quantity?

<p>Well-chosen test cases can expose critical errors with minimal input. (B)</p> Signup and view all the answers

What is the primary requirement for a loop to avoid becoming an infinite loop?

<p>The loop must contain code that eventually makes the condition false. (D)</p> Signup and view all the answers

Which of the following statements about while loops is most accurate?

<p>The <code>while</code> loop evaluates its condition before executing the loop body. (A)</p> Signup and view all the answers

In the context of input validation with loops, what is the primary reason for using a loop?

<p>To repeatedly prompt the user until valid input is provided. (B)</p> Signup and view all the answers

Consider the code int x = 3; int y = x++;. After execution, what are the values of x and y?

<p><code>x</code> is 4, <code>y</code> is 3 (C)</p> Signup and view all the answers

What is the crucial difference in behavior between the prefix increment operator (++x) and the postfix increment operator (x++)?

<p>The prefix operator increments the variable before its value is used, while the postfix operator increments it after. (B)</p> Signup and view all the answers

In the context of loops, what is a counter variable typically used for?

<p>To count the number of iterations a loop has performed. (C)</p> Signup and view all the answers

Which of the following describes the best practice for initializing a counter variable?

<p>It must be initialized before the loop to ensure predictable behavior. (A)</p> Signup and view all the answers

What is the purpose of an accumulator variable in a loop?

<p>To keep a running total by accumulating values from each iteration. (A)</p> Signup and view all the answers

Why must a sentinel value be carefully chosen?

<p>To prevent it from being confused with a valid data value. (B)</p> Signup and view all the answers

Which characteristic distinguishes a do-while loop from a while loop?

<p>A <code>do-while</code> loop is a post-test loop, guaranteeing at least one execution, while a <code>while</code> loop is a pretest loop. (C)</p> Signup and view all the answers

Given a menu-driven program that takes numerical input and performs calculations until the user enters '0' to quit, what loop would be MOST appropriate?

<p>A <code>do-while</code> loop, to ensure the menu is displayed at least once. (B)</p> Signup and view all the answers

Consider the for loop: for (int i = 0; i < 10; i++). If the loop body does not modify i, what will happen?

<p>The loop will execute 10 times. (D)</p> Signup and view all the answers

Can the update expression in a for loop increment or decrement by values other than one?

<p>Yes, it can increment or decrement by any amount. (A)</p> Signup and view all the answers

In a nested loop structure, what is the relationship between the iterations of the inner loop and the outer loop?

<p>For each iteration of the outer loop, the inner loop executes all of its iterations. (D)</p> Signup and view all the answers

What is the primary purpose of the break statement within a loop?

<p>To terminate the loop prematurely. (A)</p> Signup and view all the answers

How does the continue statement alter the flow of control in a loop?

<p>It skips the remaining statements in the current iteration and proceeds to the next iteration. (C)</p> Signup and view all the answers

Which of the following best describes the structure of a text file?

<p>A file containing information encoded as text, such as letters, digits and punctuation. (D)</p> Signup and view all the answers

In file handling, what is the key advantage of random access over sequential access?

<p>Random access allows direct retrieval of any piece of data without reading preceding data. (C)</p> Signup and view all the answers

What condition must be met for the open() function to successfully open an input file using ifstream?

<p>The file must already exist. (B)</p> Signup and view all the answers

What is a while loop and give an example?

<p>A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. It continues to execute the block of code within its body as long as the condition remains true.</p> <p>#include <iostream> using namespace std;</p> <p>int main() { int counter = 0;</p> <p>while (counter &lt; 5) { cout &lt;&lt; &quot;Counter: &quot; &lt;&lt; counter &lt;&lt; endl; counter++; }</p> <p>cout &lt;&lt; &quot;Loop finished.&quot; &lt;&lt; endl; return 0; }</p> Signup and view all the answers

How does pretest and posttest loops work?

<p>A pretest and posttest loop runs if the condition is true</p> Signup and view all the answers

Why should loop body statements be indented?

<p>It add structure to the code</p> Signup and view all the answers

How to test if loops are valid?

<p>Use if/else statements</p> Signup and view all the answers

What are logical operators?

<p>And, or and not/&amp;&amp; , || , !</p> Signup and view all the answers

Give me an example of an increment and decrement and what does it mean?

<p>In C++, increment (++) increases a variable's value by 1, while decrement (--) decreases it by 1. For example, x++ increments x, and y-- decrements y</p> Signup and view all the answers

What is a running total?

<p>An accumulated sum of numbers from iterations of loop</p> Signup and view all the answers

What is a sentinel value?

<p>A special value used to signal the end of input or a loop</p> Signup and view all the answers

What is do-while loop?

<p>The loop is going to run while the condition is true. Once the condition stops it becomes false.</p> Signup and view all the answers

How can a do-while be used in a menu-driven program?

<p>Bring the user back to the menu to make another choice</p> Signup and view all the answers

The first thing you should ask a customer when designing a program?

<p>What do you want to see?</p> Signup and view all the answers

What particular loops can I use and why would I use them?

<p>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 (loop body may not be executed at all); has initialization and update code; is useful with counters or if precise number of iterations is known</p> Signup and view all the answers

Flashcards

What is a loop?

A part of a program that executes more than once.

What is a pretest loop?

A loop that checks its condition before execution.

Exiting a loop

The loop must have code to change the condition to false.

What is an infinite loop?

A loop that continues indefinitely due to an unchangeable condition.

Signup and view all the flashcards

What is a post-test loop?

A loop that checks its condition after each execution.

Signup and view all the flashcards

What are sentinels?

A control variable that stops the loop when it reaches a specific value.

Signup and view all the flashcards

What does increment mean?

Increases the value of a variable.

Signup and view all the flashcards

What does decrement mean?

Reduces the value of a variable.

Signup and view all the flashcards

What is prefix mode?

The operator is placed before the variable, affecting the variable's value first.

Signup and view all the flashcards

What is postfix mode?

The operator is placed after the variable, returning its current value first.

Signup and view all the flashcards

What is a counter?

A variable incremented/decremented each loop iteration for managing loop execution.

Signup and view all the flashcards

What is a running total?

An accumulated sum from iterations of a loop.

Signup and view all the flashcards

What is a nested loop?

A loop inside another loop.

Signup and view all the flashcards

What is the break statement?

A statement that terminates the current loop.

Signup and view all the flashcards

What is the continue statement?

A statement to skip to the next iteration.

Signup and view all the flashcards

Text file Definition

Contains info encoded as text, viewed with a text editor.

Signup and view all the flashcards

Binary file Definition

Contains binary data not encoded as text, is not for direct reading.

Signup and view all the flashcards

What is sequential access?

Reads data sequentially, from start to end.

Signup and view all the flashcards

What is random access?

Retrieves any piece of data directly.

Signup and view all the flashcards

What is the Read Position?

The location of the next piece of data in an input file.

Signup and view all the flashcards

while loop

The while loop executes as long as its condition is true.

Signup and view all the flashcards

do-while loop

do-while loop executes at least once.

Signup and view all the flashcards

for loop

The for loop is useful with counters.

Signup and view all the flashcards

Study Notes

Introduction to Loops: The while Loop

  • Loop represents a part of a program that can execute more than once.
  • The basic structure of while loop includes checking a condition; if it is true then a statement is run.
  • The format for a while loop is while (condition){ statement(s);}
  • If the loop contains only one statement, the curly braces {} can be omitted.

How while Loop Works

  • First the condition is evaluated; If true, the statement(s) are executed, and then the condition is evaluated again.
  • If the condition is false, the loop will exit.
  • A loop iteration is when the body of the loop is executed

while Loop Example

  • Example:
int val = 5;
while (val >= 0)
{
    cout << val << " ";
    val = val - 1;
}
  • The above produces the output: 5 4 3 2 1 0.
  • val is called a loop control variable.
  • while loop is a pretest loop and condition is evaluated before the loop executes.

Exiting The Loop

  • The loop must have code that allows the condition to eventually become false.
  • Otherwise, can result in an infinite loop, which does not stop.
  • Example:
x = 5;
while (x > 0)
  cout << x; // infinite loop because x is always > 0 is always true

Common Loop Errors

  • Don't put ; immediately after (condition)
  • The curly braces {} should not be forgotten.
 int numEntries = 1;
 while (numEntries <=3)
    cout << "Still working ... ";
    numEntries++; // not in the loop body
  • The = should not be used when == is required
while (numEntries = 3)   // always true
{
    cout << "Still working ... ";
    numEntries++;
}

while Loop Programming Style

  • The loop body statements should be indented
  • The braces{ and } should align with the loop header and placed ​​on lines by themselves.
  • The above conventions make the source code more understandable.

Using The while Loop for Input Validation

  • Loops are useful for validating user input data.
  • Prompt for and read data
  • Use a while loop tests if the data is valid.
  • It will enter the loop only if the data is not valid.
  • In the loop body, display an error message and asks the user to re-enter the data.
  • The loop is exited when the user inputs valid data.

Input Validation Loop Example

  • Example:
cout << "Enter a number (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;
}
//Code to use the valid number follows

Increment and Decrement Operators

  • The increment operator increases the value of a variable. I.e. val++; is the same as val = val + 1;
  • The decrement operator reduces the value of a variable. I.e. val--; is the same as val = val – 1;
  • The operators can be used in the prefix or postfix mode.

Prefix Mode

  • ++val and --val increment or decrement the variable, then return the new value of the variable.
  • The new value of the variable is used in other operations within the same statement

Prefix Mode Example

  • Example:
int x = 1, y = 1;
x = ++y; // y is incremented to 2, then 2 is assigned to x
cout <<  x<< " " << y; // Displays 2 2

x = --y;  // y is decremented to 1, then 1 is assigned to x
cout << x << " " << y; // Displays 1 1

Postfix Mode

  • val++ and val-- return the current value of the variable, then increment or decrement the variable
  • It is the returned current value of the variable that is used in any other operations within the same statement

Postfix Mode Example

  • Example:
int x = 1, y = 1;

x = y++;  // y++ returns a 1, The 1 is assigned to x and y is incremented to 2
cout << x << " " << y;       // Displays 1 2

 x = y--; // y-- returns a 2, The 2 is assigned to x and y is decremented to 1
cout << x << " " << y; // Displays 2 1

Increment & Decrement Notes

  • They can be used in arithmetic expressions; result = num1++ + --num2;
  • They must be applied to a variable, not an expression or a literal value; result = (num1 + num2)++; // Illegal
  • They can be used in relational expression, for example if (++num > limit)
  • Pre- and post-operations will cause different comparisons

Counters

  • A counter is a variable that is incremented or decremented each time a loop iterates.
  • Counters can control the loop execution.
  • They must be initialized before entering the loop.
  • They can be incremented/decremented when inside the loop or in the loop test.

Letting the User Control the Loop

  • Program can be written so that user input determines loop repetition
  • This can be applied when a program processes a list of items, and the user knows the number of items
  • The user is prompted before the loop is entered
  • User input is used here to control the number of loops

User Controls the Loop Example

  • Example:
int num, limit;

cout << "Table of squares\n";
cout << "How high to go? ";
cin >> limit;

cout << "\n\nnumber square\n";
num = 1;
while (num <= limit)
{
	cout << setw(5) << num << setw(6) << num*num << endl;
num++;
}

Keeping a Running Total

  • Represents an accumulated sum of numbers from loop iterations.
  • When finding a running total, can be found by using an accumulator
  • Example:
int sum = 0, num = 1;  // This represents the sum; known as the accumulator
while (num <= 10)  // the accumulator
{
sum += num;
num++;
}
cout << "Sum of numbers 1 – 10 is " << sum << endl;

Sentinels

  • A sentinel is a value in a list of values that indicates the end of the list.
  • Special value that cannot be confused with a valid value, -999 can be used for the test score value.
  • It is used to terminate the input when a user may not know how many values.

Sentinel Example

Example:

int total = 0;
cout << "Enter points earned "  << "(or -1 to finish): ";
cin >> points;

while (points != -1) // -1 is the sentinel
{
 total += points;
 cout << "Enter points earned: ";
 cin >> points;
}

The do-while Loop

  • The do-while loop is a post-test loop, and the condition is evaluated after the loop executes.
  • The format is do{ statement; } while (condition);
  • The {} are not required if the body contains a single statement.
  • There is a semi-colon ; after the (condition) is required

do-while Loop Notes

  • The loop body always executes at least once.
  • Execution continues until true and the loop is exited when condition is false.

do-while and Menu Driven Programs

  • do-while can be used in a menu-driven program to bring the user back to the menu to make another choice.
  • To simplify processing user input, use the toupper ('to uppercase') or tolower ('to lowercase') function. This allows you to check user input regardless of the case of the input. NOTE: cctype needs to be included
  • Example:
do{
   // code to display menu
   // and perform actions
   cout << "Another choice? (Y/N) ";
} while ((choice =='Y')||(choice=='y'));   //The condition could be written as(toupper(choice) == 'Y');or as (tolower(choice) == 'y');

The for Loop

  • The loop is a pretest loop that can execute zero or more times as needed.
  • Loop format represents the following
for( initialization; test; update )
{
    statement;
}

The for Loop Notes

  • If test is false the first time it is evaluated, the body of the loop will not be executed.
  • The update expression can increment or decrement by any amount.
  • Variables used in the initialization section should not be modified in the body of the loop.

For Loop Modifications

  • You can define variables in initialization code
  • Their scope is the for loop
  • Initialization and update code can contain more than one statement
  • Separate the statements with commas
  • Example:
for (int sum = 0, num = 1; num <= 10; num++)
    sum += num;

More for Loop Modifications

  • Can omit initialization if it’s already done
int sum = 0, num = 1;
for (; num <= 10; num++)
    sum += num;
- Can omit update if it’s done in loop body
for (sum = 0, num = 1; num <= 10;)
        sum += num++;
- Can omit the loop body if all of the work is done in the header

Deciding Each Loop to use

  • while: pretest loop (this loops body may not be executed).
  • do-while: post test loop (this loop body will always be executed at least once).
  • for: pretest loop (this loop body may not be executed); has initialization and update code; is most useful for counters or if the number can be precisely calculated.

Nested Loops

  • The nested loop is when one loop exists inside of another loop’s body
  • Example:
for (row = 1; row <= 3; row++)  //This is called the outer loop
{
    for (col = 1; col <= 3; col++)        //This is called the inner Inner loop
        {
         cout << row * col << endl;
        }
}

Notes on Nested Loops

  • The inner loop goes through all of its iterations for each iteration of the outer loop
  • The inner loop completes its iterations faster than the outer loop
  • The total number of iterations for inner loop is product of number of iterations of the two loops. In previous example, inner loop iterates 9 times in total.

Breaking Out of A Loop

  • Use it sparingly . It’s used to terminate the execution of a loop iteration, making the code harder to understand
  • When used in an inner loop, break terminates that loop only and returns to the outer loop

The continue Statement

  • The continue statement can go to the end of the loop and prepare for next iteration.
  • while and do-while loops go to the test expression and repeat if test is true.
  • for loop goes to the update step and then test, and repeats the loop if test condition is true.
  • Use continue sparingly - like break, it can make program logic hard to understand

Using Files for Data Storage

  • The file can be used instead so it doesn’t appear as computer screen output for your program.
  • Files are stored on secondary storage media such as a disk which allows data to be retained between program execution.
  • A file can be used instead of a keyboard for program input.

File Types

  • A text file has encoded letters such as text, digit and punctuation. A text editor such as notepad is able to view.
  • A binary file is binary that cannot be encoded as text, a regular text editor cannot read this.

File Access-Ways to Use the Data in a File

  • Sequential access starts reading the first piece of data and continues until last piece of data.
  • Random (direct) access to retrieve any piece of data directly, without the need to retrieve preceding data items

What is Needed to Use Files

  • First, one must include the ifstream or the ofstream header file.
  • Then, define a file stream object for either input/output.
  • The input reads data from a file using ifstream inFile;
  • The output writes data to a file usingofstream outFile;

Opening the File

  • Use the member function.
inFile.open("inventory.dat");
outFile.open("report.txt");
  • The files name may include its location on the disc, or the path. It must also include its extensions and the output file is created while an existing file, will be erased first. Also, the input file must exist for the open to work.

Using The File

  • To use the file: use output file object and << to send data to a file with outFile << "Inventory report";
  • Then use the input file object and >> to copy data from the file to variables with the example below:
    inFile >> partNum;
    inFile >> qtyInStock >> qty0n0rder;

Closing the File

  • Use the close member function
    inFile.close();
    outFile.close();
  • Ensure that you are not waiting for the operating system due to there being a limit to how many open files, and there is the cause for any missing data.

Input File - The Read Position

  • The next piece of data of an input file is known as the read position.
  • It is set to the first byte of the file.
  • As any data gets read, it advances

User- Specified Filenames

  • In a program, users can specify the inputs and outputs required; C++ before 11 required the C-string reprentation.
cout << "Which input file? ";
cin >> inputFileName;
inFile.open(inputFileName.c_str());
  • For anything past it, can just pass it to open without the function call.

Using the >> Operator to Test End of File

  • This operation indicates whether you get a true or false if the file has been successfully read.
  • The read expression fails(false) if you read passed the file and that should always be tested.
  • while (inFile >> score)` sum += score; for example;

File Open Errors

  • Errors can occur when a file is attempted to be opened due to the file not existing, there is a misspelled filename or in a separate location.
  • if (inFile) if the open succeeds, is set to true. and in else there is an error with code cout << "Error on file open\n";

Creating Good Test Data

  • If testing a specific program, data is more important than the quantity of the test. There should also be tests to show how different parts execute.
  • Normal ,invalid data and those that are at valid limits all need evaluations.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser