Here are the key points about using while loops in C++:
- A while loop repeats a statement or group of statements as long as a given condition is true.
- The general form of a while statement is:
while(condition) {
statement(s);
}
- The condition is evaluated first before executing the statement(s). The statement(s) will continue to execute as long as the condition remains true.
- Common types of while loops include:
- Counter-controlled - Used when the number of repetitions is known. A counter variable is incremented each time.
- Sentinel-controlled - Loop ends when a sentinel value is input.
- Flag-controlled - A boolean
Unlocking the Future of AI Agents with Large Language Models
ย
Object oriented programming17 control structures repetition statements
1. Object Oriented Programming: 17
Control Structure - Repetition
Prof Neeraj Bhargava
Vaibhav Khanna
Department of Computer Science
School of Engineering and Systems Sciences
Maharshi Dayanand Saraswati University Ajmer
2. 2
Why Is Repetition Needed?
โข Repetition allows you to efficiently use
variables
โข Can input, add, and average multiple numbers
using a limited number of variables
โข For example, to add five numbers:
โ Declare a variable for each number, input the numbers and
add the variables together
โ Create a loop that reads a number into a variable and adds
it to a variable that contains the sum of the numbers
3. 3
while Looping (Repetition) Structure
โข The general form of the while statement is:
while is a reserved word
โข Statement can be simple or compound
โข Expression acts as a decision maker and is
usually a logical expression
โข Statement is called the body of the loop
โข The parentheses are part of the syntax
4. 4
while Looping (Repetition) Structure
(continued)
โข Infinite loop: continues to execute endlessly
โ Avoided by including statements in loop body that
assure exit condition is eventually false
7. 7
Case 1: Counter-Controlled while
Loops
โข If you know exactly how many pieces of
data need to be read, the while loop
becomes a counter-controlled loop
8. 8
Case 2: Sentinel-Controlled while
Loops
โข Sentinel variable is tested in the condition and
loop ends when sentinel is encountered
9. 9
Case 3: Flag-Controlled while Loops
โข A flag-controlled while loop uses a bool
variable to control the loop
โข The flag-controlled while loop takes the
form:
10. 10
Case 4: EOF-Controlled while Loops
โข Use an EOF (End Of File)-controlled while
loop
โข The logical value returned by cin can
determine if the program has ended input
11. 11
eof Function
โข The function eof can determine the end
of file status
โข Like other I/O functions (get, ignore,
peek), eof is a member of data type
istream
โข The syntax for the function eof is:
where istreamVar is an input stream
variable, such as cin
12. 12
More on Expressions in while
Statements
โข The expression in a while statement can be
complex
โ For example:
while ((noOfGuesses < 5) && (!isGuessed))
{
โฆ
}