Beruflich Dokumente
Kultur Dokumente
Repetition Structure
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
true
statements
next statement
} next statement;
5
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
Infinite Loops
An infinite loop is one in which the condition is initially satisfied, so the loop is entered, but the condition for exiting the loop is never met. Generally an infinite loop is caused by failing to modify a variable involved in the condition within the loop body. To break out of a malfunctioning program press ctrl-C on Linux or ctrl-break, on an DOS or Windows machine.
INTRODUCTION TO PROGRAMMING
How should it be fixed to print the numbers between 1 and 5 inclusive in a column?
9
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
11
INTRODUCTION TO PROGRAMMING
#include <iostream> using namespace std; int main() { int number, sum, cnt; //Initialization cout << Enter a list of integers terminated by 99; cin >> number; //first number sum = 0; cnt = 0; while (number != -99) //Loop to sum and count values { sum += number; ++cnt; cin >> number; //Read next number } //while //Calculate and print average cout << The average is << sum/float(cnt); return 0; } //main
12
INTRODUCTION TO PROGRAMMING
A loop body of more than one statement, must be enclosed in curly braces.
13
INTRODUCTION TO PROGRAMMING
14
INTRODUCTION TO PROGRAMMING
Example
Print the numbers from 100 to 10 as follows; 100 90 80 70 --------- 10 for ( int i=100 ; i>=10 ; I = i-10 ) { cout<< i << ; }
15
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
Nesting of Loops
The statements in the loop body may be any C+ + statement including another looping statement. When a for loop is entered from the top, the initialization occurs and then the boolean expressions are executed. When it is entered as a result of completing execution of the loop body the increment and then the boolean expressions are executed.
19
INTRODUCTION TO PROGRAMMING
K <=3
cout<<I<<,<<K
20
INTRODUCTION TO PROGRAMMING
true
bool expr
do {
INTRODUCTION TO PROGRAMMING
22
INTRODUCTION TO PROGRAMMING
INTRODUCTION TO PROGRAMMING
24
INTRODUCTION TO PROGRAMMING
25
INTRODUCTION TO PROGRAMMING