Anda di halaman 1dari 70

Loops in c++

Dr Ahmed Telba

b = 3;
a = ++b;
// a = 4 , b = 4
b = 3;
a = b++ ;
// a = 3 , b = 4

Constant

#include<iostream>
using namespace std;
#define pi 3.14159265
int main()
{
float R ,r ;
r = 0 ;//initial to 0
cout<<"enter circle radius plz: ";
cin>> r ;
cout<< "circle area = "
<< 0.5 * pi * r * r << endl;
return 0 ;
}

#include<iostream>
using namespace std;
const double pi = 3.14159265;
int main()
{
float r ;
r = 0 ;//initial to 0
cout<<"enter circle radius plz: ";
cin>> r ;
cout<< "circle area = "
<< 0.5 * pi * r * r << endl;
return 0 ;
}

Relational operators
Here are the relational operators, as they
are known, along with examples:
>
greater than
5 > 4 is TRUE
<
less than
4 < 5 is TRUE
>= greater than or equal
4 >= 4 is
TRUE
<= less than or equal
3 <= 4 is TRUE
== equal to
5 == 5 is TRUE
!= not equal to
5 != 4 is TRUE

Logical operation
&& AND
|| OR ,
! NOT

if Selection Structure
Translation into C++
If students grade is greater than or equal to 60
Print Passed
if ( grade >= 60 )
cout << "Passed";

Diamond symbol (decision symbol)


Indicates decision is to be made
Contains an expression that can be true or false
Test condition, follow path

if structure
Single-entry/single-exit
8

2.5if Selection Structure


Flowchart of pseudocode statement

grade >=
60
false

true

print Passed

A decision can be made on


any expression.
zero - false
nonzero - true
Example:
3 - 4 is true

2.6if/else Selection
Structure
if
Performs action if condition true

if/else
Different actions if conditions true or false

Pseudocode
if students grade is greater than or equal to 60
print Passed
else
print Failed

C++ code
if ( grade >= 60 )
cout << "Passed";
else
cout << "Failed";
10

2.6if/else Selection
Ternary conditional
operator (?:)
Structure

Three arguments (condition, value if


true, value if false)

Code could be written:


cout << ( grade >= 60 ? Passed : Failed );
Condition

false
print Failed

11

Value if true

grade >= 60

Value if false

true
print Passed

2.6if/else Selection
Structure
Nested if/else structures
One inside another, test for multiple cases
Once condition met, other statements skipped
if students grade is greater than or equal to 90
Print A
else
if students grade is greater than or equal to 80
Print B
else
if students grade is greater than or equal to 70
Print C
else
if students grade is greater than or equal to 60
Print D
else
Print F
12

2.6if/else Selection
Structure
Example
if ( grade >= 90 )
cout << "A";
else if ( grade >= 80 )
cout << "B";
else if ( grade >= 70 )
cout << "C";
else if ( grade >= 60 )
cout << "D";
else
cout << "F";

13

// 90 and above
// 80-89
// 70-79
// 60-69
// less than 60

