Sie sind auf Seite 1von 43

Introduction to

Programming
Engr. Rashid Farid Chishti
chishti@iiu.edu.pk
Chapter 03: Loops and Decisions

International Islamic University H-10, Islamabad, Pakistan


http://www.iiu.edu.pk

Relational Operators
//demonstrates relational operators
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int n;
cout << "Enter a number: ";
cin >> n;
cout<<n<<"< 10 is "<<(n < 10)<<endl;
cout<<n<<"<=10 is "<<(n <= 10)<<endl;
cout<<n<<"> 10 is "<<(n > 10)<<endl;
cout<<n<<">=10 is "<<(n >= 10)<<endl;
cout<<n<<"==10 is "<<(n == 10)<<endl;
cout<<n<<"!=10 is "<<(n != 10)<<endl;
system("PAUSE"); return 0;
}

Number Systems
Base 16

Base 10

Base 8

Base 2

0000

0001

0010

0011

0100

0101

0110

0111

10

1000

11

1001

10

12

1010

11

13

1011

12

14

1100

13

15

1101

14

16

1110

15

17

1111

Bits and Bytes

All data is represented internally by


computers as sequences of bits.
Each bit can assume the value 0 or 1.
4
8
210
220
230
240
250
260
270
280
290
2100

bits
bits
bytes
bytes
bytes
bytes
bytes
bytes
bytes
bytes
bytes
bytes

=
=
=
=
=
=
=
=
=
=
=
=

1
2
1
1
1
1
1
1
1
1
1
1

nibble
nibble
Kilo
Mega
Giga
Tera
Peta
Exa
Zetta
Yotta
Bronto
Geo

or 1 Byte
Byte
or
Byte
or
Byte
or
Byte
or
Byte
or
Byte
or
Byte
or
Byte
or
Byte
Byte

1
1
1
1
1
1
1
1

KB
MB
GB
TB
PB
EB
ZB
YB

Logic Gates and Bitwise


A B A OR B A AND B A XOR B NOT A NOT B
Operators

A|B

A&B

A^B

~A

~B

0 0

0 1

1 0

1 1

Bitwise Operators in C++ are

Bitwise AND
Bitwise OR
Bitwise Exclusive OR
Bitwise NOT
Left Shift
Right Shift

(
(
(
(
(
(

&
|
^
~
<<
>>

)
)
)
)
)
)

Left Shift( << ) and Right Shift


//demonstrates
( >> ) left shift (<<) and right shift (>>)
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
short n;
cout << "Enter a number: ";
cout <<n<< "<<1 = " <<(n <<
cout <<n<< "<<2 = " <<(n <<
cout <<n<< "<<3 = " <<(n <<
cout <<n<< "<<4 = " <<(n <<
cout <<n<< ">>1 = " <<(n >>
cout <<n<< ">>2 = " <<(n >>
cout <<n<< ">>3 = " <<(n >>
cout <<n<< ">>4 = " <<(n >>
system("PAUSE"); return 0;
}

cin >> n;
1)<<endl;
2)<<endl;
3)<<endl;
4)<<endl<<endl;
1)<<endl;
2)<<endl;
3)<<endl;
4)<<endl;

Bitwise Operators
#include <iostream>
#include <iomanip>
// for setw()
#include <stdlib.h>
using namespace std;
int main(void) {
short var1 = 0x0035 & 0x000F; //
short var2 = 0x0004 | 0x0068; //
short var3 = 0x0054 ^ 0x00F0; //
short var4 = ~ 0x0055;
//
cout << setw(4) <<hex<<
<< setw(4) <<hex<<
<< setw(4) <<hex<<
<< setw(4) <<hex<<
system("PAUSE");
return 0;
}

var1
var2
var3
var4

bitwise
bitwise
bitwise
bitwise

<<endl
<<endl
<<endl
<<endl;

AND
OR
XOR
NOT

Bitwise Operators
//swap two numbers without using extra variable
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int A,B;
cout << "Enter two Numbers: ";
cin >> A >> B;
cout<<"A="<< A <<", B="<< B <<endl;
A = A ^ B; // A XOR B
B = A ^ B;
A = A ^ B;
cout<<"A="<< A <<", B="<< B <<endl;
system("PAUSE");
return 0;
}

Logical Operators: && , || , !


