Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.

Slides:



Advertisements
Similar presentations
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Advertisements

True or false A variable of type char can hold the value 301. ( F )
Computer Science 1620 Loops.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
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.
Lecture 1 The Basics (Review of Familiar Topics).
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 6 Repetition Statements.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Fundamentals of Python: From First Programs Through Data Structures
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Chapter 4 Program Control Statements
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Chapter 4 Selection Structures: Making Decisions.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
1 C++ Programming Basics Chapter 2 Lecture CSIS 10A.
CONTROLLING PROGRAM FLOW
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
C++ Programming: Basic Elements of C++.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Lecture 04 Structural Programming in C++ You will learn: i) Operators: relational and logical ii) Conditional statements iii) Repetitive statements.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
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,
Chapter 3. Outline Relational Operators Loops Decisions Logical Operators Precedence Summary.
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
1 CS161 Introduction to Computer Science Topic #8.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
CSC 1010 Programming for All Lecture 4 Loops Some material based on material from Marty Stepp, Instructor, University of Washington.
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
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.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Computer Programming
Chapter 3 Selection Statements
LESSON 06.
REPETITION CONTROL STRUCTURE
The setw Manipulator The setw manipulator causes the number (or string) that follows it in the stream to be printed within a field n characters wide, where.
Chapter 4 C Program Control Part I
Introduction to C++ October 2, 2017.
Intro to Programming Week # 5 Repetition Structure Lecture # 9
Lecture 4B More Repetition Richard Gesick
Outline Altering flow of control Boolean expressions
Chapter 4 - Program Control
3 Control Statements:.
Computing Fundamentals
Chapter 4: Control Structures I (Selection)
Algorithms computer as the tool process – algorithm
2.6 The if/else Selection Structure
Using C++ Arithmetic Operators and Control Structures
Programming Fundamental
Presentation transcript:

Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1

The while loops 2

3 The for loop does something a fixed number of times. What happens if you don’t know how many times you want to do something before you start the loop? In this case a different kind of loop may be used: the while loop.

The while loops while (expression) statement(s) non-zero value (true) A while loop will continue executing as long as expression evaluates to a non-zero value (true). 4

Example 1 5 Asks the user to enter a series of numbers. When the number entered is 0, the loop terminates. Notice that there’s no way for the program to know in advance how many numbers will be typed before the 0 appears; that’s up to the user.

Example 1, cont. 6 // endon0.cpp // demonstrates WHILE loop #include using namespace std; int main() { int n = 99; // make sure n isn’t initialized to 0 while( n != 0 ) // loop until n is 0 cin >> n; // read a number into n cout << endl; return 0; }

The syntax of the while loop 7 The while loop looks like a simplified version of the for loop. It contains a test expression but no initialization or increment expressions.

Multiple Statements in a while Loop 8 Example 2:Example 2: calculates the fourth power of a series of integers. Let’s assume that in this program it’s important to put the results in a column four digits wide. To ensure that the results fit this column width, we must stop the loop before the results become larger than Without prior calculation we don’t know what number will generate a result of this size, so we let the program figure it out.

Multiple Statements in a while Loop, cont. 9 #include #include //for setw using namespace std; int main() { int pow=1; //power initially 1 int numb=1; //numb goes from 1 to ??? while( pow<10000 ) //loop while power <= 4 digits { cout << setw(2) << numb; //display number cout << setw(4) << pow << endl; //display fourth power ++numb; //get ready for next power pow = numb*numb*numb*numb; //calculate fourth power } cout << endl; return 0; }

Multiple Statements in a while Loop, cont. 10 Here’s the output:

The precedence of the operators 11

while statement equivalent to for statement 12 The general form of the for statement is for ( initialization; loopContinuationCondition; increment ) statement In most cases, the for statement can be represented by an equivalent while statement, as follows: initialization; while ( loopContinuationCondition ) { statement increment; }

while statement equivalent to for statement, cont. How do you print your name 10 times using a while loop? int x = 0; while (x < 10) { cout << “Ahmed” << endl; x++; } 13

 Write a program for computing factorial N (N!), Where N! = 1 *2 * 3 * N. #include using namespace std; void main() { int N; cout<<"Please enter a number:"; cin>>N; int f = 1; for(int i = N; i>1; i--) f = f * i; cout<<"Factorial of "<<N<<" is "<<f<<endl; }

