Repetition Control and IO ErrorsPlease note that the mate.docxsodhi3
Repetition Control and I/O Errors
Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material to required textbook.
INTRODUCTION
Repetition control (also called loop control or just looping) is widely used in programming to reduce the
amount of simple sequential statements. File I/O errors are encountered when inputs (both file input and
user input) are not what the program expected.
THE while LOOP
With all looping mechanisms we will have a block of code (enclosed in curly braces) within the loop.
This block of code is called the body of the loop. The intention of the loop is to execute the same block
of code repetitively. Looping obviates the need to write overlong programs with the same statements
executed sequentially.
Some caution must be exercised when using the while loop, and these cautions all relate to the use of the
loop control variable or condition. The while loop has the following form:
while (loop_control_condition_is_true) {
// the statements in the body of the loop go
// here
}
Note that there is no semicolon (;) at the end of the loop block and that the body of the loop is contained
within curly braces. Note further the loop control condition is always evaluated at the top of the loop.
The number of times that the loop body is executed is determined by the use of the loop control
condition, which is a logical expression that must evaluate to true or to false. The loop body may be
executed 0 or more times. For instance, the body of the loop is not executed at all if the loop control
condition evaluates to false when the loop is encountered in your program. Usually, however, we want
the loop to execute at least once. If so, that brings us to the first important caution:
If you want the loop body to execute at least once, you must ensure that the loop control condition
evaluates to true when the while loop is encountered in your program. For example:
bool cond = true;
...
while (cond) {
...
}
Once we are sure that the loop body will execute at least once, we have to pay attention to the second
caution:
If you want to avoid an infinite loop (where the loop is never exited) you must ensure that the loop
control condition is made to evaluate false at some point within the body of the loop. For example:
const int MAX = 1000;
int i = 0;
...
while (i < MAX) {
...
i++;
}
The loop control condition can be a simple logical expression, or it can be a fairly complicated one. For
instance:
while (((i < MAX) && cond) || keep_going) ...
Using the KISS principle (Keep It Simple, Smarty) it is always advisable to keep the loop control
condition as simple as possible.
Some programmers are purists about loop control conditions, and believe the while loop should never be
exited except at the top of the loop (when the loop control condition becomes false). C++, however, has
two statemen ...
Repetition Control and IO ErrorsPlease note that the mate.docxsodhi3
Repetition Control and I/O Errors
Please note that the material on this website is not intended to be exhaustive.
This is intended as a summary and supplementary material to required textbook.
INTRODUCTION
Repetition control (also called loop control or just looping) is widely used in programming to reduce the
amount of simple sequential statements. File I/O errors are encountered when inputs (both file input and
user input) are not what the program expected.
THE while LOOP
With all looping mechanisms we will have a block of code (enclosed in curly braces) within the loop.
This block of code is called the body of the loop. The intention of the loop is to execute the same block
of code repetitively. Looping obviates the need to write overlong programs with the same statements
executed sequentially.
Some caution must be exercised when using the while loop, and these cautions all relate to the use of the
loop control variable or condition. The while loop has the following form:
while (loop_control_condition_is_true) {
// the statements in the body of the loop go
// here
}
Note that there is no semicolon (;) at the end of the loop block and that the body of the loop is contained
within curly braces. Note further the loop control condition is always evaluated at the top of the loop.
The number of times that the loop body is executed is determined by the use of the loop control
condition, which is a logical expression that must evaluate to true or to false. The loop body may be
executed 0 or more times. For instance, the body of the loop is not executed at all if the loop control
condition evaluates to false when the loop is encountered in your program. Usually, however, we want
the loop to execute at least once. If so, that brings us to the first important caution:
If you want the loop body to execute at least once, you must ensure that the loop control condition
evaluates to true when the while loop is encountered in your program. For example:
bool cond = true;
...
while (cond) {
...
}
Once we are sure that the loop body will execute at least once, we have to pay attention to the second
caution:
If you want to avoid an infinite loop (where the loop is never exited) you must ensure that the loop
control condition is made to evaluate false at some point within the body of the loop. For example:
const int MAX = 1000;
int i = 0;
...
while (i < MAX) {
...
i++;
}
The loop control condition can be a simple logical expression, or it can be a fairly complicated one. For
instance:
while (((i < MAX) && cond) || keep_going) ...
Using the KISS principle (Keep It Simple, Smarty) it is always advisable to keep the loop control
condition as simple as possible.
Some programmers are purists about loop control conditions, and believe the while loop should never be
exited except at the top of the loop (when the loop control condition becomes false). C++, however, has
two statemen ...
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Honest Reviews of Tim Han LMA Course Program.pptxtimhan337
Personal development courses are widely available today, with each one promising life-changing outcomes. Tim Han’s Life Mastery Achievers (LMA) Course has drawn a lot of interest. In addition to offering my frank assessment of Success Insider’s LMA Course, this piece examines the course’s effects via a variety of Tim Han LMA course reviews and Success Insider comments.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
2. Outline
Introduction to iterative flow control
Iterative flow controls (Looping statements)
for loop
while loop
do . . . while loop
Jumping statements
break, continue, goto
Program termination statements
return, exit, abort
2
Chapter 3
3. Objectives
Learn how to use iterative flow control
Learn how to form Boolean expressions and examine
relational and logical operators
Design and develop program using loop statements
3
Chapter 3
4. 1. Introduction to looping
The loop Statements allow a set of instructions to be performed
repeatedly until a certain condition is fulfilled.
Following is the general from of a loop statement in most of
the programming languages
4
Chapter 3
5. 1. Introduction to looping (cont’d)
Part of loop
Initialization Expression(s)
initialize(s) the loop
variables in the beginning of the loop.
Test Expression
Decides whether the loop will be executed (if test expression is
true) or not (if test expression is false).
Update Expression(s)
update(s) the values of loop variables after every iteration of
the loop.
The Body-of-the-Loop
Contains statements to be executed repeatedly.
5
Chapter 3
6. 1. Introduction to looping (cont’d)
Types of loop
Most programming language provides the following types of loop to
handle looping requirements
Loop Type Description
while loop Repeats a statement or group of statements until a given
condition is true.
It tests the condition before executing the loop body.
for loop Execute a sequence of statements multiple times and
abbreviates the code that manages the loop variable.
do...while loop Like a while statement, except that it tests the
condition at the end of the loop body
nested loops You can use one or more loop inside any another
while, for or do..while loop.
6
Chapter 3
7. 1. Introduction to looping (cont’d)
Category of loops
1) Pretest and Posttest loops
Pretest loops (while loop & for loop) - the loop condition checked first,
if false, statements in the loop body never executed.
Posttest loop (do .. while loop) - the loop condition is checked/tested
after the loop body statements are executed.
Loop body always executed at least once
2) Count-controlled and Event-Controlled loops
Count-controlled (for loop) – also called fixed count loop
Repeat a statement or block a specified number of times
Used when exactly how many loops want to made
Event-controlled (while and do-while loop) – also called variable condition loop
Repeat a statement or block until a condition within the loop
body changes that cause the repetition to stop.
7
Chapter 3
8. 1. Introduction to looping (cont’d)
Types of Event-Controlled Loops
Sentinel controlled
Keep processing data until a special value (sentinel value)
that is not a possible data value is entered to indicate
that processing should stop.
End-of-file controlled
Keep processing data or executing statement(s) as long as
there is more data in the file.
Flag controlled
Keep processing data until the value of a flag changes in
the loop body
8
Chapter 3
9. 2. while loop
Syntax
while (repetition condition) {
statement (s);
}
next statement(s);
Repetition condition
It is the condition which controls the loop
Must evaluated to true/false (i.e. Boolean expression)
Can be formed by combining two or more relational expression with
logical operators
The statement is repeated as long as the loop repetition condition is true.
infinite loop - if the loop repetition condition is always true.
9
Chapter 3
10. 2. while loop (cont’d)
10
Chapter 3
Logic of a while loop
12. 3. for loop
Syntax
Condition
controls the loop and must evaluated to true/false
Can be formed by combining two or more relational expression with
logical operators
The statement is repeated as long as the loop repetition condition is true
for ( initialization ; condition ; increment )
{
statement;
}
The initialization is
executed once before the
loopbegins
The statement is executed
until the condition becomes
false
The increment portion is executed at
the end of each iteration
12
Chapter 3
13. 3. for loop (cont’d)
13
Chapter 3
statement
true
condition
evaluated
false
increment
initialization
Logic of a for loop
15. 3. for loop (cont’d)
The for loop Variations
a) Multiple initialization and update expressions
A for loop may contain multiple initialization and/or multiple
update expressions.
These multiple expressions must be separated by commas.
Example:
b) Other for loop forms
for ( ;n < 10; ) if we wanted to specify no initialization and no update expression
for (; n<10; n++)
if we wanted to include an update expression but no initialization
(maybe because the variable was already initialized before).
for (;;)
for(j=25; ;--j)
infinite loop:- Removing either all the expressions or missing condition
or using condition that never get false gives us an infinite loop
15
Chapter 3
16. 3. for loop (cont’d)
Prefix or postfix increment/decrement
Reason being that when used alone, prefix operators are faster
executed than postfix
16
Chapter 3
17. 3. for loop (cont’d)
Empty loop
If a loop does not contain any statement in its loop-body, it is said
to be an empty loop:
for(j=25; (j);--j) //(j) tests for non zero value of j.
If we put a semicolon after for’s parenthesis it repeats only for
counting the control variable.
And if we put a block of statements after such a loop, it is not a
part of for loop.
17
Chapter 3
18. 4. do . . . while loop
Syntax
do {
statement (s);
} while (repetition condition)
next statement(s);
It is similar to while loop except it is posttest loop
The statement is first executed.
If the loop repetition condition is true, the statement is repeated.
Otherwise, the loop is exited.
The repetition condition should be Boolean expression
Used when your program need to be executed at least one iteration
18
Chapter 3
19. 4. do . . . while loop (cont’d)
19
Chapter 3
Logic of a do . . while loop
23. 6. Jumping Statements
(a) The goto statement
It can transfer the program control anywhere in the program.
The target destination is marked by a label.
The target label and goto must appear in the same statement.
The syntax:
23
Chapter 3
goto label;
………
………
label:
24. 6. Jumping Statements (cont’d)
(b) The break statement
Enables a program to skip over part of the code.
It terminates the smallest enclosing while, do-while and for
loop statements.
It skips the rest of the loop and jumps over to the
statement following the loop.
The figures on the next slide explains the working of a break
statement :
Aslo use along with switch as discussed under the selection
control section
Syntax:
break;
24
Chapter 3
25. 6. Jumping Statements (cont’d)
How break statement works with loops
25
Chapter 3
while(condition)
{
statement1;
if(val>2000)
break;
:
statement2;
}
statement3;
for(initialization; condition; update)
{
statement1;
if(val>2000)
break;
:
statement2;
}
statement3;
Note:
• The break statement can be used in similar fashion with do…while loop also
26. Example of break statement
6. Jumping Statements (cont’d)
26
Chapter 3
27. 6. Jumping Statements (cont’d)
(c) The continue statement
Enables a program to skip over part of the code.
works somewhat like the break statement.
For the for loop, continue causes the conditional test and
increment portions of the loop to execute.
For the while and do...while loops, program control
passes to the conditional tests.
Syntax:
continue;
27
Chapter 3
28. Example of continue statement
6. Jumping Statements (cont’d)
28
Chapter 3
As you can see on the output
below the program jumps
printing 3 & 6 which are
factor of 3
30. 7. Terminating Program
(a) The return statement
As you seen in the main() function it terminate the program
and return control back to the Operating System
Syntax: return returnValue;
(b) The exit() function
Used to terminate the program normally and return the
control to the Operating System.
Syntax: exit(int exitCode);
Avaliable in <cstdlib> library (ported from C's "stdlib.h")
(c) The abort() function
The same as exit() function but except it used to terminate the
program abnormally.
Syntax: abort(int exitCode);
30
Chapter 3
31. 7. Terminating Program
Example
31
Chapter 3
if (errorCount > 10)
{
cout << "too many errors" << endl;
exit(-1); // Terminate the program
// also you can use abort(-1); instead to
terminate the program abnormally
}
if (errorCount > 10)
{
cout << "too many errors" << endl;
return 1;
}
32. Exercises (MCQ)
(1) The statement i++; is equivalent to
(a) i = i + i; (b) i = i + 1; (c) i = i - 1; (d) i --;
(2) What's wrong? for (int k = 2, k <=12, k++)
(a) the increment should always be ++k
(b) the variable must always be the letter i when using a for loop
(c) there should be a semicolon at the end of the statement
(c) the commas should be semicolons
(3) A looping process that checks the test condition at the end of loop?
(a) for while (b) do-while (c) while (d) none
(4) A looping process is best used when the number of iterations is
known
(a) for while (b) do-while (c) while (d) all are require
32
Chapter 3
33. Exercises (MCQ)
(5) A continue statement causes execution to skip to
(a) The return 0; statement
(b) The first statement after the loop
(c) The statement following the continue statement
(d) The next iteration of the loop
(6) A break statement causes execution to skip to
(a) The return 0; statement
(b) The first statement after the loop
(c) The statement following the continue statement
(d) The next iteration of the loop
(e) The statement outside the loop
33
Chapter 3
34. Reading Resources/Materials
Chapter 7 & 8:
Diane Zak; An Introduction to Programming with C++ [8th
Edition], 2016 Cengage Learning
Chapter 5:
Gary J. Bronson; C++ For Engineers and Scientists [3rd
edition], Course Technology, Cengage Learning, 2010
Chapter 2 (section 2.4):
Walter Savitch; Problem Solving With C++ [10th edition],
University of California, San Diego, 2018
Chapter 4 & 5:
P. Deitel , H. Deitel; C++ how to program [10th edition],
Global Edition (2017) 34
Chapter 3