#include <iostream>
#include <stdlib.h>
using namespace std;
int main(void) {
cout << "( 3 || 0)="
OR
cout << "( -3 || 5)="
OR
cout << "('0' || 0)="
OR
cout << endl;
cout << "( 3 && 0)="
AND
cout << "( -3 && 5)="
AND
cout << "('5' && -2)="
AND
cout << endl;
cout << "(! 0)=" << (

<< (

3 ||

0)<<endl; // logical

<< ( -3 ||

5)<<endl; // logical

<< ('0' ||

0)<<endl; // logical

<<(

3 &&

0)<<endl; //logical

<<( -3 &&

5)<<endl; //logical

<<('5' && -2)<<endl; //logical

! 0 )<<endl; //logical NOT

Decision Making in C++

Often, people base their decisions on certain


conditions. For example, a person might go to
a doctor if he feels sick. The decision,
whether to go the doctor, is based on a
certain condition: feeling sick. The same is
true when using programs.
All of the previous programs had sequential
execution: each statement in the program
executes once, and they are executed in the
same order that they are listed.
You can design your program so that it selects
which code to execute based on certain
conditions.

Decision: Using the if


The if statement allows conditional
statement
Its syntax is

execution.

if(condition)
statement;
where condition is an integral expression and
statement is any executable statement.
The statement will be executed only if the value
of the integral expression is nonzero (TRUE).
When we want to run more than one statements
based on some condition, the syntax looks like
this:
if(condition){
many_statement_terminated_with ;
}

Decision: Using the if


// This program tests if one positive integer is not
statement
//
divisible by another:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int n,d;
cout << "Enter two positive integers: ";
cin >> n >> d;
if (n%d)
cout << n << " is not divisible by " << d << endl;
system("PAUSE");
return 0;
}

Decision: Using the if


// demonstrates IF with multiline body
statement
#include
<iostream>
#include <stdlib.h>
using namespace std;
int main(){
int x;
cout << "Enter a number: ";
cin >> x;
if( x > 100 ){
cout << "The number " << x;
cout << " is greater than 100\n";
}
system("PAUSE");
return 0;
}

Decision: Using the if


// The Minimum of Three Integers
statement
#include
<iostream>
#include <stdlib.h>
using namespace std;
int main(){
int n1,n2,n3,min;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
min=n1;
// now min <= n1
if (n2 < min)
min = n2;
// now min <= n1 and min <= n2
if (n3 < min)
min = n3;
// now min <= n1,min <= n2,and min <= n3
cout << "Their minimum is " << min << endl;
system("PAUSE");
return 0;
}

Decision: Using the ifelse


The if..else statement causes one of two
statement
alternative statements to execute depending

upon

whether the condition is true. Its syntax is


if(condition) statement1;
else statement2;
where condition is an integral expression and
statement1 and statement2 are executable statements.
If the value of the condition is nonzero (TRUE)
then statement1 will execute; otherwise (FALSE)
statement2 will execute.

Decision: Using the ifelse


// demonstrates Ifelse
statement
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int x;
cout << "Enter a number: ";
cin >> x;
if( x % 2 )
cout << "This is an Odd Number" <<endl;
else
cout << "This is an Even Number" <<endl;
system("PAUSE");
return 0;
}

Decision: Using Nested if


// Using Nested Selection Statements
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int x,y;
cout << "Enter Value of X: "; cin >> x ;
cout << "Enter Value of Y: "; cin >> y ;
if ( x > 5 ){
if ( y > 5 )
cout << "(X > 5) and (Y > 5 ) \n";
else
cout<<"(X > 5 ) but (Y <= 5 )\n";
}
else
cout << "(Y might be > 5 ) but (X <= 5 ) \n";

system("PAUSE");
return 0;

Decision: Using the else if


// demonstrates Ifelse
statement
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int age;
cout << "Enter your age: ";
cin >> age;
if (age < 18)
cout << "You are a child.\n";
else
if(age < 65)
cout << "You are an adult.\n";
else
cout << "you are a senior citizen.\n";
system("PAUSE"); return 0;
}

Decision: Using compound


// using compound statements
Conditions
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int x,y; cout << "Enter Value of X: "; cin >> x ;
cout << "Enter Value of Y: "; cin >> y ;
if (( x >= 5) &&( y >= 5))
cout << "(X >= 5) and (Y >= 5 ) \n";
if (( x > 5) &&( y < 5))
cout << "(X >= 5) and (Y < 5 ) \n";
if (( x < 5) &&( y >= 5))
cout << "(X < 5) and (Y >= 5 ) \n";
if (( x < 5) &&( y < 5))
cout << "(X < 5) and (Y < 5 ) \n";
system("PAUSE"); return 0;
}

Decision: Using compound


