You are on page 1of 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
0 0 0 0000
1 1 1 0001
2 2 2 0010
3 3 3 0011
4 4 4 0100
5 5 5 0101
6 6 6 0110
7 7 7 0111
8 8 10 1000
9 9 11 1001
A 10 12 1010
B 11 13 1011
C 12 14 1100
D 13 15 1101
E 14 16 1110
F 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 bits = 1 nibble
8 bits = 2 nibble or 1 Byte
210 bytes = 1 Kilo Byte or 1 KB
220 bytes = 1 Mega Byte or 1 MB
230 bytes = 1 Giga Byte or 1 GB
240 bytes = 1 Tera Byte or 1 TB
250 bytes = 1 Peta Byte or 1 PB
260 bytes = 1 Exa Byte or 1 EB
270 bytes = 1 Zetta Byte or 1 ZB
280 bytes = 1 Yotta Byte or 1 YB
290 bytes = 1 Bronto Byte
2100 bytes = 1 Geo Byte
Logic Gates and Bitwise Operators
A B A OR B A AND B A XOR B NOT A NOT B
A|B A&B A^B ~A ~B
0 0 0 0 0 1 1
0 1 1 0 1 1 0
1 0 1 0 1 0 1
1 1 1 1 0 0 0
 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: "; cin >> n;
cout <<n<< "<<1 = " <<(n << 1)<<endl;
cout <<n<< "<<2 = " <<(n << 2)<<endl;
cout <<n<< "<<3 = " <<(n << 3)<<endl;
cout <<n<< "<<4 = " <<(n << 4)<<endl<<endl;
cout <<n<< ">>1 = " <<(n >> 1)<<endl;
cout <<n<< ">>2 = " <<(n >> 2)<<endl;
cout <<n<< ">>3 = " <<(n >> 3)<<endl;
cout <<n<< ">>4 = " <<(n >> 4)<<endl;
system("PAUSE"); return 0;
}
Bitwise Operators
#include <iostream>
#include <iomanip> // for setw()
#include <stdlib.h>
using namespace std;
int main(void) {
short var1 = 0x0035 & 0x000F; // bitwise AND
short var2 = 0x0004 | 0x0068; // bitwise OR
short var3 = 0x0054 ^ 0x00F0; // bitwise XOR
short var4 = ~ 0x0055; // bitwise NOT

cout << setw(4) <<hex<< var1 <<endl


<< setw(4) <<hex<< var2 <<endl
<< setw(4) <<hex<< var3 <<endl
<< setw(4) <<hex<< var4 <<endl;
system("PAUSE");
return 0;
}
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)=" << ( 3 || 0)<<endl; // logical OR
cout << "( -3 || 5)=" << ( -3 || 5)<<endl; // logical OR
cout << "('0' || 0)=" << ('0' || 0)<<endl; // logical OR
cout << endl;
cout << "( 3 && 0)=" <<( 3 && 0)<<endl; //logical AND
cout << "( -3 && 5)=" <<( -3 && 5)<<endl; //logical AND
cout << "('5' && -2)=" <<('5' && -2)<<endl; //logical AND
cout << endl;
cout << "(! 0)=" << ( ! 0 )<<endl; //logical NOT
cout << "(! -3)=" << ( ! -3)<<endl; //logical NOT
cout << "(!'5')=" << ( !'5')<<endl; //logical NOT
system("PAUSE"); return 0;
}
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 statement
 The if statement allows conditional execution.
Its syntax is
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 statement
// This program tests if one positive integer is not
// 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 statement
// demonstrates IF with multiline body
#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 statement
// The Minimum of Three Integers
#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 if…else statement
 The if..else statement causes one of two
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 state-
ments.
 If the value of the condition is nonzero (TRUE)
then statement1 will execute; otherwise (FALSE)
statement2 will execute.
Decision: Using the if…else statement
// demonstrates If…else
#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 statement
// demonstrates If…else
#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 Conditions
// using compound 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) &&( 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 Conditions
// using compound statements
#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 Conditions
// using compound statements
#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 statement
// This program converts a Marks into Grades
#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 statement
// demonstrates switch ... Case
#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 ? : statement
// demonstrates ? :
#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 loop
// prints all the Fibonacci numbers up to an input limit:
#include <iostream>
#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 do…while 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 do…while 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 prime
#include <iostream>
#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 loop
// Writing in Reverse
#include <iostream>
#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 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 ■ 6 5 4 3 2 1
1 2 3 4 5 ■ ■ ■ 5 4 3 2 1
1 2 3 4 ■ ■ ■ ■ ■ 4 3 2 1
1 2 3 ■ ■ ■ ■ ■ ■ ■ 3 2 1
1 2 ■ ■ ■ ■ ■ ■ ■ ■ ■ 2 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 C
A D
A E
A F
A F
A E
A D
A C
A B
A

You might also like