Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1."— Presentation transcript:

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

2 The while loops 2

3 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.

4 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

5 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.

6 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; }

7 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.

8 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 9999. Without prior calculation we don’t know what number will generate a result of this size, so we let the program figure it out.

9 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; }

10 Multiple Statements in a while Loop, cont. 10 Here’s the output:1 2 16 3 81 4 256 5 625 6 1296 7 2401 8 4096 9 6561

11 The precedence of the operators 11

12 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; }

13 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

14  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; }

15 #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; }

16 The Do..while loops 16

17 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);

18 Syntax of do..while 18

19 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.

20 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 }

21 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

22 Revision 22

23 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;

24 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)

25 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.

26 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”;}

27 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";

28 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 100 10- 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);

29 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;} 3- 53 4- 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";

30 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";

31 Answers 10- 2 1 0 11- 2 1 12- 1 2 3 4

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

33 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

34 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.

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

36 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.

37 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; }

38 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: 22229 It’s prime Enter a number: 22231 It’s not prime; divisible by 11

39 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.

40 #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; }

41 The run of the program

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

43

44 The run of the program

45 Structures Chapter 4 - Structures Chapter 4Chapter 4 –Structures

46 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.

47 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

48 Syntax of the Structure Definition

49 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

50 The following figure shows how part1 looks in memory. 50

51 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

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

53 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 = 217.55F; //display structure members cout << “Model ” << part1.modelnumber; cout << “, part ” << part1.partnumber; cout << “, costs $” << part1.cost << endl; } 53

54 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, 217.55F }; //initialize variable part part2; //define variable 54

55 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

56 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

57 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

58 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

59 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

60 Your Turn Your Turn …

61 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.

62 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 11. 9. 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.

63 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.

64 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.

65 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.

66 Thanks 66


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

Similar presentations


Ads by Google