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

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

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

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

Outlines

• Chapter 3 – Chapter 3 – Loops & Revision– Loops

• while• do … while

– revision

1

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

The while loops2

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

The while loops3

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

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

The while loops

while (expression)

statement(s)

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

4

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

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.

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

Example 1, cont.6

// endon0.cpp// demonstrates WHILE loop#include <iostream>using namespace std;int main(){int n = 99; // make sure n isn’t initialized to 0while( n != 0 ) // loop until n is 0

cin >> n; // read a number into ncout << endl;return 0;}

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

The syntax of the while loop7

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

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

Multiple Statements in a while Loop8

• Example 2Example 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.

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

Multiple Statements in a while Loop, cont.9

#include <iostream>#include <iomanip> //for setwusing namespace std;int main(){int pow=1; //power initially 1int numb=1; //numb goes from 1 to ???while( pow<10000 ) //loop while power <= 4 digits{

cout << setw(2) << numb; //display numbercout << setw(4) << pow << endl; //display fourth power++numb; //get ready for next powerpow = numb*numb*numb*numb; //calculate fourth power

}cout << endl;return 0;}

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

Multiple Statements in a while Loop, cont.10

• Here’s the output:1 12 163 814 2565 6256 12967 24018 40969 6561

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

The precedence of the operators11

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

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

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

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

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

Write a program for computing factorial N (N!), Where N! = 1 *2 * 3 * N.

#include <iostream>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;

}

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

#include <iostream>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;

}

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

The Do..while loops16

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

Control Structures--do…while loops17

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

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

Syntax of do..while18

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

Example 419

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

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

Example 4, cont.20 #include <iostream>

using namespace std;void main(){long dividend, divisor;char ch;do //start of do loop{ //do some processingcout << “Enter dividend: “; cin >> dividend;cout << “Enter divisor: “; cin >> 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}

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

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

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

Revision22

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

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;

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

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 < 10) || (x < y)) && (count >= 0) )» h. ((limit / count) > 7) || (limit < 20)» i. (limit < 20) || ((limit / count) > 7)» j. ((limit / count) > 7) && (limit < 0)» k. (limit < 0) && ((limit / count) > 7)) + (!6)

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

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 .

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

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

elsecout << "1 is false";

cout << “ try again”;

c. if(-1)cout << "-1 is true";

else{cout << "-1 is false";

cout << “ try again”;}

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

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

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

elsecout << "Hello from the else.\n";

cout << "End again\n";

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

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 < 0 or 0 … n … 100 or 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;docout << n << " ";while (n++ <= 3);

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

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";elsecout << "OK";

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

Answers • 7- All nonzero integers are converted to true ; 0 is converted to false .

a. 0 is false try againb. 1 is true try againc. -1 is true

• 8- StartHello from the second if.EndStart againEnd again

• 9- Both of the following are correctif (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";elsecout << n << " is larger than 100.\n";

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

Answers

• 10- 2 1 0

• 11- 2 1

• 12- 1 2 3 4

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

Lecture 7

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

Selection Structure33

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

Flow of Control StatementsThree 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

34

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

Selection Structure35

• C++ provides three types of selection statements:1. The if selection statement either

• performs (selects) an action if a condition (predicate) is true or

• skips the action if the condition is false.2. The if…else selection statement

• performs an action if a condition is true or • performs a different action if the condition is false.

3. The switch selection statement performs one of many different actions, depending on the value of an integer expression.

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

Precedence: Arithmetic and Relational Operators36

• Example 3Example 3: : Fibonacci series, the first few terms of the series are:

1 1 2 3 5 8 13 21 34 55• Each term is found by adding the two previous

ones:

1+1 is 2,

1+2 is 3,

2+3 is 5,

3+5 is 8, and so on.

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

Precedence: Arithmetic and Relational Operators, cont.

37

#include <iostream>using namespace std;int main(){ //largest unsigned longconst unsigned long limit = 4294967295;unsigned long next=0; //next-to-last termunsigned long last=1; //last termwhile( next < limit / 2 ) //don’t let results get too

big{

cout << last << “ “; //display last termlong sum = next + last; //add last two termsnext = last; //variables move forwardlast = sum; // in the series

}return 0;}

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

Precedence: Arithmetic and Relational Operators, cont.38

• The test expression uses two operators:

(next < limit / 2)

Our intention is to compare next with the result of limit/2.

• arithmetic operators have a higherhigher precedence than relational operators.

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

Nesting If Statement & Loops

39

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

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.

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

Nesting ifs Inside Loops, cont.#include <iostream>using namespace std;#include <process.h> //for exit()int main(){

unsigned long n, j;cout << “Enter a number: “;cin >> n; //get number to testfor(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;

}

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

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

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

Your Turn43

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

Your Turn (1/2)44

• 10. Write a while loop that displays the numbers from 100 to 110.

• 11. True or false: Relational operators have a higher precedence than arithmetic operators.

• 13. Write a do loop that displays the numbers from 100 to 110.

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

Your Turn (2/2)45

• 14. Write an if statement that prints Yes if a variable age is greater than 21.

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

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

H.W.46

• Write a program that uses a while statement to calculate the factorial. The FACTOR program asks the user to type in a number, and then calculates the factorial of this number. The factorial is calculated by multiplying the original number by all the positive integers smaller than itself. Thus the factorial of 5 is 5*4*3*2*1, or 120.

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

ThanksThanks

47