The document discusses different types of loops in JavaScript, including for, do-while, while, labeled, break, continue, for-in, and for-of loops. It provides examples and explanations of how each loop type works, when to use each type, and their basic syntax. The key loops are: for loops repeat until a condition is false, do-while loops always run once then repeat while a condition is true, while loops check a condition before each iteration, and break and continue can terminate or skip iterations within a loop.
This document discusses loops in C++ programming. It defines while, for, and do-while loops and how each one works. It also describes loop control statements like break, continue, and goto that change the normal execution of loops. Finally, it provides an example of an infinite loop in C++ using a for loop without a conditional expression to repeat indefinitely.
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRKrishna Raj
This document provides an overview of different types of loop statements in computer programming, including while loops, for loops, do-while loops, and nested loops. It also discusses jump statements like break, continue, goto, and exit that change the normal flow of loops. The key types of loops covered are while loops, which repeat a statement as long as a condition is true, for loops, which allow initialization of loop variables, testing a condition, and updating variables each iteration, and do-while loops, which first execute the statement and then check the condition.
This document provides information about loop statements in programming. It discusses the different parts of a loop, types of loops including while, for, and do-while loops. It also covers nested loops and jump statements like break and continue. Examples are given for each loop type. The document concludes with multiple choice and program-based questions as exercises.
This document discusses different types of loops in Java programming: while, for, do-while, and enhanced for loops. It provides the syntax and flow for each loop type along with examples. The key loop types are:
- While loops repeat while a condition is true, testing at the start of each iteration.
- For loops iterate a specific number of times, with initialization, condition, and update sections.
- Do-while loops are like while loops but test the condition at the end, so the body executes at least once.
- Enhanced for loops iterate over collections/arrays, declaring a block variable to access each element.
Loops in C++ allow programmers to repeatedly execute a block of code. There are three main types of loops in C++: while loops, do-while loops, and for loops. While loops and do-while loops check the loop condition at the end of each iteration and repeat the block while the condition is true. For loops allow initialization of a counter variable, a condition to test on each pass, and an update to the counter. For loops are useful when the number of iterations is known. Do-while loops differ in that the block is guaranteed to run at least once even if the condition is false.
The document discusses various control structures and functions used in Arduino programming including decision making structures like if, else if, else statements and switch case statements. It also covers different types of loops like while, do-while and for loops that allow repeating blocks of code. Functions are described as reusable blocks of code that perform tasks and help organize a program. Strings can be implemented as character arrays or using the String class, and various string functions are provided to manipulate and work with strings.
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 ...
This document discusses different types of looping statements in C++ including while, do-while, and for loops. It explains the syntax and flow of each loop. While and do-while loops evaluate a condition before or after executing the loop body. For loops allow pre-determining the number of iterations using initialization, condition testing, and incrementing/decrementing of a control variable. The document also covers jump statements like goto, break, continue and exit() which can transfer program control within and between loops and functions.
This document discusses different types of loop constructs in C programming language. It describes while, do-while and for loops. While and do-while loops execute statements repeatedly as long as a given condition is true. For loops allow initialization of counters, check a condition, and update the counter each iteration. The document also covers flow charts to illustrate loop execution and examples of each loop type as well as continue, break and goto statements that change loop flow.
Loops allow blocks of code to be repeatedly executed. The three types of loops in C are while loops, for loops, and do-while loops. While loops check the condition before each iteration. For loops allow initialization, condition checking, and increment/decrement in the loop header. Do-while loops check the condition after executing the block at least once. Break and continue statements can be used to exit or skip portions of loops. Switch statements compare a value to multiple case values and execute the corresponding block.
This document discusses different types of program control statements in C++. It covers selection statements like if-else and switch that allow conditional execution of code. It also covers iteration statements like for, while, and do-while loops that allow repetitive execution of code. Additionally, it discusses jump statements like break, continue, goto, and return that allow changing the normal sequential flow of code execution. The document provides syntax and examples to explain how each of these statement types work.
C++ provides several types of loops to repeat blocks of code, including while, for, do-while, and nested loops. Loop control statements like break, continue, and goto change the normal execution flow. An infinite loop is one whose condition never becomes false, allowing the loop to repeat indefinitely until terminated.
The document discusses different types of loops in computer programming including for, while, do-while, and infinite loops. It provides examples of using each loop type to print "Hello World" multiple times and explains the key differences between while and do-while loops. While loops check the loop condition first before executing the body, whereas do-while loops always execute the body at least once before checking the condition. Infinite loops occur when the loop condition is never false, causing the loop to repeat indefinitely until terminated.
The document discusses different types of iteration logic or loops in C programming. It describes the repeat-for loop, repeat-while loop, for loop, while loop, and do-while loop. The key aspects of each loop type are defined, including initialization, condition checking, updating, and flow of execution through the loop body. Examples are provided to illustrate the usage and flow of each loop type.
This document discusses different types of looping in C programming. It introduces while, do-while, and for loops. The while loop checks the loop condition at the start of each iteration. The do-while loop checks the condition at the end of each iteration, running at least once. The for loop combines initialization, condition, and increment into one statement and is often used when the number of iterations is known. Examples are provided to illustrate the usage of each loop type.
The document summarizes common repetition structures in C programming including while, do-while, for loops as well as break, continue, and exit statements. It explains that repetition structures allow code to execute repeatedly while a condition is true and covers the syntax and usage of each structure.
Loops allow code to be executed repeatedly. The main loop types are while, for, and do-while loops. While and do-while loops test the condition at the beginning or end of the loop respectively. For loops allow code to be executed a specific number of times. Loops can be nested by placing one loop inside another. Break and continue statements control the flow of loops. Break exits the current loop while continue skips to the next iteration. Though goto can provide unconditional jumps, its use is discouraged due to reducing code readability.
Looping allows programmers to repeat instructions multiple times until a condition is no longer met. There are three main types of loops: for loops, which repeat a specified number of times; while loops, which repeat as long as a condition is true; and do-while loops, which first execute the code block once before checking the condition. For loops include initialization of a counter, a condition test, and an increment statement. Nested for loops run one or more inner loops within the body of an outer loop, so the total number of iterations equals the product of iterations in each nested loop.
This document discusses programming fundamentals and control structures in C++. It covers three main control structures: sequences which execute statements sequentially, repetition (looping) which repeats statements while a condition is met, and selection (branching) which executes instructions depending on conditions. Specific structures covered include if/else, switch, while, do-while, for, and nested loops. Control flow and how these structures direct a program's execution is also explained.
This document discusses repetition structures in C programming, including while, for, and do-while loops. It covers the basic components of loops, different types of loops, and common errors. Key topics include using while loops to compute sums and averages, using for loops with initializing, testing, and altering expressions, applying different loop programming techniques, and nesting loops within each other.
This document contains an interview with Colin Dean, a computer science graduate. In the interview, Dean discusses his realization that he wanted to study computer science, provides advice for first-year students, and shares details about his education and career. He also answers questions about whom he would like to have dinner with, what technology blogs he reads, and where he sees himself in ten years. The document concludes with biographical information about Colin Dean.
The document discusses various control structures and functions used in Arduino programming including decision making structures like if, else if, else statements and switch case statements. It also covers different types of loops like while, do-while and for loops that allow repeating blocks of code. Functions are described as reusable blocks of code that perform tasks and help organize a program. Strings can be implemented as character arrays or using the String class, and various string functions are provided to manipulate and work with strings.
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 ...
This document discusses different types of looping statements in C++ including while, do-while, and for loops. It explains the syntax and flow of each loop. While and do-while loops evaluate a condition before or after executing the loop body. For loops allow pre-determining the number of iterations using initialization, condition testing, and incrementing/decrementing of a control variable. The document also covers jump statements like goto, break, continue and exit() which can transfer program control within and between loops and functions.
This document discusses different types of loop constructs in C programming language. It describes while, do-while and for loops. While and do-while loops execute statements repeatedly as long as a given condition is true. For loops allow initialization of counters, check a condition, and update the counter each iteration. The document also covers flow charts to illustrate loop execution and examples of each loop type as well as continue, break and goto statements that change loop flow.
Loops allow blocks of code to be repeatedly executed. The three types of loops in C are while loops, for loops, and do-while loops. While loops check the condition before each iteration. For loops allow initialization, condition checking, and increment/decrement in the loop header. Do-while loops check the condition after executing the block at least once. Break and continue statements can be used to exit or skip portions of loops. Switch statements compare a value to multiple case values and execute the corresponding block.
This document discusses different types of program control statements in C++. It covers selection statements like if-else and switch that allow conditional execution of code. It also covers iteration statements like for, while, and do-while loops that allow repetitive execution of code. Additionally, it discusses jump statements like break, continue, goto, and return that allow changing the normal sequential flow of code execution. The document provides syntax and examples to explain how each of these statement types work.
C++ provides several types of loops to repeat blocks of code, including while, for, do-while, and nested loops. Loop control statements like break, continue, and goto change the normal execution flow. An infinite loop is one whose condition never becomes false, allowing the loop to repeat indefinitely until terminated.
The document discusses different types of loops in computer programming including for, while, do-while, and infinite loops. It provides examples of using each loop type to print "Hello World" multiple times and explains the key differences between while and do-while loops. While loops check the loop condition first before executing the body, whereas do-while loops always execute the body at least once before checking the condition. Infinite loops occur when the loop condition is never false, causing the loop to repeat indefinitely until terminated.
The document discusses different types of iteration logic or loops in C programming. It describes the repeat-for loop, repeat-while loop, for loop, while loop, and do-while loop. The key aspects of each loop type are defined, including initialization, condition checking, updating, and flow of execution through the loop body. Examples are provided to illustrate the usage and flow of each loop type.
This document discusses different types of looping in C programming. It introduces while, do-while, and for loops. The while loop checks the loop condition at the start of each iteration. The do-while loop checks the condition at the end of each iteration, running at least once. The for loop combines initialization, condition, and increment into one statement and is often used when the number of iterations is known. Examples are provided to illustrate the usage of each loop type.
The document summarizes common repetition structures in C programming including while, do-while, for loops as well as break, continue, and exit statements. It explains that repetition structures allow code to execute repeatedly while a condition is true and covers the syntax and usage of each structure.
Loops allow code to be executed repeatedly. The main loop types are while, for, and do-while loops. While and do-while loops test the condition at the beginning or end of the loop respectively. For loops allow code to be executed a specific number of times. Loops can be nested by placing one loop inside another. Break and continue statements control the flow of loops. Break exits the current loop while continue skips to the next iteration. Though goto can provide unconditional jumps, its use is discouraged due to reducing code readability.
Looping allows programmers to repeat instructions multiple times until a condition is no longer met. There are three main types of loops: for loops, which repeat a specified number of times; while loops, which repeat as long as a condition is true; and do-while loops, which first execute the code block once before checking the condition. For loops include initialization of a counter, a condition test, and an increment statement. Nested for loops run one or more inner loops within the body of an outer loop, so the total number of iterations equals the product of iterations in each nested loop.
This document discusses programming fundamentals and control structures in C++. It covers three main control structures: sequences which execute statements sequentially, repetition (looping) which repeats statements while a condition is met, and selection (branching) which executes instructions depending on conditions. Specific structures covered include if/else, switch, while, do-while, for, and nested loops. Control flow and how these structures direct a program's execution is also explained.
This document discusses repetition structures in C programming, including while, for, and do-while loops. It covers the basic components of loops, different types of loops, and common errors. Key topics include using while loops to compute sums and averages, using for loops with initializing, testing, and altering expressions, applying different loop programming techniques, and nesting loops within each other.
This document contains an interview with Colin Dean, a computer science graduate. In the interview, Dean discusses his realization that he wanted to study computer science, provides advice for first-year students, and shares details about his education and career. He also answers questions about whom he would like to have dinner with, what technology blogs he reads, and where he sees himself in ten years. The document concludes with biographical information about Colin Dean.
This document provides an overview of fundamental computer programming concepts in Chapter 1. It begins with defining what a computer program and programming are, and reasons for studying programming such as career opportunities and developing logical thinking. It then covers the program development life cycle and an overview of programming languages and paradigms. The remainder of the document discusses specific aspects of C++ programs including compilation processes, program structure, input/output streams, library functions, preprocessor directives, variables and data types.
This chapter provides an in-depth overview of the viscosity of macromolecules, an essential concept in biophysics and medical sciences, especially in understanding fluid behavior like blood flow in the human body.
Key concepts covered include:
✅ Definition and Types of Viscosity: Dynamic vs. Kinematic viscosity, cohesion, and adhesion.
⚙️ Methods of Measuring Viscosity:
Rotary Viscometer
Vibrational Viscometer
Falling Object Method
Capillary Viscometer
🌡️ Factors Affecting Viscosity: Temperature, composition, flow rate.
🩺 Clinical Relevance: Impact of blood viscosity in cardiovascular health.
🌊 Fluid Dynamics: Laminar vs. turbulent flow, Reynolds number.
🔬 Extension Techniques:
Chromatography (adsorption, partition, TLC, etc.)
Electrophoresis (protein/DNA separation)
Sedimentation and Centrifugation methods.
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsesushreesangita003
what is pulse ?
Purpose
physiology and Regulation of pulse
Characteristics of pulse
factors affecting pulse
Sites of pulse
Alteration of pulse
for BSC Nursing 1st semester
for Gnm Nursing 1st year
Students .
vitalsign
The ever evoilving world of science /7th class science curiosity /samyans aca...Sandeep Swamy
The Ever-Evolving World of
Science
Welcome to Grade 7 Science4not just a textbook with facts, but an invitation to
question, experiment, and explore the beautiful world we live in. From tiny cells
inside a leaf to the movement of celestial bodies, from household materials to
underground water flows, this journey will challenge your thinking and expand
your knowledge.
Notice something special about this book? The page numbers follow the playful
flight of a butterfly and a soaring paper plane! Just as these objects take flight,
learning soars when curiosity leads the way. Simple observations, like paper
planes, have inspired scientific explorations throughout history.
Exploring Substances:
Acidic, Basic, and
Neutral
Welcome to the fascinating world of acids and bases! Join siblings Ashwin and
Keerthi as they explore the colorful world of substances at their school's
National Science Day fair. Their adventure begins with a mysterious white paper
that reveals hidden messages when sprayed with a special liquid.
In this presentation, we'll discover how different substances can be classified as
acidic, basic, or neutral. We'll explore natural indicators like litmus, red rose
extract, and turmeric that help us identify these substances through color
changes. We'll also learn about neutralization reactions and their applications in
our daily lives.
by sandeep swamy
Odoo Inventory Rules and Routes v17 - Odoo SlidesCeline George
Odoo's inventory management system is highly flexible and powerful, allowing businesses to efficiently manage their stock operations through the use of Rules and Routes.
GDGLSPGCOER - Git and GitHub Workshop.pptxazeenhodekar
This presentation covers the fundamentals of Git and version control in a practical, beginner-friendly way. Learn key commands, the Git data model, commit workflows, and how to collaborate effectively using Git — all explained with visuals, examples, and relatable humor.
How to Subscribe Newsletter From Odoo 18 WebsiteCeline George
Newsletter is a powerful tool that effectively manage the email marketing . It allows us to send professional looking HTML formatted emails. Under the Mailing Lists in Email Marketing we can find all the Newsletter.
Title: A Quick and Illustrated Guide to APA Style Referencing (7th Edition)
This visual and beginner-friendly guide simplifies the APA referencing style (7th edition) for academic writing. Designed especially for commerce students and research beginners, it includes:
✅ Real examples from original research papers
✅ Color-coded diagrams for clarity
✅ Key rules for in-text citation and reference list formatting
✅ Free citation tools like Mendeley & Zotero explained
Whether you're writing a college assignment, dissertation, or academic article, this guide will help you cite your sources correctly, confidently, and consistent.
Created by: Prof. Ishika Ghosh,
Faculty.
📩 For queries or feedback: [email protected]
*Metamorphosis* is a biological process where an animal undergoes a dramatic transformation from a juvenile or larval stage to a adult stage, often involving significant changes in form and structure. This process is commonly seen in insects, amphibians, and some other animals.
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetSritoma Majumder
Introduction
All the materials around us are made up of elements. These elements can be broadly divided into two major groups:
Metals
Non-Metals
Each group has its own unique physical and chemical properties. Let's understand them one by one.
Physical Properties
1. Appearance
Metals: Shiny (lustrous). Example: gold, silver, copper.
Non-metals: Dull appearance (except iodine, which is shiny).
2. Hardness
Metals: Generally hard. Example: iron.
Non-metals: Usually soft (except diamond, a form of carbon, which is very hard).
3. State
Metals: Mostly solids at room temperature (except mercury, which is a liquid).
Non-metals: Can be solids, liquids, or gases. Example: oxygen (gas), bromine (liquid), sulphur (solid).
4. Malleability
Metals: Can be hammered into thin sheets (malleable).
Non-metals: Not malleable. They break when hammered (brittle).
5. Ductility
Metals: Can be drawn into wires (ductile).
Non-metals: Not ductile.
6. Conductivity
Metals: Good conductors of heat and electricity.
Non-metals: Poor conductors (except graphite, which is a good conductor).
7. Sonorous Nature
Metals: Produce a ringing sound when struck.
Non-metals: Do not produce sound.
Chemical Properties
1. Reaction with Oxygen
Metals react with oxygen to form metal oxides.
These metal oxides are usually basic.
Non-metals react with oxygen to form non-metallic oxides.
These oxides are usually acidic.
2. Reaction with Water
Metals:
Some react vigorously (e.g., sodium).
Some react slowly (e.g., iron).
Some do not react at all (e.g., gold, silver).
Non-metals: Generally do not react with water.
3. Reaction with Acids
Metals react with acids to produce salt and hydrogen gas.
Non-metals: Do not react with acids.
4. Reaction with Bases
Some non-metals react with bases to form salts, but this is rare.
Metals generally do not react with bases directly (except amphoteric metals like aluminum and zinc).
Displacement Reaction
More reactive metals can displace less reactive metals from their salt solutions.
Uses of Metals
Iron: Making machines, tools, and buildings.
Aluminum: Used in aircraft, utensils.
Copper: Electrical wires.
Gold and Silver: Jewelry.
Zinc: Coating iron to prevent rusting (galvanization).
Uses of Non-Metals
Oxygen: Breathing.
Nitrogen: Fertilizers.
Chlorine: Water purification.
Carbon: Fuel (coal), steel-making (coke).
Iodine: Medicines.
Alloys
An alloy is a mixture of metals or a metal with a non-metal.
Alloys have improved properties like strength, resistance to rusting.
INTRO TO STATISTICS
INTRO TO SPSS INTERFACE
CLEANING MULTIPLE CHOICE RESPONSE DATA WITH EXCEL
ANALYZING MULTIPLE CHOICE RESPONSE DATA
INTERPRETATION
Q & A SESSION
PRACTICAL HANDS-ON ACTIVITY
Geography Sem II Unit 1C Correlation of Geography with other school subjectsProfDrShaikhImran
The correlation of school subjects refers to the interconnectedness and mutual reinforcement between different academic disciplines. This concept highlights how knowledge and skills in one subject can support, enhance, or overlap with learning in another. Recognizing these correlations helps in creating a more holistic and meaningful educational experience.
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessMark Soia
Boost your chances of passing the 2V0-11.25 exam with CertsExpert reliable exam dumps. Prepare effectively and ace the VMware certification on your first try
Quality dumps. Trusted results. — Visit CertsExpert Now: https://www.certsexpert.com/2V0-11.25-pdf-questions.html
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