#include using namespace std; void main() { int N; cout<<"Please enter a number:"; cin>>N; int f = 1; int i = N; while(i>1) { f = f * i; i--; } cout<<"Factorial of "<<N<<" is "<<f<<endl; }

The Do..while loops 16

Control Structures--do…while loops 17 A do..while loop is very similar to a regular while loop. Terminating condition is specified at the end of the loop do { statements; } while (expression);

Syntax of do..while 18

Example 4 19 DIVDO, invites the user to enter two numbers: a dividend (the top number in a division) and a divisor (the bottom number). It then calculates the quotient (the answer) and the remainder, using the / and % operators, and prints out the result.

Example 4, cont. 20 #include using namespace std; void main() { long dividend, divisor; char ch; do //start of do loop { //do some processing cout > dividend; cout > divisor; cout << “Quotient is “ << dividend / divisor; cout << “, remainder is “ << dividend % divisor; cout << “\nDo another? (y/n): “; //do it again? cin >> ch; } while( ch != ‘n’ ); //loop condition }

Example 4, cont. 21 Here’s an example of DIVDO’s output: Enter dividend: 11 Enter divisor: 3 Quotient is 3, remainder is 2 Do another? (y/n): y Enter dividend: 222 Enter divisor: 17 Quotient is 13, remainder is 1 Do another? (y/n): n

Revision 22

Questions 1- Convert each of the following mathematical formulas to a C++ expression. 2- The following code intends to input a user’s first name, last name, and age. However, it has an error. Fix the code. string fullName; int age; cout << "Enter your first and last name." << endl; cin >> fullName; cout << "Enter your age." << endl; cin >> age; cout << "You are " << age << " years old, " << fullName << endl;