2.6if/else Selection
Structure
Compound statement
Set of statements within a pair of braces
if ( grade
cout <<
else {
cout <<
cout <<

>= 60 )
"Passed.\n";
"Failed.\n";
"You must take this course again.\n";

Without braces,
cout << "You must take this course again.\n";

always executed

Block
Set of statements within braces
14

2.7while Repetition
Structure
Repetition structure
Action repeated while some condition remains
true
Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list

while loop repeated until condition becomes


false

Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
15

2.7The while Repetition


Structure
Flowchart of while loop
product <= 1000

false

16

true
product = 2 * product

2.8Formulating Algorithms (CounterControlled Repetition)


Counter-controlled repetition
Loop repeated until counter reaches certain
value

Definite repetition
Number of repetitions known

Example
A class of ten students took a quiz. The
grades (integers in the range 0 to 100) for
this quiz are available to you. Determine the
class average on the quiz.
17

condition ? result1 : result2

*/
#include <iostream>
using namespace std;
int main( )
{
int x=100;
if ( x == 100 )

//if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
}

#include <iostream>
using namespace std;
int main()
// Most important part of the
program!
{
int x = 3;
cout << " value of x ";
cin>>x;
if (x % 2)
cout << " number is odd"" ";
else
cout << "number is even
" ;}

#include <iostream>
using namespace std;
int main()
{
int x=6;
int y=3;
if (x != 5 && y<= 3)
{
cout << "condition true" << endl;
}
cout << "value of y after short circuit: " << y << endl;

if (x == 5 && y++ >= 3)

cout << "value of y without short circuit: " << y << endl;

}
}

#include <iostream>

using namespace std;


int main()
{
int age;

// Most important part of the program!


// Need a variable...

cout<<"Please input your age: "; // Asks for age


cin>> age;
// The input is put in age
if ( age <= 50 ) {
// If the age is less than 50
cout<<"You are pretty young!\n"; // Just to show you it works...
}
else if ( age <= 70 ) {
// I use else just to show an example
cout<<"You are old\n";
// Just to show you it works...
}
else {
cout<<"You are really old\n";
// Executed if no other statement is
}
}

using namespace std


/*This is a comment that spans
three lines. Note that there is no comment
symbol of any kind on the second line.*/

#include <iostream>
using std::cin;
using std::cout;
using std::endl;
instead of
#include <iostream>
using namespace std;

Selection structures
Selection structures
if, ifelse, switch
Repetition structures
while, dowhile, for
Sequence structure
Programs executed sequentially by default

Selection structures
if, if/else, switch

Repetition structures
while, do/while, for

#include <iostream>
using namespace std;
int main( )
{
int number1, number2;
cout << "Enter two whole numbers: ";
cin >> number1 >> number2;
cout << number1 << " divided by " << number2
<< " equals " << (number1/number2) << "\n"
<< "with a remainder of " << (number1%number2)
<< "\n";
return 0;
}

#include<iostream>
using namespace std;
int main()
{
int x;
cout << "enter value of x =";
cin>>x;
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";
}

//while
//while ( condition ) statements

#include <iostream>
using namespace std;
int main ()
{
int n = 10 ;
while (n>0)
{
cout<< n << ", ";
n--;
}
cout<< "FIRE!";
return 0;
}

) (

#include <iostream>
using namespace std;
int main()
{
int n = 10 ;
do
{
cout << n << ", ";
n--;
} while (n>0);
cout << "FIRE!";
return 0;
}

for (initialization ; condition ; increase)


statement;
#include <iostream>
using namespace std;
int main ()
{
for ( int n=10 ; n>0 ; n-- )
{
cout << n << ", ";
}
cout << "Fire!";
return 0;
}

//Enter value until you enter 0 return o end loop


#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
while(n != 0)
{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " <<n<< "\n";
}
return 0;
}

continue; & break;

#include <iostream>
using namespace std;
int main()
{
for (int n=10; n>0;n--)
{
if (n==5)
//continue;
break;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

// switch case
#include<iostream>
using namespace std;
int main()
{ unsigned short dnum ;
cout<< "Enter number of day(1-7): ";
cin>> dnum;
cout<< "\n";
switch(dnum){
case 1: // if dnum = 1
cout << "the day is Friday";
break;
case 2: // if dnum = 2
cout << "the day is Saturday";
break;
case 3: // if dnum = 3
cout << "the day is Sunday";
break;
case 4: // if dnum = 4
cout << "the day is Monday";
break;
case 5: // if dnum = 5
cout << "the day is Tuesday";
break;
case 6: // if dnum = 6
cout << "the day is Wednesday";
break;
case 7: // if dnum = 7
cout << "the day is Thursday";
break;
default: // if dnum < 1 or dnum> 7
cout << "Sorry we're closed its not listed ";
break;
} cout<< "\n"; return 0; }

//if else
#include<iostream>
using namespace std;
int main()
{
unsigned short dnum ;
cout<< "Enter number of day(1-7): ";
cin>> dnum;
cout<< "\n";
if(dnum == 1)
cout << "the day is Friday";
else if(dnum == 2)
cout << "the day is Saturday";
else if(dnum == 3)
cout << "the day is Sunday";
else if(dnum == 4)
cout << "the day is Monday";
else if(dnum == 5)
cout << "the day is Tuesday";
else if(dnum == 6)
cout << "the day is Tuesday";
else if(dnum == 7)
cout << "the day is Thursday";
else
cout << "Sorry we're closed ";
cout<<'\n';
return 0;
}

nested loops
// nested loop
#include <iostream>
using namespace std;
int main ()
{
for( int i = 1 ; i<=3 ; i++){
for(int j = 1 ; j<=5 ; j++)
cout << j << " ";
cout<<"\n";
}
return 0;
}

find minimum number


// find minimum number
#include<iostream>
using namespace std;
int main()
{
int n, a, min;
cout<<"Enter n: ";
cin>>n;
cout<<"\nEnter number 1: ";
cin>>a;
min = a;
for(int i =2 ; i <=n;i++)
{
cout<<"\nEnter number "<<i<<": ";
cin>>a;
if(a<min)
min = a;
}
cout<<"\nmin = "<< min << endl;
return 0;
}

//Write program to compute the polynomial


#include<iostream>
using namespace std;
int main()
{
int n ;
float a = 0.0f ;//Initial a to 0 where f means float value
cout<<"Enter n: ";
cin>>n;
for(int i=1 ; i<=n;i++)
a+= 1.0f/I ;
//like a = a + (float)1/i;
cout<< a << endl;
return 0;
}

// average value

#include<iostream>
using namespace std;
int main()
{
float sum =0 , average=0 , a=0;
int n;
cout<<"Enter n: ";
cin>>n;
for(int i =1 ; i<=n;i++)
{
cout<<"Enter a"<<i<<" : ";
cin>>a;
sum += a;
}
average = sum / n;
cout<<"\nAverage = "<<average;
return 0;
}

while loop statement


A while loop statement repeatedly executes a target statement as long as a
given condition is true.
Syntax:
The syntax of a while loop in C++ is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The
condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true.
When the condition becomes false, program control passes to the line
immediately following the loop.

Example:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;
// while loop execution
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}

for loop

A is a repetition control structure that allows you to efficiently write a loop


that needs to execute a specific number of times.
Syntax:
The syntax of a for loop in C++ is:
for ( init; condition; increment )
{
statement(s);
}
Here is the flow of control in a for loop:

The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to put
a statement here, as long as a semicolon appears.

Next, the condition is evaluated. If it is true, the body of the loop is


executed. If it is false, the body of the loop does not execute and flow of
control jumps to the next statement just after the for loop.

After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop
control variables. This statement can be left blank, as long as a semicolon
appears after the condition.

Syntax:
The syntax of a do...while loop in C++ is:

do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so
the statement(s) in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the
statement(s) in the loop execute again. This process repeats until the
given condition becomes false.
Flow Diagram:

Do while

Example:
#include <iostream>
using namespace std;
int main ()
{
// for loop execution
for( int a = 10; a < 20; a = a + 1 )
{
cout << "value of a: " << a << endl;
}
return 0;
}

Example:

#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a = 10;

// do loop execution
do
{
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 20 );
return 0;

The Infinite Loop:


A loop becomes infinite loop if a condition never becomes false. The for loop is
traditionally used for this purpose. Since none of the three expressions that form the
for loop are required, you can make an endless loop by leaving the conditional
expression empty.
#include <iostream>
using namespace std;
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}