// using compound statements
Conditions
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int n1,n2,n3;
cout << "Enter three integers: ";
cin >> n1 >> n2 >> n3;
if (n1 <= n2 && n1 <= n3)
cout << "Their minimum is " << n1 <<endl;
if (n2 <= n1 && n2 <= n3)
cout << "Their minimum is " << n2 <<endl;
if (n3 <= n1 && n3 <= n2)
cout << "Their minimum is " << n3 <<endl;
system("PAUSE");
return 0;
}

Decision: Using compound


// using compound statements
Conditions
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
char ans;
cout << "Are you enrolled (y/n): ";
cin >> ans;
if (ans == 'Y' || ans == 'y')
cout << "You are enrolled.\n";
else
cout << "You are not enrolled.\n";
system("PAUSE"); return 0;
}

Decision: Using the else if


// This program converts a Marks into Grades
statement
#include
<iostream>
#include <stdlib.h>
using namespace std;
int main(){ int score;
cout << "Enter your Marks in Subject: "; cin >> score;
if(score>100) cout<<"Error: Marks Can not be > 100\n";
else if (score >= 80) cout << "Your grade is [A] \n";
else if (score >= 75) cout << "Your grade is [B+] \n";
else if (score >= 70) cout << "Your grade is [B] \n";
else if (score >= 65) cout << "Your grade is [C+] \n";
else if (score >= 60) cout << "Your grade is [C] \n";
else if (score >= 55) cout << "Your grade is [D+] \n";
else if (score >= 50) cout << "Your grade is [D] \n";
else if (score >= 0) cout << "Your grade is [F] \n";
else cout << "Error: Marks can not be less than 0.\n";
system("PAUSE"); return 0; }

Assignment #3
1. White a program to calculate the GPA in
First semester.
The program asks the marks out of 100 in
each subject and calculates GPA.
It also calculates the percentage marks
in the first semester.
Output should be like this

Decision: Using the switch


// demonstrates switch ... Case
statement
#include
<iostream>
#include <stdlib.h>
using namespace std;
int main(){
int x,y;
char op;
cout << "Enter two integers: "; cin >> x >> y;
cout << "Enter an operator [+,-,*,/,%]: "; cin >> op;
switch (op){
case '+': cout << x + y << endl; break;
case '-': cout << x - y << endl; break;
case '*': cout << x * y << endl; break;
case '/': cout << x / y << endl; break;
case '%': cout << x % y << endl; break;
default: cout <<"Invalid Operator \n";
}
system("PAUSE"); return 0; }

Decision: Using the ? :


// demonstrates ? :
statement
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int m,n;
cout << "Enter two integers: ";
cin >> m >> n;
cout << ( m < n ? m : n ) << " is the minimum. \n";
system("PAUSE");
return 0;
}
// The conditional expression ( m<n ? m : n ) evaluates
// to m if m < n, and to n otherwise.

Loops

Loops cause a section of your program to be


repeated a certain number of times.
The repetition continues while a condition is
true.
When the condition becomes false, the loop
ends and control passes to the statements
following the loop.
There are three kinds of loops in C++:

the for loop,


the while loop,
and the do...while loop.

while loop
// Using Compound Statements
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int x,loop_count=0;
cout << "How much counting you want? ";
cin >> x ;
while(loop_count <= x)
{
cout << loop_count <<" ";
loop_count++;
}
system("PAUSE");
return 0;
}

while loop
// computes the sum 1 + 2 + 3 + + n,
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int last_no, sum = 0, current_no = 1;
cout << "Enter a Positive Number: ";
cin >> last_no;
cout << "0";
while (current_no <= last_no){
sum = sum + current_no;
cout << "+" << current_no;
current_no++;
}
cout << " = " << sum <<endl;
system("PAUSE");
return 0;
}

Using break to terminate a loop


#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int last_no,sum=0, current_no=1;
cout << "Enter a Positive Number: ";
cin >> last_no;
cout << "0";
while (true){
if (current_no > last_no)
break; // terminates the loop immediately
sum = sum + current_no;
cout<<"+"<<current_no;
current_no++;
}
cout << " = " << sum <<endl;
system("PAUSE"); return 0;
}

Using break to terminate a


// prints all the Fibonacci numbers up to an input limit:
loop<iostream>
#include
#include <stdlib.h>
using namespace std;
int main(){
long bound;
cout << "Enter a positive integer: "; cin >> bound;
cout << "Fibonacci numbers < " << bound << " = 0,1";
long f0=0,f1=1;
while (true){
long f2 = f0 + f1;
if (f2 > bound)
break; // terminates the loop immediately
cout << "," << f2;
f0 = f1; f1 = f2;
}
cout<<endl; system("PAUSE"); return 0;
}

