Podcast
Questions and Answers
What fundamental characteristic defines a loop in programming?
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?
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?
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?
Which of the following is a potential consequence of a missing update expression in a while
loop?
What is the primary purpose of using a while
loop for input validation?
What is the primary purpose of using a while
loop for input validation?
During input validation using a while
loop, under what condition should the loop's body (containing the error message and re-prompt) be executed?
During input validation using a while
loop, under what condition should the loop's body (containing the error message and re-prompt) be executed?
Given the variable int count = 5;
, what is the value of count
after executing count++;
?
Given the variable int count = 5;
, what is the value of count
after executing count++;
?
Given the variable int num = 10;
, what is the value of num
after executing --num;
?
Given the variable int num = 10;
, what is the value of num
after executing --num;
?
What is the key difference between prefix and postfix increment/decrement operators in C++?
What is the key difference between prefix and postfix increment/decrement operators in C++?
What is a counter variable primarily used for within a loop?
What is a counter variable primarily used for within a loop?
When must a counter variable be initialized?
When must a counter variable be initialized?
What is a running total?
What is a running total?
What is the role of an accumulator variable?
What is the role of an accumulator variable?
What is a sentinel value used for in a loop?
What is a sentinel value used for in a loop?
What is a critical characteristic of a sentinel value?
What is a critical characteristic of a sentinel value?
Which loop type is guaranteed to execute its loop body at least once?
Which loop type is guaranteed to execute its loop body at least once?
What is the correct syntax for a do-while
loop in C++?
What is the correct syntax for a do-while
loop in C++?
What header file is required to use the toupper()
and tolower()
functions in C++?
What header file is required to use the toupper()
and tolower()
functions in C++?
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?
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?
What are the three expressions inside the parentheses of for
loop, and in what order should they appear?
What are the three expressions inside the parentheses of for
loop, and in what order should they appear?
In a for
loop, when is the initialization expression executed?
In a for
loop, when is the initialization expression executed?
Inside a for
loop, what is the purpose of the 'test' expression?
Inside a for
loop, what is the purpose of the 'test' expression?
Which of the following best describes the purpose of the update
expression in a for
loop?
Which of the following best describes the purpose of the update
expression in a for
loop?
When should a for
loop be preferred over a while
loop?
When should a for
loop be preferred over a while
loop?
What happens if the test condition in a for
loop is false the first time it is evaluated?
What happens if the test condition in a for
loop is false the first time it is evaluated?
In a for
loop, can the loop variable be declared within the initialization expression?
In a for
loop, can the loop variable be declared within the initialization expression?
What distinguishes a nested loop?
What distinguishes a nested loop?
In a nested loop scenario, how many times does the inner loop typically execute for each iteration of the outer loop?
In a nested loop scenario, how many times does the inner loop typically execute for each iteration of the outer loop?
What does the break
statement do in a loop?
What does the break
statement do in a loop?
If a break
statement is located within an inner loop of a nested loop structure, what is its effect?
If a break
statement is located within an inner loop of a nested loop structure, what is its effect?
What is the purpose of the continue
statement in a loop?
What is the purpose of the continue
statement in a loop?
If a continue
statement is executed in a for
loop, what happens next?
If a continue
statement is executed in a for
loop, what happens next?
What is a text file?
What is a text file?
What is the primary difference between sequential access and random (direct) access in file handling?
What is the primary difference between sequential access and random (direct) access in file handling?
To use file input/output in C++, which header file(s) must be included?
To use file input/output in C++, which header file(s) must be included?
What is the purpose of the open()
member function when working with files in C++?
What is the purpose of the open()
member function when working with files in C++?
What happens if you try to open an input file using ifstream
and the specified file does not exist?
What happens if you try to open an input file using ifstream
and the specified file does not exist?
What steps can you take to ensure that your program robustly handles file open errors?
What steps can you take to ensure that your program robustly handles file open errors?
When testing a program, why is the quality of the test data more important than its quantity?
When testing a program, why is the quality of the test data more important than its quantity?
What is the primary requirement for a loop to avoid becoming an infinite loop?
What is the primary requirement for a loop to avoid becoming an infinite loop?
Which of the following statements about while
loops is most accurate?
Which of the following statements about while
loops is most accurate?
In the context of input validation with loops, what is the primary reason for using a loop?
In the context of input validation with loops, what is the primary reason for using a loop?
Consider the code int x = 3; int y = x++;
. After execution, what are the values of x
and y
?
Consider the code int x = 3; int y = x++;
. After execution, what are the values of x
and y
?
What is the crucial difference in behavior between the prefix increment operator (++x
) and the postfix increment operator (x++
)?
What is the crucial difference in behavior between the prefix increment operator (++x
) and the postfix increment operator (x++
)?
In the context of loops, what is a counter variable typically used for?
In the context of loops, what is a counter variable typically used for?
Which of the following describes the best practice for initializing a counter variable?
Which of the following describes the best practice for initializing a counter variable?
What is the purpose of an accumulator variable in a loop?
What is the purpose of an accumulator variable in a loop?
Why must a sentinel value be carefully chosen?
Why must a sentinel value be carefully chosen?
Which characteristic distinguishes a do-while
loop from a while
loop?
Which characteristic distinguishes a do-while
loop from a while
loop?
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?
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?
Consider the for
loop: for (int i = 0; i < 10; i++)
. If the loop body does not modify i
, what will happen?
Consider the for
loop: for (int i = 0; i < 10; i++)
. If the loop body does not modify i
, what will happen?
Can the update expression in a for
loop increment or decrement by values other than one?
Can the update expression in a for
loop increment or decrement by values other than one?
In a nested loop structure, what is the relationship between the iterations of the inner loop and the outer loop?
In a nested loop structure, what is the relationship between the iterations of the inner loop and the outer loop?
What is the primary purpose of the break
statement within a loop?
What is the primary purpose of the break
statement within a loop?
How does the continue
statement alter the flow of control in a loop?
How does the continue
statement alter the flow of control in a loop?
Which of the following best describes the structure of a text file?
Which of the following best describes the structure of a text file?
In file handling, what is the key advantage of random access over sequential access?
In file handling, what is the key advantage of random access over sequential access?
What condition must be met for the open()
function to successfully open an input file using ifstream
?
What condition must be met for the open()
function to successfully open an input file using ifstream
?
What is a while loop and give an example?
What is a while loop and give an example?
How does pretest and posttest loops work?
How does pretest and posttest loops work?
Why should loop body statements be indented?
Why should loop body statements be indented?
How to test if loops are valid?
How to test if loops are valid?
What are logical operators?
What are logical operators?
Give me an example of an increment and decrement and what does it mean?
Give me an example of an increment and decrement and what does it mean?
What is a running total?
What is a running total?
What is a sentinel value?
What is a sentinel value?
What is do-while loop?
What is do-while loop?
How can a do-while be used in a menu-driven program?
How can a do-while be used in a menu-driven program?
The first thing you should ask a customer when designing a program?
The first thing you should ask a customer when designing a program?
What particular loops can I use and why would I use them?
What particular loops can I use and why would I use them?
Flashcards
What is a loop?
What is a loop?
A part of a program that executes more than once.
What is a pretest loop?
What is a pretest loop?
A loop that checks its condition before execution.
Exiting a loop
Exiting a loop
The loop must have code to change the condition to false.
What is an infinite loop?
What is an infinite loop?
Signup and view all the flashcards
What is a post-test loop?
What is a post-test loop?
Signup and view all the flashcards
What are sentinels?
What are sentinels?
Signup and view all the flashcards
What does increment mean?
What does increment mean?
Signup and view all the flashcards
What does decrement mean?
What does decrement mean?
Signup and view all the flashcards
What is prefix mode?
What is prefix mode?
Signup and view all the flashcards
What is postfix mode?
What is postfix mode?
Signup and view all the flashcards
What is a counter?
What is a counter?
Signup and view all the flashcards
What is a running total?
What is a running total?
Signup and view all the flashcards
What is a nested loop?
What is a nested loop?
Signup and view all the flashcards
What is the break statement?
What is the break statement?
Signup and view all the flashcards
What is the continue statement?
What is the continue statement?
Signup and view all the flashcards
Text file Definition
Text file Definition
Signup and view all the flashcards
Binary file Definition
Binary file Definition
Signup and view all the flashcards
What is sequential access?
What is sequential access?
Signup and view all the flashcards
What is random access?
What is random access?
Signup and view all the flashcards
What is the Read Position?
What is the Read Position?
Signup and view all the flashcards
while loop
while loop
Signup and view all the flashcards
do-while loop
do-while loop
Signup and view all the flashcards
for loop
for loop
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 iswhile (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; Iftrue
, thestatement(s)
are executed, and then thecondition
is evaluated again. - If the
condition
isfalse
, 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 andcondition
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++
andval--
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 thecondition
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') ortolower
('to lowercase') function. This allows you to check user input regardless of the case of the input. NOTE: cctype needs to be included
Menu-Driven Program Example
- 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
anddo-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 theofstream
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 using
ofstream 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 withoutFile << "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 inelse
there is an error with codecout << "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.