Chapter 3
Control Structures: Selection

#include <iostream>
using namespace std;
int main( )
{
cout << "Read the preface. You may prefer\n"
<< "a more elementary book by the same
author.\n";

cout << "17 divided by 5 is " << (17/5) << "\n";


cout << "with a remainder of " << (17%5) << "\n";}

#include <iostream>
using namespace std;
int main( )
{
char a,b,c;
a='b';
b='c';
c=a;
cout<< a << b <<c<< 'c';
}

count, and endl, you might start your


program with the following:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;

THE AND OPERATOR, &&


if ( (score > 0) && (score < 10) )
cout << "score is between 0 and
10.\n";
else
cout << "score is not between 0 and
10.\n";

Structured Programming
Algorithm Development
Conditional Expressions
Selection Statements
Loops

Structured Programming
Sequence
Sequence of steps performed one after another
Selection
Condition evaluated as true or false
if true, one set of statements executed
if false, another set of statements executed
Repetition
Repeat (loop through) a set of steps
As long as a condition is true

Flowchart Symbols

Sequence

Selection

Repetition

Conditional Expressions

Operator Precedence

Examples

a = 5.5
b = 1.5
k=3
a + b >= 6.5
b-k>a
a < 10 && a > 5

Selection Statements

Conditional Operator

if/else Statement
if (a<b)
count++;
else
c = a + b;
Conditional Statement
a<b ? count++ : c = a + b;

If dist is less than 50.0 and time is greater than


10.0,
then increment time by 2; otherwise, increment
time
by 2.5.
if (dist < 50.0 && time > 10.0)
time+=2;
else
time+=2.5;

Nested if/else Statements

if (code == 10)
cout << "Too hot - turn off." << endl;
else
if (code == 11)
cout << "Caution - recheck in 5 min." << endl;
else
if (code == 13)
cout << "Turn on fan." << endl;
else
cout << "Normal." << endl;

//Equivalent switch Statement


switch (code)
{
case 10:
cout << "Too hot - turn off." << endl;
break;
case 11:
cout << "Caution - recheck in 5 min." << endl;
break;
case 13:
cout << "Turn on fan." << endl;
break;
default:
cout << "Normal." << endl;
}

//If rank equals 1 or 2 then print "Low",


else if rank equals
3 or 4 then print
"High", otherwise
print "Error".
switch (rank)
{
case 1:
case 2:
cout << "Low" << endl;
break;
case 3:
case 4:
cout << "High" << endl;
default:
cout << "Error" << endl;
}

Anda mungkin juga menyukai