Lecture Notes 3 Loops (Repetition)

Slides:



Advertisements
Similar presentations
Lecture Computer Science I - Martin Hardwick Strings #include using namespace std; int main () { string word; cout
Advertisements

Control Flow Statements: Repetition/Looping
Programming In C++ Spring Semester 2013 Lecture 3 Programming In C++, Lecture 3 By Umer Rana.
CS 101 Introductory Programming - Lecture 7: Loops In C & Good Coding Practices Presenter: Ankur Chattopadhyay.
Do-while Loops Programming. COMP102 Prog Fundamentals I: do-while Loops /Slide 2 The do-while Statement l Syntax do action while (condition) l How it.
Loops –Do while Do While Reading for this Lecture, L&L, 5.7.
The "if structure" is used to execute statement(s) only if the given condition is satisfied.
Write a function to calculate the cubic function: y = 4x 3 + 2x 2 –5x – 4 The function should return y for any given value of x. Question One #include.
CSC 221: Computer Programming I Fall 2001  conditional repetition  repetition for: simulations, input verification, input sequences, …  while loops.
Tinaliah, S. Kom.. * * * * * * * * * * * * * * * * * #include using namespace std; void main () { for (int i = 1; i
Triana Elizabeth, S.Kom. #include using namespace std; void main () { for (int i = 1; i
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Executes a statement or statements for a number of times – iteration. Syntax for(initialize; test; increment) { // statements to be executed } Initial.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
A loop is a repetition control structure. it causes a single statement or block to be executed repeatedly What is a loop?
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Announcements Quiz 1 Posted on blackboard Handed Back (and Gone Over)Next Monday “Only a Quiz” Counts 5% of Final Grade Exam 1 Counts 10%
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
1 Lecture 14 Chapter 6 Looping Dale/Weems/Headington.
Copyright © Texas Education Agency, Computer Programming For Loops.
Loops Programming. COMP104 Lecture 9 / Slide 2 Shortcut Assignment l C++ has a set of operators for applying an operation to a variable and then storing.
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Chapter 6 Looping.
COMP 1001: Introduction to Computers for Arts and Social Sciences Programming in Scratch Monday, May 16, 2011.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Engineering 1020 Introduction to Programming Peter King Winter 2010.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Lecture 15: Control Flow (cont). 2 Lecture Contents: t Design and implementation of programs illustrating linear algorithms, branch algorithms and loop.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
Program Flow Control - Looping Addis Ababa Institute of Technology Yared Semu April 2012.
Control Structures CPS120: Introduction to Computer Science Lecture 5.
ITEC 109 Lecture 11 While loops. while loops Review Choices –1 st –2 nd to ?th –Last What happens if you only use ifs? Can you have just an else by itself?
Structured Programming The Basics. Control structures They control the order of execution What order statements will be done in, or whether they will.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
REPETITION STATEMENTS - Part1  Also called LOOP STATEMENTS OR LOOP STRUCTURES 1 C++ Statements that repeat one or more actions while some condition is.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
LESSON 5 Loop Control Structure. Loop Control Structure  Operation made over and over again.  Iterate statement.
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
ITEC 2600 Introduction to Analytical Programming
Control Flow based Testing
Repetition Structures (Loops)
Programming Fundamentals
Web Programming– UFCFB Lecture 16
Intro to Programming Week # 5 Repetition Structure Lecture # 9
Introducing Do While & Do Until Loops & Repetition Statements
Loop Control Structure.
CPS120: Introduction to Computer Science
Scratch: selection / branching/ if / If…else / compound conditionals / error trapping by Mr. Clausen.
Control Structures Part 2
Computer Science Core Concepts
Let’s all Repeat Together
ICT Programming Lesson 3:
Statements and flow control
Repetition Statements (Loops) - 2
Statements in C Programming
Loops CGS3416 Spring 2019 Lecture 7.
Chapter 2 Sets Active Learning Lecture Slides
Review of Previous Lesson
CPS120: Introduction to Computer Science
Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement.
SEQUENCE Start Initial situation Step 1 Step 2 Step 3 End
How to allow the program to know when to stop a loop.
Presentation transcript:

Lecture Notes 3 Loops (Repetition) Andreas Savva Programming in C++ Lecture Notes 3 Loops (Repetition)

Structures Sequential Branching Repeating

Loops Repetition is referred to the ability of repeating a statement or a set of statements as many times this is necessary.

The teacher of physical education said: Run around the football-field until I tell you to stop. Run around the football-field five times.

Loops while() do – while() for( ; ; )

The while() Loop while (<Condition>) <Loop body> ; true false while (<Condition>) <Loop body> ;

The while() Loop while (<Condition>) <Statement> ; { <Statement 1> ; <Statement 2> ; . . . }

#include <iostream> using namespace std; void main() { cout << ” * \n”; cout << ” *** \n”; cout << ”*****\n”; cout << endl; } * *** ***** * *** *****

i #include <iostream> using namespace std; * void main() *** Screen #include <iostream> using namespace std; void main() { int i = 1; while (i <= 4) cout << ” * \n”; cout << ” *** \n”; cout << ”*****\n”; cout << endl; i++; } * *** ***** i Variable 5 4 1 3 2 true false

i #include <iostream> using namespace std; void main() { Variable #include <iostream> using namespace std; void main() { int i = 1; while (i < 11) i += 3; cout << i << endl; } 10 13 7 4 1 Screen 4 7 10 13

Examples void main() { int i = 1; while (i<=5) cout << i << ’ ’; i++; } 1 2 3 4 5 void main() { int i = 1; while (i<=5) cout << ’i’ << ’ ’; ++i; } i i i i i

More Examples void main() { int i = 1; while (i<=5) 1 1 1 1 1 1 … cout << i << ’ ’; i++; } 1 1 1 1 1 1 … void main() { int i = 1; while (i<=5) cout << i++ << ’ ’; } 1 2 3 4 5

More Examples void main() { int x; 2 3 -6 -999 while (cin >> x, x!=-999) cout << x << ’ ’; } 2 3 -6 -999 2 3 -6 void main() { int x; while (cin >> x, x!=-999); cout << x << ’ ’; } 2 3 -6 -999 -999

More Examples void main() { int i = 1; 2 3 4 5 while (i++ < 5) cout << i << ’ ’; } 2 3 4 5 void main() { int i = 1; while (++i < 5) cout << i << ’ ’; } 2 3 4

Exercises What is the output of the following segments? (a) int i = -3; while (i != 3) { cout << i << ” ”; i = i + 1; } (b) int i = 0, sum = 0; while (i <= 10) sum += i; i++; cout << ”Sum = ” << sum; (c) int i = 1; while (i++ <= 5) (d) int i = 10; while (i > 3) { cout << i << endl; i = i - 2; } (e) int i = 6; while (i-- > 1) cout << i << ’\n’; (f) int i = 0; while (++i < 8) cout << i; (g) int i = -3; while (++i <= 3); cout << ’i’;

Exercises Write a program to display the numbers from 1 to 100 inclusive. Write a program to display all the letters of the Latin alphabet. Write a program to calculate the average of the integer numbers between 15 and 25, inclusive. Write a program to display the odd numbers from 1 to 101, and also to display their sum. Write a program to read the radian of a circle, check if it is bigger than zero, and if it is to calculate and display the perimeter of the circle using the formula P=2*3.14*R, where P is the perimeter and R is the radius of the circle. Otherwise it should prompt for the radius again until it is bigger than zero. The powers of 2 are: 1, 2, 4, 8, 16, 32, … . Write a program to display the first power of 2, which is bigger than 1000. Write a program to calculate the sum of: 12 + 22 + 32 + … + Ν2.

Nested Loops Example 1 12345 #include <iostream> using namespace std; void main() { int i, j, n = 5; i = 1; while (i <= n) j = 1; while (j <= n) cout << j; j++; } cout << endl; i++; 12345

Nested Loops Example 2 #include <iostream> using namespace std; void main() { int i, j, n = 5; i = 1; while (i <= n) j = 1; while (j <= n) cout << i; j++; } cout << endl; i++; 11111 22222 33333 44444 55555

Nested Loops Example 3 ABCDEF #include <iostream> using namespace std; void main() { char i, j, n = ’F’; i = ’A’; while (i <= n) j = ’A’; while (j <= n) cout << j; j++; } cout << endl; i++; ABCDEF

Nested Loops Example 4 ABCDEF BCDEF CDEF DEF EF F #include <iostream> using namespace std; void main() { char i, j, n = ’F’; i = ’A’; while (i <= n) j = i; while (j <= n) cout << j; j++; } cout << endl; i++; ABCDEF BCDEF CDEF DEF EF F

Nested Loops Example 5 A AB ABC ABCD ABCDE ABCDEF #include <iostream> using namespace std; void main() { char i, j, n = ’F’; i = ’A’; while (i <= n) j = ’A’; while (j <= i) cout << j; j++; } cout << endl; i++; A AB ABC ABCD ABCDE ABCDEF

Nested Loops Example 6 * * * * * * * void main() { int i, j, n = 7; while (i <= n) j = 1; while (j <= n) if (i==j || i+j==n+1) cout << ’*’; else cout << ’ ’; j++; } cout << endl; i++; * * * * * * *

Exercises What is the output of the following program if the input for n is: (a) 0 (b) 1 (c) 2 (d) 4 (e) 7 #include <iostream> using namespace std; void main() { int i=1, j, n; cout << ”Enter n: ”; cin >> n; n = 2 * n + 1; while (i <= n) { j = 1; while (j <= n) { if ((2*i == n+1) || (2*j == n+1)) cout << ’*’; else cout << ’ ’; j++; } cout << endl; i++;

The do–while() Loop do <Loop body> ; while (<Condition>); true false do <Loop body> ; while (<Condition>);

The do – while() Loop do <Statement> ; while (<Condition>) ; do { <Statement 1> ; <Statement 2> ; . . . } while (<Condition>) ;

i #include <iostream> using namespace std; * void main() *** { Screen #include <iostream> using namespace std; void main() { int i = 1; do { cout << ” * \n”; cout << ” *** \n”; cout << ”*****\n”; cout << endl; i++; } while(i <= 4); } * *** ***** i Variable 5 4 2 1 3

i #include <iostream> using namespace std; void main() { Variable #include <iostream> using namespace std; void main() { int i = 1; do i += 3; cout << i << endl; } while(i < 11); } 10 13 7 4 1 Screen 4 7 10 13

The for( ; ; ) Loop for (<init> ; <condition> ; <change>) <Loop body> ; init is usually an assignment to give a loop counter an initial value. Executed ONLY when entering the loop. Can also declare variables. condition is any statement returning an integral value and for as long as it is true, the statement will be executed. Executed at every pass. change is a statement normally to modify the loop counter, so that eventually it will make condition false and the loop will terminate. Executed at every pass after the execution of the loop body.

Example 1 1 2 3 4 5 6 void main() { int i; for(i=1; i<7; i++) cout << i << ” ”; } 1 2 3 4 5 6

Example 2 1 2 3 4 5 6 void main() { int i; for(i=1; i<7; ++i) cout << i << ” ”; } 1 2 3 4 5 6

Example 3 2 3 4 5 6 7 void main() { int i; for(i=1; i++<7; ) cout << i << ” ”; } 2 3 4 5 6 7

Example 4 2 3 4 5 6 void main() { int i; for(i=1; ++i<7; ) cout << i << ” ”; } 2 3 4 5 6

Example 5 9 8 7 6 void main() { int i; for(i=9; i>5; --i) cout << i << ” ”; } 9 8 7 6

while equivalent of for for (i=0; i<5; i++) cout << i; i=0; while (i<5) { i++; } same as Example e1; while(e2) { s; e3; } for(e1; e2; e3) s; same as

Nested For-Loops Example 1 int main() { int i, j, n = 7; for(i=1; i<=n; i++){ for(j=1; j<=i; j++) cout << j; cout << endl; } return 0; 1 12 123 1234 12345 123456 1234567

Nested For-Loops Example 2 int main() { int n = 7; for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) if (i==j) cout << ’*’; else if (i>j) cout << i; else cout << j-i; cout << endl; } return 0; *123456 2*12345 33*1234 444*123 5555*12 66666*1 777777*

The power of C++ Enter x: 6 3 7 -999 Enter x: 6 Enter x: 3 Enter x: 7 #include <iostream> using namespace std; void main() { int x; for(cout << ”Enter x: ” ; cin >> x, x!=-999 ; ) ; } Enter x: 6 3 7 -999 #include <iostream> using namespace std; void main() { int x; for( ; cout << ”Enter x: ” , cin >> x, x!=-999 ; ) ; } Enter x: 6 Enter x: 3 Enter x: 7 Enter x: -999

Endless Loop #include <iostream> using namespace std; void main() { for( ; ; ) ; }

Exercise #include <iostream> #include <iomanip> void main() { printf(’ M T W T F S S’); printf(’ --------------------’); for (int day=1; day<=31; day++) if (day % 7 == 0) cout << setw(3) << day << endl; else cout << setw(3) << day; } M T W T F S S -------------------- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

The break and continue statements A break statement is used to “break” out of a loop or a switch statement. When it is executed, it causes the flow of control to immediately exit the innermost switch statement or loop. A continue statement can only be used inside loops and it causes the execution to skip to the end of the loop, ready to start a new insertion.

Break & Continue statements void main() { for(int i=1; i<8; i++) if (i==4) break; cout << i << ” ”; } 1 2 3 void main() { for(int i=1; i<8; i++) if (i==4) continue; cout << i << ” ”; } 1 2 3 5 6 7

Memory Scope C++ is a block language. { … } Variables declared in a block are called local variables. Variables declared outside the block, but not within another inner block, are called global variables. { int x; const double pi = 3.14; x = 1; int p = 4; x = p; cout << x << p; } int y = 12; cout << x << y << pi; x pi p y

Scope Example 8 17 #include <iostream> using namespace std; int main() { int x = 5, y = 3; cout << x + y << endl; int y = 12; } return 0; 8 17

Local and Global Variables #include <iostream> using namespace std; float max; int main() { int x, y; ... int y, z; } char ch; float x, p; return 0; 1 2 3 4 5 1 2 3 4 5 Local Global max x, y max y, z x, max ch x, y, max x, p ch, y, max

undeclared identifier Scope Correct Wrong #include <iostream> using namespace std; int main() { int i; for(i=0; i<10; i++) cout << i; } return 0; #include <iostream> using namespace std; int main() { for(int i=0; i<10; i++) cout << i; } return 0; i i undeclared identifier for(int i=0; i<10; i++) cout << i; Wrong

Be Careful 00000000000 ... #include <iostream> using namespace std; int main() { int i; while(i=0, i<10) cout << i; i = i + 1; } return 0; 00000000000 ...

Random Number Generation Library: stdlib.h Generates unsigned integer between 0 and RAND_MAX (usually 32767). Used in games. Examples: i = rand() % 6; // generates a number between 0 and 5 i = 1 + rand() % 6; // generates a number between 1 and 6 num = rand();

Returns the current time in seconds Random Numbers #include <iostream> using namespace std; #include <stdlib.h> #include <time.h> void main(){ int i; srand(time(0)); for(i=0; i<10; i++) cout << 1+rand()%6 << ’ ’; } Returns the current time in seconds 2 3 4 5 6 6 2 5 1 2