Questions cont., 3- What will the following code output? {string s1 = "5"; string s2 = "3"; string s3 = s1 + s2; cout << s3 << endl;} 4- Determine the value, true or false, of each of the following Boolean expressions, assuming that the value of the variable count is 0 and the value of the variable limit is 10. Give your answer as one of the values true or false. »a. (count = = 0) && (limit < 20) »b. count = = 0 && limit < 20 »c. (limit > 20) || (count < 5) »d. !(count = = 12) »e. (count = = 1) && (x < y) »f. (count < 10) || (x < y) »g. !( ((count = 0) ) »h. ((limit / count) > 7) || (limit < 20) »i. (limit 7) »j. ((limit / count) > 7) && (limit < 0) »k. (limit 7) »l. (5 && 7) + (!6)

Questions cot., 5- Does the following sequence produce division by zero? { j = -1; if ((j > 0) && (1/(j + 1) > 10)) cout << i << endl; } 6- Write an if-else statement that outputs the word Warning provided that either the value of the variable temperature is greater than or equal to 100, or the value of the variable pressure is greater than or equal to 200, or both. Otherwise, the if-else statement outputs the word OK. The variables temperature and pressure are both of type int.

Questions cont., 7- What is the output of the following? Explain your answers. a. if(0) cout << "0 is true"; else cout << "0 is false"; cout << “ try again”; b. if(1) cout << "1 is true"; else cout << "1 is false"; cout << “ try again”; c. if(-1) cout << "-1 is true"; else {cout << "-1 is false"; cout << “ try again”;}

Questions cont., 8- What output will be produced by the following code? int x = 2; cout << "Start\n"; if (x <= 3) if (x != 0) cout << "Hello from the second if.\n"; else cout << "Hello from the else.\n"; cout << "End\n"; cout << "Start again\n"; if (x > 3) if (x != 0) cout << "Hello from the second if.\n"; else cout << "Hello from the else.\n"; cout << "End again\n";

Questions cont., 9- Write a multi-way if-else statement that classifies the value of an int variable n into one of the following categories and writes out an appropriate message. n What is the output of the following? int count = 3; while (count- - > 0) cout << count << " "; 11. What is the output of the following? int count = 3; while (- -count > 0) cout << count << " "; 12. What is the output of the following? int n = 1; do cout << n << " "; while (n++ <= 3);

Answers 1- 3*x + y, (x + y)/7 Note that x + y/7 is not correct, (3*x + y)/(z + 2) 2- the fixed program will be { string first, last; int age; cout << "Enter your first and last name." << endl; cin >> first >> last; cout << "Enter your age." << endl; cin >> age; cout << "You are " << age << " years old, " << first << " " << last << endl;} true, true, true, true, false, true, false, error ((limit/count) > 7) involves a division by zero, true, error (division by zero), false, true. 5- no, since j>0 is false condition. 6. if ( (temperature >= 100) || (pressure >= 200) ) cout << "Warning"; else cout << "OK";

Answers 7- All nonzero integers are converted to true ; 0 is converted to false. a. 0 is false try again b. 1 is true try again c. -1 is true 8- Start Hello from the second if. End Start again End again 9- Both of the following are correct if (n < 0) cout << n << " is less than zero.\n"; else if ((0 <= n) && (n <= 100)) cout << n << " is between 0 and 100\n"; else if (n >100) cout << n << " is larger than 100.\n"; if (n < 0) cout << n << " is less than zero.\n"; else if (n <= 100) cout << n << " is between 0 and 100.\n"; else cout << n << " is larger than 100.\n";

Answers

Lecture 7 Nesting If Statement & Loops. Exit(o); Break; Continue; Structure.

Flow of Control Statements Three kinds of control structures 1.Sequential Structure 2.Repetition structure (also known as Iterative or Loops ) –For –While –do-while 3.Selection structure (also known as Decisions or Branches ) – if –if-else –Switch 33

Precedence: Arithmetic and Relational Operators, cont. 34 The test expression uses two operators: (next < limit / 2) Our intention is to compare next with the result of limit/2. higherarithmetic operators have a higher precedence than relational operators.

Nesting If Statement & Loops - exit(0); - break; - Continue; 35

Nesting: ifs Inside Loops The loop and decision structures we’ve seen so far can be nested inside one another. You can nest ifs inside loops, loops inside ifs, ifs inside ifs, and so on. Example 6, PRIME. –This example tells you whether a number you enter is a prime number. –Prime numbers are integers divisible only by themselves and 1. The first few primes are 2, 3, 5, 7, 11, 13, 17.

Nesting ifs Inside Loops, cont. #include using namespace std; #include //for exit() int main() { unsigned long n, j; cout << “Enter a number: “; cin >> n; //get number to test for(j=2; j <= n/2; j++) //divide by every integer from if(n%j == 0) //2 on up; if remainder is 0, {cout << “It’s not prime; divisible by “ << j << endl; exit(0); //exit from the program } cout << “It’s prime\n”; return 0; }

Nesting ifs Inside Loops, cont. Here’s output from three separate invocations of the program: Enter a number: 13 It’s prime Enter a number: It’s prime Enter a number: It’s not prime; divisible by 11

A break Statement in a Loop The break statement can be used with any of the C++ loop statements. a break statement ends a loop when an inappropriate input is entered.

#include using namespace std; int main( ) { int number, sum = 0, count = 1; cout << "Enter 4 negative numbers:\n"; while (count <= 4) { cin >> number; if (number >= 0) { cout << "ERROR: positive number" << " or zero was entered "; break; } sum = sum + number; count++; } cout << sum << " is the sum of the first " << (count - 1) << " numbers.\n"; return 0; }

The run of the program

A continue Statement in a Loop. The continue statement ends the current iteration of the loop body.

The run of the program

Structures Chapter 4 - Structures Chapter 4Chapter 4 –Structures

Structure Sometimes it is useful to have a collection of values of different types and to treat the collection as a single item. It is looks like you build your own variables’ type.

Structures A structure is a collection of simple variables. The variables in a structure can be of different types: Some can be int, some can be float, and so on. membersDefining the Structure: The structure definition tells how the structure is organized: It specifies what members the structure will have. Structure name “tag” 47

Syntax of the Structure Definition

Defining a Structure Variable The definitionThe definition does not itself define any variables; –that is, it does not set aside any space in memory or even name any variables. –It’s merely a specification for how such structure variables will look when they are defined. Defines a Structure variableDefines a Structure variable, called part1, of type structure part. part part1; 49

The following figure shows how part1 looks in memory. 50

Simple program #include using namespace std; struct part //declare a structure {int modelnumber; //ID number of widget int partnumber; //ID number of widget part float cost; //cost of part }; //////////////////////////////////////////////////////////// int main() { part part1; //define a structure variable …… ….. return 0; } 51

Accessing Value to Structure Members dot operator (.) used to access the struct members. part1.modelnumber = 6244;. part1.partnumber = 373;. part1.cost = F; 52

Simple program, cont. #include using namespace std; struct part //declare a structure { int modelnumber; //ID number of widget int partnumber; //ID number of widget part float cost; //cost of part }; //////////////////////////////////////////////////////////////// void main() { part part1; //define a structure variable part1.modelnumber = 6244; //give values to structure members part1.partnumber = 373; part1.cost = F; //display structure members cout << “Model ” << part1.modelnumber; cout << “, part ” << part1.partnumber; cout << “, costs $” << part1.cost << endl; } 53

Initializing Structure Members #include using namespace std; /////////////////////////////////////////////////// struct part //specify a structure { int modelnumber; //ID number of widget int partnumber; //ID number of widget part float cost; //cost of part }; //////////////////////////////////////////////////// int main() { part part1 = { 6244, 373, F }; //initialize variable part part2; //define variable 54

Initializing Structure Members, cont. //display first variable cout << “Model ” << part1.modelnumber; cout << “, part ” << part1.partnumber; cout << “, costs $” << part1.cost << endl; part2 = part1; //assign first variable to second //display second variable cout << “Model “ << part2.modelnumber; cout << “, part “ << part2.partnumber; cout << “, costs $” << part2.cost << endl; return 0; } 55

Other syntax Combining Declaration and Definition the structure declaration and the definition can be combined into a single statement: part struct part { int modelnumber; //ID number of widget int partnumber; //ID number of widget part float cost; //cost of part part1, part2 } part1, part2; //definition goes here the variable name part1 is placed at the end of the declaration 56

Structures Within Structures ExampleExample: English system of measurement –Suppose we want to create a program that uses the English system to store distances, then find area of any room. –distances are measured in feet and inches, The length of a living room, for example, might be given as 15’–8”, meaning 15 feet plus 8 inches. –Create struct with two numbers, representing feet and inches. struct Distance //English distance { int feet; float inches; }; –In this program we want to create a data structure that stores the dimensions of a typical room: its length and width. struct Room //rectangular area {Distance length; //length of rectangle Distance width; //width of rectangle }; 57

Structures Within Structures, cont. int main() { Room dining; //define a room dining.length.feet = 13; //assign values to room dining.length.inches = 6.5; dining.width.feet = 10; dining.width.inches = 0.0; //convert length & width float l = dining.length.feet + dining.length.inches/12; float w = dining.width.feet + dining.width.inches/12; //find area and display it cout << “Dining room area is ” << l * w << “ square feet\n” ; return 0; } 58

Initializing Nested Structures diningRoomWrite a definition that initializes the members of dining —which is a variable of type struct Room Room dining = { {13, 6.5}, {10, 0.0} }; 59

Your Turn Your Turn …

Your Turn (1/4) 1. A structure brings together a group of a. items of the same data type. b. related data items. c. integers with user-defined names. d. variables. 3. The closing brace of a structure is followed by a __________. 4. Write a structure specification that includes three variables—all of type int—called hrs, mins, and secs. Call this structure time. 5. True or false: A structure definition creates space in memory for a variable.

Your Turn (2/4) 6. When accessing a structure member, the identifier to the left of the dot operator is the name of a. a structure member. b. a structure tag. c. a structure variable. d. the keyword struct. 7. Write a statement that sets the hrs member of the time2 structure variable equal to Write a definition that initializes the members of time1—which is a variable of type struct time, as defined in Question 4—to hrs = 11, mins = 10, secs = 59.

Your Turn (3/4) 10. True or false: You can assign one structure variable to another, provided they are of the same type. 15. The library function exit() causes an exit from a. the loop in which it occurs. b. the block in which it occurs. c. the function in which it occurs. d. the program in which it occurs.

Your Turn (4/4) 11. Write a statement that sets the variable temp equal to the paw member of the dogs member of the fido variable.

Answers of the questions 1. b, d 2. true 3. semicolon 4. struct time { int hrs; int mins; int secs; }; 5. false; only a variable definition creates space in memory 6. c 7. time2.hrs = 11; 9. time time1 = { 11, 10, 59 }; 10. true 11. temp = fido.dogs.paw; 15.d.

Thanks 66