Using dowhile loop


#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
unsigned char choice=0;
do
{
cout<<"\n Do U want exit [y,n]:";
cin >>choice;
}
while (choice!='y' && (choice!='Y'));
cout << "\n Bye Bye \n" ;
system("PAUSE");
return 0;
}

Using dowhile loop


#include <iostream>
#include <stdlib.h>
using namespace std;
int 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 << "\n Do another? (y/n): "; //do it again?
cin >> ch;
}
while( ch != 'n' );
// loop condition
return 0;
}

Using for loop


#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n; long sum = 0;
for(int i=1; i <= n; i++)
sum = sum + i;
cout << "The sum of the first " << n
<< " integers is " << sum <<endl;
system("PAUSE");
return 0;
}

Using for loop


#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
int main()
{
int n, i=1;
cout << "Which Table: ";
cin >> n;
for( ; i <= 20; i++)
cout << setw(3) << i << "*" << n << " =
<< setw(3) << i*n << endl;
system("PAUSE");
return 0;
}

"

Using for loop


// Calculating factorial
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
unsigned long n, i, fact=1;
cout << "n!: ";
cin >> n;
if( n < 0 )
exit(0);
for( i=1 ; i <= n; i++)
fact = fact*i;
cout << n << "! = " << fact << endl;
system("PAUSE");
return 0;
}

Using for loop to calculate


#include <iostream>
prime
#include
<stdlib.h>
using namespace std;
int main(){
long n; cout << "Enter a positive integer: "; cin >> n;
if (n < 2) cout << n << " is not prime." << endl;
else if (n < 4) cout << n << " is prime." << endl;
else if (n%2 == 0) cout << n << " = 2*" << n/2 << endl;
else{
for (int d=3; d <= n/2; d += 2)
if (n%d == 0){
cout << n << " = " << d << "*" << n/d << endl;
system("PAUSE"); exit(0);
}
cout << n << " is prime." << endl;
}
system("PAUSE"); return 0;
}

Finding Reverse using while


// Writing in Reverse
loop<iostream>
#include
#include <stdlib.h>
using namespace std;
int main(){
long m, d , n = 0;
cout << "Enter a positive integer: "; // e.g. 123456
cin >> m;
while ( m > 0 ){
d = m % 10; // d will be the right-most digit of m
m /= 10;
// then remove that digit from m
n = 10*n + d; // and append that digit to n
}
cout << "The reverse is " << n << endl;
system("PAUSE"); return 0;
}

Using continue and break


// Using Writing in Reverse
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
int n;
for (;;){
cout << "Enter int: "; cin >> n;
if (n%2 == 0)
continue; // Stay in Loop
if (n%3 == 0)
break;
// Come out of loop
cout << "\n I m in loop \n";
}
cout << "\n I m outside of loop \n";
system("PAUSE"); return 0;
}

Assignment #4
1. Write a program that prints the minimum
of four input integers.
2. Write a program that finds the median of
three input integers.
3. Write a program to find the min of 3
numbers using ? : operator
4. Using a while loop write a program to
Compute a Sum of Reciprocals of first n
numbers This program computes the sum of
reciprocals s = 1 + 1/2 + 1/3 + 1/3 + +
1/n,
5. Using nested for loops write a program to
show all prime numbers in range given by
user.
6. Write a program using do..while loop to
compute the sum of the first n squares,
where n is input.

Assignment #4
7. Write a program to print out all
Armstrong numbers between 1 and 500. If
sum of cubes of each digit of the number
is equal to the number itself, then the
number is called an Armstrong number.
For example:
153 = (1*1*1) + (5*5*5) + (3*3*3)
8. Write a program to produce the following
output using loops:
1
1
1
1
1
1
1

2
2
2
2
2
2

3
3
3
3
3

4
4
4
4

5
5
5

6
6

6
6

5
5
5

4
4
4
4

3
3
3
3
3

2
2
2
2
2
2

1
1
1
1
1
1
1

Assignment #4
9. Write a program to produce
the following output
using loop:*
*
* *
* *
*

*
*
*
*
*
*

*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*
*
*

*
*
*
*
*
*
*
*

*
*
*
*
*
*

*
* *
* *
*

Assignment #4
10.Write a program to produce the following
output using for loop:A
A B
A B C
A B C D
A B C D E
A B C D E F
A B C D E F
A B C D E
A B C D
A B C
A B
A

Assignment #4
11. Write a program to produce the following output using
loop:A
A B
A

A
A

F
F
A

E
A

D
A

C
A B
A

Das könnte Ihnen auch gefallen