while - Future Academy

Download Report

Transcript while - Future Academy

1
Outlines
• Chapter 3 – Loops & Revision
– Loops
• while
• do … while
– revision
2
The while loops
3
The while loops
• 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
4
while (expression)
statement(s)

A while loop will continue executing as long as
expression evaluates to a non-zero value (true) .
5
Example 1
• 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.
// endon0.cpp
// demonstrates WHILE loop
#include <iostream>
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
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
• 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.
#include <iostream>
#include <iomanip> //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.
• Here’s the output:
1
1
2
16
3
81
4
256
5
625
6
1296
7
2401
8
4096
9
6561
11
The precedence of the operators
12
while statement equivalent to for
statement
• 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.
13

How do you print your name 10 times using a while loop?
int x = 0;
while (x < 10)
{
cout << “Ahmed” << endl;
x++;
}

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;
}
#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;
}
16
The Do..while loops
Control Structures--do…while loops
17
do
{
statements;
} while (expression);

A do..while loop is very similar to a regular while loop.

Terminating condition is specified at the end of the loop
Syntax of do..while
18
19
Example 4
• 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 <iostream>
using namespace std;
void main()
{
long dividend, divisor;
char ch;
do
//start of do loop
{
//do some processing
cout << “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
}
21
Example 4, cont.
• 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
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 < 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)
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 < 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;
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;}
• 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";
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
• 8Start
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 (n <= 100)
cout << n << " is between 0 and 100.\n";
else
cout << n << " is larger than 100.\n";
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";
Answers
• 10- 2 1 0
• 11- 2 1
• 12- 1 2 3 4
Lecture 7
33
Selection Structure
Flow of Control Statements
34
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
Selection Structure
35
• 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.
36
Precedence: Arithmetic and
Relational Operators
• Example 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.
37
Precedence: Arithmetic and
Relational Operators, cont.
#include <iostream>
using namespace std;
int main()
{
//largest unsigned long
const unsigned long limit = 4294967295;
unsigned long next=0;
//next-to-last term
unsigned long last=1;
//last term
while( next < limit / 2 )
//don’t let results get too big
{
cout << last << “ “;
//display last term
long sum = next + last;
//add last two terms
next = last;
//variables move forward
last = sum;
// in the series
}
return 0;
}
38
Precedence: Arithmetic and
Relational Operators, cont.
• 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 higher
precedence than relational operators.
Nesting If Statement & Loops
39
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 <iostream>
using namespace std;
#include <process.h>
//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: 22229
It’s prime
Enter a number: 22231
It’s not prime; divisible by 11
43
Your Turn
44
Your Turn (1/2)
• 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.
45
Your Turn (2/2)
• 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.
46
H.W.
• 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.
Thanks
47