www.aabu.edu.jo/~wael
C++ Program
A sequence of structured statements written by
programmer using C++ language to solve a problem.
Using Visual ...
General form of C++ Program
#include <iostream.h>
void main() {
.
.
C++ statements
.
.
}
Remark: C++ language is case sens...
Problem : Compute and print the summation
of two numbers.
Program
#include <iostream.h>
void main() {
int a, b, s;
cout<<"...
Remarks:
- iostream.h: C++ library that contains all
input/output statements and other constrols.
- main(): the main funct...
Variables
• Variables:
- Variable is one memory location.
-The name of the location is the variable name.
-The location co...
Predefined Data Types:
• int : values (e.g. 5 , -321 , 12)
operations (e.g. + , - , * , / , % , >, <, = =, !=, > =, <= )
•...
Constant Values: can be numerical (3, 100, -5,
3.14) or string (‘A’, ‘$’, ‘Ahmad’, Amman).
Constant identifier: one memory...
Variable names
• int X,x,Number, IF,If,iF,a7,Total_sum;
• float _abc;
Problem : Compute and print the average of
three numbers.
Program
#include <iostream.h>
void main() {
int n1, n2, n3;
floa...
Problem : Compute the area of the circle.
Where area = π x R2
Program
#include <iostream.h>
void main() {
const double Pi ...
Examples on integer division
#include <iostream.h>
void main( )
{
int x;
x=1/3*3; // 1/3=0
cout<<x<<endl;
x=1.0/3*3;
cout<...
Boolean variables and relational
operations
#include <iostream.h>
void main( )
{
bool x,y;
x= 5 > 7;
cout<<x<<endl;
y= 5 <...
Misleading examples
X= 7 > 5 > 3;
This expression gives false because its evaluated
as follows
X=(7>5) >3;
= 1 > 3; // Fal...
Priority
• * , / , % have the same priority ( High )
• + , - have the same priority (Low)
Examples on arithmetic operations
X= 5 + 2 * 3 – 7;
The order of execution is as follows:
* , then + , then -
X= 5 + 2 * 3...
If Statement in C++
One way if
if ( Condition )
statement;
if ( Condition ) {
statements; }
Problem : Read any number from the user,
then print positive if it is positive.
Program
#include <iostream.h>
void main() ...
Another Version
#include <iostream.h>
void main() {
int Num;
bool w;
cout<<"n Please Enter an integer number:";
cin>>Num;
...
If Statement in C++
Two way if
if ( Condition )
statement;
else
statement;
if ( Condition ) {
statements; }
else {
stateme...
Write a program that reads a mark,
if mark is 60 or greater, the program
prints PASS, else it will print FAIL
#include <io...
More than one statement in the if
#include <iostream.h>
void main() {
int mark;
cout<<"n Please Enter your mark: ";
cin>>m...
Write a program that prints the
fraction a/b in the form c d/b
Example: 7/3 = 2 1/3
#include <iostream.h>
void main ( )
{
...
Enhancement on the previous example
#include <iostream.h>
void main ( )
{
int a,b,c,d;
cout<<“To convert the fraction from...
Condition
Condition: An expression that is evaluated to
produce only true or false values.
Arithmetic Expressions
- It is ...
Relational Expressions
- It is composed from operands and operators.
- Operands may be numbers and/or identifiers
that hav...
Logical Expressions
- It is called also Boolean expression.
- It is composed from operands and operators.
- Operands are i...
Evaluating Logical
Expressions
• The truth table
(1) AND table
&& True False
True True False
False False False
(2) OR table
|| True False
True True True
False True False
(3) NOT table
! True False
False True
Arithmetic  Relational  Logical
• NOTES
1) A relational expression may contain arithmetic sub
expressions,
e.g. ( 3 + 7 ...
Operator Precedence
Operator Description Precedence
( ) parentheses Highest
+, – , ! unary plus, unary minus,
Not
*, /, %
...
Examples
• Find the value of the following expression:
(1) 5 + 8 * 2 / 4
16
4
9 (This is the final result)
Find the value of the following expression
( 9 + 3 ) - 6 / 3 + 5
12
2
10`
15 (this is the final result)
Find the value of the following Expression
If x = True, y = False, z = False, find the value of the
expression x && y || z...
Another example
• X=true, Y=false, Z= true
X || Y && Z
true
• X=true, Y=false, Z= false
X || Y && Z
true
If a = 3, b = 5, x = true, y = false, find the value of the
expression: ( a < b ) AND y OR x
( a < b ) && y || x
True
Fals...
What is the output of the following code:
Program
#include <iostream.h>
void main() {
int a=10, b=3;
cout<<"n a+b= t"<<a+b...
Problem : Read any number from the user,
then print positive if it is positive and print
negative otherwise.
Program
#incl...
Problem : Read Two numbers from the user,
then print the greatest one.
Program
#include <iostream.h>
void main() {
int x,y...
Problem : Read three numbers to print the
smallest one.
Program
#include <iostream.h>
void main() {
int a, b, c;
cout<<"nP...
Program2 (Nested if)
#include <iostream.h>
void main() {
int a, b, c;
cout<<"nPlease Enter three numbers:";
cin>>a>>b>>c;
...
Problem : Read number, if it is positive, Add
number 10 to it and print the Number “is positive”, but
otherwise, subtract ...
Example on dangling else
if ( x>y)
if ( x<z)
cout<<“ Hello”;
else
cout<<“Hi”;
Another idea
if ( x>y)
{if ( x<z)
cout<<“ Hello”;}
else
cout<<“Hi”;
Assignment Statement
Simple Assignment:
Max = 5 ;
Max = A ;
F = A+B*2;
Compound Assignment:
A += 10 ;  A = A + 10;
A -= C...
Increment and Decrement
Postfix
C++;  use the value of C, then increment (C = C+1) it.
C--;  use the value of C, then de...
What is the output of the following C++
Source Code
Program#include <iostream.h>
void main( ) {
int A=10, B=4, R;
cout<<"A...
Examples
X=5;
Y=7;
Z=X++ + Y; // Z=X+Y; X=X+1;
cout<<X<<“ “<<Y<<“ “<<Z<<endl;
Z=++X +Y; // X=X+1; Z=X+Y;
cout<<X<<“ “<<Y<<...
Loop (iteration statements)
used to repeat subcode number of times
there three loop techniques:
1- for Loop.
2- while Loop...
For Loop Technique
General Form:
for (counter_var=initial_val; condition; increasing or decreasing counter_var)
{
.
Statem...
Problem : Print the word “Amman” five
times.
Program
#include <iostream.h>
void main( ) {
for (int i=1; i<=5; i++)
cout<<"...
Problem : Print the following numbers.
1 3 5 7 9 11
Program
#include <iostream.h>
void main( ) {
for (int k=1; k<=11; k+=2...
Problem : Print the following numbers.
20 17 14 11 8 5 2
Program
#include <iostream.h>
void main() {
for (int m=20; m>=2; ...
Another Version of the previous
example
#include <iostream.h>
void main( ) {
int m;
for (m=20; m>=2; m-=3)
cout<<m<<“t”;
c...
Problem : Print the following numbers.
1 2 3 4 … n(entered by user)
Program
#include <iostream.h>
void main() {
int n;
cou...
Problem : Print the following numbers.
L (entered By user) (L+1) (L+2) … U (entered By user)
Program#include <iostream.h>
...
Problem : Read five numbers from the user and print
the positive numbers only.
Program
#include <iostream.h>
void main()
{...
Problem : Read five numbers from the user and print
the positive numbers only.
Program
#include <iostream.h>
void main() {...
Problem : Compute and print S, Where
S = 1+ 2+ 3+ 4+ 5
Program
#include <iostream.h>
void main() {
int S=0;
for (int i=1; ...
Problem : Compute and print S, Where
Sum = 1+ 3+ 5+ 7+ … + n
Program
#include <iostream.h>
void main() {
int Sum=0, n;
cou...
Problem : Compute and print the summation
of any 10 numbers entered by the user.
Program
#include <iostream.h>
void main()...
Problem : Compute and Print the factorial of
the number 5. (Fact = 5 * 4 * 3 * 2 * 1)
Program
#include <iostream.h>
void m...
A program to find n!
#include <iostream.h>
void main( ) {
int Fact=1,n;
cout<<“Enter an integer to find its
factorial”;
ci...
Problem : Compute and Print the value of M
where M = 2 * 4 * 6 * … * n
Program
#include <iostream.h>
void main( ) {
long M...
Problem : Compute and Print Mn
Program
#include <iostream.h>
void main() {
long Result=1;
int M, n;
cout<<"please enter th...
Write a program that finds Mn
for
positive & negative n
• H.W.
Print the following shape
*****
*****
*****
*****
*****
cin>>n;
for(int i=1;i<=n;i++)
{ for (int j=1;j<=n;j++)
cout<<“*”;
...
Problem : Draw the following shape
*
**
***
****
*****
#include <iostream.h>
void main( ) {
for (int raw=1; raw<=5; raw++)...
Problem : Draw the following shape
*****
****
***
**
*
#include <iostream.h>
void main() {
for (int i=1; i<=5; i++) {
for ...
What is the output for the following
program
for(int i=1;i<=5;i++)
{
for (int j=1;j<=5;j++)
if (i==j) cout<<“*”;
else
if (...
Problem : display the multiplication table for
the number 3.
#include <iostream.h>
void main() {
for (int i=1; i<=10; i++)...
Problem : display the multiplication table for
the numbers from 1 to 5.
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10...
for (int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
cout<<i*j<<“t”;
cout<<endl;
}
Problem : Read any number from the user
and print Prime if it is a prime number, or
Not prime otherwise.
#include <iostrea...
S=m0
+ m1
+ … +mn
#include <iostream.h>
void main()
{int s=0,n,m;
int t=1;
cout<<"Enter m please ";
cin>>m;
cout<<"Enter n...
#include <iostream.h>
void main()
{int s=0,n,m;
int t=1;
cout<<"Enter m please ";
cin>>m;
cout<<"Enter n please ";
cin>>n;...
While Technique
General Form:
while (Condition) {
.
Statement(s);
.
}
Statements will be executed repeatedly while conditi...
Problem : Print the word “Amman” five
times.
Program
#include <iostream.h>
void main() {
int i=1;
while (i<=5)
{
cout<<"Am...
#include <iostream.h>
void main() {
int i=1;
while (i++<=5)
{
cout<<"Ammann";
}
cout<<i<<endl;
}
Problem : Print the following numbers.
1 3 5 7 9 11
Program#include <iostream.h>
void main() {
int i=1;
while (i <= 11) {
...
Problem : Print the following numbers.
20 17 14 … n
Program
#include <iostream.h>
void main() {
int n, k=20;
cout<<"Enter ...
Problem : Read five numbers from the user and print
the positive numbers only.
Program
#include <iostream.h>
void main() {...
#include <iostream.h>
void main() {
int sum=0,i,x,y;
cout<<"Enter x,y please: ";
cin>>x>>y;
i=x;
while ( i <=y) {
sum=sum+...
Problem : Compute and print S, Where
Sum = 1+ 3+ 5+ 7+ … + n
Program
#include <iostream.h>
void main() {
int n, Sum=0, i=1...
Problem : Read 10 numbers by the user and
compute and print the summation of
numbers, which are divisible by 3.
Program
#i...
Problem : Compute and Print the value of M
where M = 2 * 4 * 6 * … * n
Program
#include <iostream.h>
void main() {
int N, ...
#include <iostream.h>
void main() {
int N, M=1, i=2;
cout<<"Enter the upper limit:";
cin>>N;
cout<<"nM=1";
while ( i <= N ...
Nested Loops
#include <iostream.h>
void main() {
int i,j=1;
while(j<=4){
i=1;
while(i<=4){
cout<<i<<"t";
i++;
}
j++;
cout<...
Problem : Draw the following shape
*
**
***
****
*****
#include <iostream.h>
void main() {
int i=1;
while (i<=5) {
int j=1...
Do .. While Technique
General Form:
do {
.
Statement(s);
.
} while (Condition) ;
Statements will be executed repeatedly wh...
Problem : Print the word “Amman” five
times.
Program
#include <iostream.h>
void main() {
int i = 1;
do {
cout<<"Ammann";
i...
Execute the following program
#include <iostream.h>
void main() {
int Choice, Num;
do {
cout<<"n Enter the New Number";
ci...
#include <iostream.h>
void main() {
int Num; char Choice;
do {
cout<<"n Enter the New Number";
cin>>Num;
if (Num % 2 == 0)...
#include <iostream.h>
void main() {
int Num; char Choice;
do {
cout<<"n Enter the New Number";
cin>>Num;
if (Num % 2 == 0)...
Homework
Resolve all problems in the presentation 5 and 6 by using the
three loop techniques: For, While, and Do … while L...
1
1 2
1 2 4
1 2 4 8
for (int i=1;i<=4;i++)
{int x=1;
for(int j=1;j<=i;j++)
{cout<<x<<“ “;
x=x*2;}
cout<<endl;}
for (int i=1;i<=4;i++)
{for(int j=0;j<i;j++)
{int x=1;
for( int k=1;k<=j;k++)
x=2*x;
cout<<x<<“ “;}
cout<<endl;}
Functions
Chapter 3
Topics to be covered
• C++ pre defined functions:
– Math library functions
– Random function
– Examples on rand with switc...
• Call by value & call By reference
• Functions on arrays
• Scope of variables &Global variables
• Recursion :
– Factorial...
• Math library functions:
– ceil(x),floor(x)
– fabs(x), fmod(x,y), pow(x,y),sqrt(x)
– sin(x), cos(x), tan(x)
• These funct...
Examples
cout<<ceil(5.2);
ceil(0.1);
ceil(-0.1);
ceil(-1.1);
floor(5.2);
floor(0.1);
floor(-0.1);
floor(-1.1);
ceil(5.2/3)...
#include <iostream.h>
#include <cmath>
void main()
{
double A,B,C,X,Y;
cout<<"Enter a number :";
cin>>X;
Y=X/180*3.141592;...
Problem : Read any number from the user
and print it is prime if it is, or not prime
otherwise.
#include <iostream.h>
#inc...
Random number generator
• #include <cstdlib>
• X=rand(); // gives a random number
// between 0.. 32767
#include <iostream.h>
#include <cstdlib>
void main()
{
int x;
for( int i=1;i<=100;i++)
{x=rand();
cout<<x<<endl;}
}
Generate 20 random numbers
between 0 - 9
#include <iostream.h>
#include <cstdlib>
void main()
{
int x;
for( int i=1;i<=20;...
20 numbers between 1 - 10
#include <iostream.h>
#include <cstdlib>
void main()
{
int x;
for( int i=1;i<=20;i++)
{x=rand()%...
Generate 10 integer random
numbers between 5 - 7
Using srand function
#include <cstdlib>
void main()
{
int x,seed;
cout<<"Enter the seed for the random generater ";
cin>>s...
Q: Write a program that generates
1200 random numbers between 1-6,
and also counts the occurrence of
each number?
Its expe...
#include <iostream.h>
#include <cstdlib>
void main()
{ int x,count1=0, count2=0, count3=0, count4=0, count5=0, count6=0;
f...
#include <iostream.h>
#include <cstdlib>
void main()
{ int x,count[7]={0};
for( int i=1;i<=1200;i++)
{
x=rand()%6 +1;
if (...
The same example
using Switch statement
#include <iostream.h>
#include <cstdlib>
void main()
{ int x,count[7]={0};
for( in...
• Do the same prev. example,
• Count the number of even numbers, and
the number of odd numbers.
#include <iostream.h>
#include <cstdlib>
void main()
{ int x,even=0,odd=0;
for( int i=1;i<=1200;i++)
{
x=rand()%6 +1;
swit...
#include <iostream.h>
#include <cstdlib>
void main()
{
int x,count[7]={0};
for( int i=1;i<=1200;i++)
{
x=rand()%6 +1;
coun...
User Defined Functions
• Write a function that calculates and
returns the square value of a double
number:
#include <iostream.h>
double square(double); // function prototype
void main( )
{double x,y;
cout<<“Enter a number :”;
cin...
Another user defined function
• Write a program to calculate and print a
rectangle area, the program should use a
function...
#include <iostream.h>
double area(double,double); // function prototype
void main( ){
double L,W,A;
cout<<“Enter the lengt...
• Write a program that finds and prints the
maximum of three integer numbers, The
program should use a function to find th...
#include <iostream.h>
int max(int,int,int);
void main(){
int x,y,z;
cout<<"Enter 3 numbers please :";
cin>>x>>y>>z;
cout<<...
#include <iostream.h>
#include <cmath>
bool prime(int);
void main(){
int x;
cout<<"Enter a number please :";
cin>>x;
if (p...
Build your own fabs function
#include <iostream.h>
double fabs(double);
void main(void)
{
double x,y;
cout<<"Enter a numbe...
Forms of functions
• Functions that take inputs and returns output:
– double square(double), int max(int a, int b, int c) ...
Write a program that uses a function to
calculate and print the sum of two numbers.
#include <iostream.h>
void print_sum(i...
Write a program that reads two numbers
and prints the sum of them,
This program should use a function to read
the numbers ...
#include <iostream.h>
void print_sum(int,int);
int read_number(void);
void main()
{int x,y;
x=read_number();
y=read_number...
Write a progam that uses a function
to print a welcome message
#include <iostream.h>
void print_welcome(void);
void main()...
• Modify the previous example, make the
main calls the print function 10 times
• Also, make the print_welcome function
pri...
#include <iostream.h>
#include<cstdlib>
void print_welcome(void);
void main(){
for(int i=1;i<=10;i++)
print_welcome();
}
v...
Inputs for any function
• The inputs for a function could be:
– constants: x=sqrt( 9);
– Variables x=sqrt(y);
– Expression...
Scope of variables with functions
#include <iostream.h>
int x=10; // global variables
int f1(int);
void f2(int);
int f3(vo...
int f1(int a)
{
cout<<x<<endl;
int x=13;
cout<<x<<endl;
f2(x);
cout<<::x<<endl;
return x+a;
}
void f2(int b)
{cout<<x<<end...
Aliasing
#include<iostream.h>
int main()
{
int x;
int &y=x;
x=5;
int &z=y;
cout<<x<<"t"<<y<<"t"<<z<<endl;
y=7;
cout<<x<<"t...
Call By value & call By reference
#include <iostream.h>
int square(int);
void main()
{
int x,y;
cout<<"Enter a number ";
c...
#include <iostream.h>
void square(int &);
void main()
{
int x;
cout<<"Enter a number ";
cin>>x;
cout<<x<<" squared is “;
s...
#include<iostream.h>
void read_two_numbers(int &,int &);
void main()
{int x,y;
read_two_numbers (x,y);
cout<<x<<" "<<y<<en...
Static variables and default
arguments
#include <iostream.h>
void f(int x=10 );
void main()
{
f();
f(5);
f(7);
}
void f(in...
Recursive functions
• Factorial
• Febonacci series
• Sum between X, Y
#include <iostream.h>
int fact(int);
void main()
{
int x;
cout<<"Enter a number to calculate its factorial ";
cin>>x;
cout...
Recursive fact
#include <iostream.h>
int fact(int);
void main()
{
int x;
cout<<"Enter a number to calculate its factorial ...
#include <iostream.h>
int fact(int);
void main()
{
int x;
cout<<"Enter a number to calculate its factorial ";
cin>>x;
cout...
• Feb(0)=0
• Feb(1)=1
• Feb(n)=feb(n-1)+feb(n-2)
#include <iostream.h>
int feb(int);
void main()
{
int x;
cout<<"Enter a number to calculate its febonacci ";
cin>>x;
cout<...
#include <iostream.h>
int feb(int);
void main()
{
int x;
cout<<"Enter a number to calculate its febonacci ";
cin>>x;
cout<...
Febonacci using for
#include <iostream.h>
int feb(int);
void main()
{
int x;
cout<<"Enter a number to calculate its febona...
Sum of numbers from 1 to n
#include <iostream.h>
int sum(int);
void main()
{
int x;
cout<<"Enter a number to calculate the...
• Write a function that returns the sum of
numbers from X to Y. The function should
calculate the sum recursively
• ∑ i = ...
Sum of numbers from X to Y
#include <iostream.h>
int sum(int,int);
void main()
{
int x,y;
cout<<"Enter two numbers to calc...
ArrayArray
Array is a set of adjacent memory locations of the same data type. All of
them have one name, which is the arra...
One Dimensional arrayOne Dimensional array
int List[5];
100 30 10 -20 5
List[0] List[1] list[2] list[3] list[4]
Read Eleme...
Definitions and initial values
int X[4]={4,2,3,1};
int A[10]={0};
int B[100]={1};
int C[7]={1,2,6};
int d[5];
int E[ ]={4,...
Not accepted Statements
int A[4]={4,2,4,5,2};
int E[ ];
int n=5;
int X[n];
Corrected by:
const int n=5;
int X[n];
#include <iostream.h>
void main() {
int A[5] = {10,20,15,100,30};
for (int i=0; i<5; i++)
cout<<A[i]<<'t';
for (i=0; i<5; ...
#include <iostream.h>
void main() {
int A[5] = {10,20,15,100,30};
for (int i=0; i<5; i++)
cout<<A[i]<<'t';
for (i=0; i<5; ...
#include <iostream.h>
void main() {
const int Size = 10;
char KeyBSym[Size]={ ')', '!', '@', '#', '$', '%', '^', '&', '*',...
#include <iostream.h>
const int S = 10;
void main() {
int A[S];
for(int i=0; i<S; i++) {
cout<<"nEnter A["<<i<<"]:";
cin>>...
#include <iostream.h>
const int S = 10;
void main() {
int A[S];
for(int i=0; i<S; i++) {
cout<<"nEnter A["<<i<<"]:";
cin>>...
Find the Maximum elementFind the Maximum element
#include <iostream.h>
const int Size = 10;
void main() {
int Vector[Size]...
SearchSearch
#include <iostream.h>
const int Size = 10;
void main() {
int Vector[Size];
for(int i=0; i<Size; i++)
cin>>Vec...
Another version of search exampleAnother version of search example
#include <iostream.h>
const int Size = 10;
void main() ...
Sort the elements:Sort the elements:#include <iostream.h>
const int Size = 5;
void main() {
int Vector[Size];
for(int i=0;...
build a swap function function
void swap(int & x,int & y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Bubble sort using
the swap
function
#include <iostream.h>
void swap(int &,int &);
const int Size = 5;
void main() {
int Ve...
Arrays and Call by reference
• We can’t return the array using return
statement.
• We need to use the call by reference
te...
Write a function that return the sum
of an array#include <iostream.h>
int Arr_Sum(int [ ],int);
void main( )
{
int A[5]={2...
Functions to Read and
print arrays
#include <iostream.h>
void Arr_read(int [ ],int);
void Arr_print(int[ ],int);
void main...
Function to calculate the sum of
two arrays#include <iostream.h>
void sum(int [ ],int [ ],int[ ],int);
void main()
{
int a...
cout statement with setw( )
#include <iostream.h>
#include <iomanip.h>
void main()
{
for(int i=1; i<= 5;i++) // without us...
Strings
#include <iostream.h>
void main()
{
char n[10];
char a[10]={'A','h','m','e','d'};
for(int i=0; a[i]!=0 ; i++)
cout...
Q1 in the exam
#include <iostream.h>
void main()
{
int a[4][3];
for(int i=0;i<4;i++)
for(int j=0;j<3;j++)
{ cout<<"Enter a...
Two Dimensional arrayTwo Dimensional array
int Matrix[3][4];
30
Assign values to Elements
Matrix[0][1] = 30;
Matrix[1][0] ...
int A[2][3] = { {1 ,2 , 3 },
{10,20,30}};
int Matrix[3][4]= {{0,30 },
{100,0,10},
{0,0,0,-20}};
#include <iostream.h>
void main() {
int A[2][3] = {{1,2,3},{10,20,30}};
int B[2][3] = {100,200,300,40,50,60};
int C[2][3] ...
#include <iostream.h>
const int Rows = 3, Columns = 4;
void main() {
int A[Rows][Columns];
for (int i=0; i<Rows; i++)
for ...
#include <iostream.h>
int A_sum(int [ ][2],int);
void main(){
int x[3][2]={6,5,4,3,2,1};
int y[4][2]={5,4,3,2,3,4,1};
cout...
Diagonal SummationDiagonal Summation
#include <iostream.h>
const int Rows = 4, Columns = 4;
void main() {
int A[Rows][Colu...
Inverse Diagonal SummationInverse Diagonal Summation
#include <iostream.h>
const int Rows = 4, Columns = 4;
void main() {
...
Lower Triangular MultiplicationLower Triangular Multiplication
#include <iostream.h>
const int Rows = 4, Columns = 4;
void...
Lower Triangular MultiplicationLower Triangular Multiplication
#include <iostream.h>
const int Rows = 4, Columns = 4;
void...
Write a Program that copies an
array to another
#include <iostream.h>
const int R = 4, C= 3;
void main() {
int A[R][C];
in...
Write a function that copies a 2-D
array to another
void copyA(int x[ ][3],int y[ ][3],int r)
{
for(int i=0;i<r;i++)
for(i...
Write a Program that copies an
array to another
#include <iostream.h>
const int R = 4, C= 3;
void main() {
int A[R][C];
in...
Store the following symbols in theStore the following symbols in the
array Symbol.array Symbol. * $ $ $
# * $ $
# # * $
# ...
Matrix Matrix SummationMatrix Matrix Summation
#include <iostream.h>
const int Rows = 4, Columns = 4;
void main() {
int A[...
Write a function to add two Arrays
void add(int x[ ][4],int y[ ][4],int z[ ][4],int r)
{
}
Compute the average for 5 marks
for 10 students
int marks [10][5];
for(int i=0;i<10;i++)
for(int j=0;j<5;j++)
{ cout<<“Ent...
int A[3][4], B[4][3];
for(int i=0;i<3;i++)
for(int j=0;j<4;j++)
cin>>A[i][j];
for(i=0;i<3;i++)
for(int j=0;j<4;j++)
B[ j][...
Function to calculate the Transpose
of an array 3x4
void trans34(int x[3][4],int y[4][3])
{
for(int r=0;r<3;r++)
for(int c...
HomeworkHomework
1- Write program to compute and print the result of
Matrix A[n][n] multiplied by Matrix B[n][n] and
store...
Calculate an accurate value for Pi
double Pi=0;
for(int i=0;i<=1000;i++)
if( i%2==0)
Pi=Pi+4.0/(2*i+1);
else
Pi=Pi-4.0/(2*...
double pi;
int t=1;
for(int i=1;i<=1000;i=i+2)
{ pi=pi+t*4.0/i;
t=t*-1;
}
Strings
#include <iostream.h>
void main()
{
char n[10];
char a[10]={'A','h','m','e','d'};
for(int i=0; i<5 ; i++)
cout<<a[...
#include <iostream.h>
void main()
{
char a[10]={'I','b','r','a','h','e','e','m‘};
for(int i=0; a[i]!=0 ; i++)
cout<<a[i]<<...
#include <iostream.h>
void main()
{
char a[10]={'A','h','m','e','d'};
for(int i=0; a[i]!=0 ; i++)
{for(int j=0;j<i;j++)
co...
#include <iostream.h>
void main()
{
char a[10]=“Ahmed“;
for(int i=0; a[i]!=0 ; i++)
{for(int j=0;j<i;j++)
cout<<" ";
cout<...
#include <iostream.h>
void main()
{
char a[10];
cout<<"Enter a name : ";
cin>>a;
cout<<a<<endl;
for(int i=0; a[i]!=0 ; i++...
#include <iostream.h>
void main()
{
char a[10];
char b[10];
cout<<"Enter ur first name : ";
cin>>a;
cout<<"Enter ur second...
#include <iostream.h>
void main()
{
char a[10];
cout<<"Enter a name : ";
cin>>a;
cout<<a<<endl;
for(int i=0; a[i]!=0 ; i++...
Final exam question
• Write a function that returns the length of a
string or array of characters.
• The function prototyp...
int length(char name[ ])
{
for(int i=0;name[i]!=0;i++)
;
return i;
}
#include <iostream.h>
void main()
{
char name[10];
cout<<"Enter ur name : ";
cin>>name;
for(int i=0; name[i]!=‘0’ ; i++);
...
Write a program that prints the
name inversed( from the last char
to the first character
• See the prev. slide
Pointers
#include <iostream.h>
void main()
{
int x=5;
int* y; // pointer to an integer
y=&x;
cout<<x<<endl<<&x<<endl;
cout...
#include <iostream.h>
void main()
{
char a[10]="Ahmad"; // prints Ahmed
cout<<a<<endl;
int b[10]={1,2,3,4,5};
cout<<b<<end...
#include <iostream.h>
void main()
{
char a[10]="Ahmad"; // prints Ahmed
cout<<a<<endl;
int b[10]={1,2,3,4,5};
cout<<b<<end...
1- do-while statement.
2- nested for loop
3- nested while statement
4- math library functions.
5- functions prototype and ...
Upcoming SlideShare
Loading in …5
×

901131 examples

1,676 views

Published on

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,676
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
97
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

901131 examples

  1. 1. www.aabu.edu.jo/~wael
  2. 2. C++ Program A sequence of structured statements written by programmer using C++ language to solve a problem. Using Visual C++ to write your program 1- Start  Programs  Microsoft Visual Studio 6  Microsoft Visual C++ 6 2- File  New  Files  C++ Source file  oK 3- Write your program using C++ statements 4- Compilation: Ctrl + F7 to see if the program has error's 5- Execution: to display the program’s result
  3. 3. General form of C++ Program #include <iostream.h> void main() { . . C++ statements . . } Remark: C++ language is case sensitive
  4. 4. Problem : Compute and print the summation of two numbers. Program #include <iostream.h> void main() { int a, b, s; cout<<"Please Enter two numbers:"; cin>>a>>b; s = a + b; cout<<"s="<<s<<endl; }
  5. 5. Remarks: - iostream.h: C++ library that contains all input/output statements and other constrols. - main(): the main function of the program which represents the program’s life time. - a, b, and s are three variables of type integer. Their values can be any integer and can be changed. - cin>>: C++ statement to take value(s) from the user. - cout<<: C++ statements to display value(s) to the output screen. - “ ”: must be around any character constants. - n or endl: to start new line at output screen.
  6. 6. Variables • Variables: - Variable is one memory location. -The name of the location is the variable name. -The location content is the value of the variable - You can change the content of the variable at any time in the statements of the algorithm. e.g. Name of the location Inside Memory location employee_name “Ali Ahmed” age 35 hourly_rate 3.25
  7. 7. Predefined Data Types: • int : values (e.g. 5 , -321 , 12) operations (e.g. + , - , * , / , % , >, <, = =, !=, > =, <= ) • float (double) : values (e.g. 3.2 , 1.23E+5 , 0.34E-2) operations (e.g. +, -, *, /, , >, <, = =, !=, > =, <= ) • bool : values (true , false) operations (e.g. AND, OR, NOT) • char : values (e.g. ‘A’ , ‘t’ , ‘(‘ , ‘5’ , ‘;’ ) operations (e.g. <, > , ≤, etc.) Data Types Variable declaration Type Variable_name
  8. 8. Constant Values: can be numerical (3, 100, -5, 3.14) or string (‘A’, ‘$’, ‘Ahmad’, Amman). Constant identifier: one memory location take a value at a first time, which can not be changed. const float pi = 3.14
  9. 9. Variable names • int X,x,Number, IF,If,iF,a7,Total_sum; • float _abc;
  10. 10. Problem : Compute and print the average of three numbers. Program #include <iostream.h> void main() { int n1, n2, n3; float s, average; cout<<"Please Enter three integers: "; cin>>n1>>n2>>n3; s = n1 + n2 + n3; average = s / 3; cout<<"n Average = t"<<average<<endl; } Remark: t to leave tab spaces
  11. 11. Problem : Compute the area of the circle. Where area = π x R2 Program #include <iostream.h> void main() { const double Pi = 3.14; int r; cout<<"n Please enter r"; cin>>r; double a; a = Pi * r * r; cout<<"n Circle's Area = "<<a<<endl; }
  12. 12. Examples on integer division #include <iostream.h> void main( ) { int x; x=1/3*3; // 1/3=0 cout<<x<<endl; x=1.0/3*3; cout<<x<<endl; }
  13. 13. Boolean variables and relational operations #include <iostream.h> void main( ) { bool x,y; x= 5 > 7; cout<<x<<endl; y= 5 < 7; cout<<y<<endl; x=true; cout<<x<<endl; y=false; cout<<y<<endl; x=5; cout<<x; }
  14. 14. Misleading examples X= 7 > 5 > 3; This expression gives false because its evaluated as follows X=(7>5) >3; = 1 > 3; // False; The relational operations are executed from left to right < ,<= ,> , >= have the same priority == , != have lower priority than the above. X = 1 == 1>3; X = 3>4 == 4>3;
  15. 15. Priority • * , / , % have the same priority ( High ) • + , - have the same priority (Low)
  16. 16. Examples on arithmetic operations X= 5 + 2 * 3 – 7; The order of execution is as follows: * , then + , then - X= 5 + 2 * 3 – 7 / 3 Execution order : * , + , / , - X= 5+2*3/4%1-7/3 ……………………..
  17. 17. If Statement in C++ One way if if ( Condition ) statement; if ( Condition ) { statements; }
  18. 18. Problem : Read any number from the user, then print positive if it is positive. Program #include <iostream.h> void main() { int Num; cout<<"n Please Enter an integer number:"; cin>>Num; if (Num > 0) cout<<" Positiven"; }
  19. 19. Another Version #include <iostream.h> void main() { int Num; bool w; cout<<"n Please Enter an integer number:"; cin>>Num; w=Num>0; if (w) cout<<" Positiven"; }
  20. 20. If Statement in C++ Two way if if ( Condition ) statement; else statement; if ( Condition ) { statements; } else { statements;}
  21. 21. Write a program that reads a mark, if mark is 60 or greater, the program prints PASS, else it will print FAIL #include <iostream.h> void main() { int mark; cout<<"n Please Enter your mark: "; cin>>mark; if (mark>=60) cout<<" PASSn"; else cout<<"FAILn";
  22. 22. More than one statement in the if #include <iostream.h> void main() { int mark; cout<<"n Please Enter your mark: "; cin>>mark; if (mark>=60) { cout<<" PASSn"; cout<<“ you can take Object course nown”; } else { cout<<"FAIL"; cout<<“You must take this course againn”; } }
  23. 23. Write a program that prints the fraction a/b in the form c d/b Example: 7/3 = 2 1/3 #include <iostream.h> void main ( ) { int a,b,c,d; cout<<“To convert the fraction from the format a/b to c d/b, Enter a,b”; cin>>a>>b; c=a/b; d=a%b; cout<<a<<“/”<<b<<“=“<<c<<“ “<<d<<“/”<<b<<endl; }
  24. 24. Enhancement on the previous example #include <iostream.h> void main ( ) { int a,b,c,d; cout<<“To convert the fraction from the format a/b to c d/b, Enter a,b”; cin>>a>>b; c=a/b; d=a%b; cout<<a<<“/”<<b<<“=“; if ( c != 0) cout<<c; if (d!=0) cout<<“ “<<d<<“/”<<b; cout<<endl; }
  25. 25. Condition Condition: An expression that is evaluated to produce only true or false values. Arithmetic Expressions - It is composed of operands and arithmetic operations ( + , - , *, /, %). - Its result is a numeric value (e.g. 3 + 4 gives 7) - Operands may be numbers and/or identifiers that have numeric values.
  26. 26. Relational Expressions - It is composed from operands and operators. - Operands may be numbers and/or identifiers that have numeric values - Its result is a logical value (true or false). - Operators are relational operators: < , > , <= , >= , = =, != e.g. (a < b) gives true, if value of a is less than value of b false, if value of a is not less than value of b (x != y) also gives true or false according to the values of x and y
  27. 27. Logical Expressions - It is called also Boolean expression. - It is composed from operands and operators. - Operands are identifiers that have logical values - Its result is a logical value (true or false) (see later). - Operators are logical: &&(AND) , ||(OR), !(NOT) e.g. X && Y a && b || c
  28. 28. Evaluating Logical Expressions • The truth table (1) AND table && True False True True False False False False
  29. 29. (2) OR table || True False True True True False True False (3) NOT table ! True False False True
  30. 30. Arithmetic  Relational  Logical • NOTES 1) A relational expression may contain arithmetic sub expressions, e.g. ( 3 + 7 ) < (12 * 4 ) 3 + 7 < 12 * 4 2) A logical expression may contain relational and arithmetic subexpressions, e.g. 1- x && y && ( a > b ) 2- (2 + t ) < (6 * w ) && ( p = =q )
  31. 31. Operator Precedence Operator Description Precedence ( ) parentheses Highest +, – , ! unary plus, unary minus, Not *, /, % + , - Binary plus, binary minus <, <=, >, >= == , != Equal, not equal && || = Assignment Lowest
  32. 32. Examples • Find the value of the following expression: (1) 5 + 8 * 2 / 4 16 4 9 (This is the final result)
  33. 33. Find the value of the following expression ( 9 + 3 ) - 6 / 3 + 5 12 2 10` 15 (this is the final result)
  34. 34. Find the value of the following Expression If x = True, y = False, z = False, find the value of the expression x && y || z x && y || z False False (the final result)
  35. 35. Another example • X=true, Y=false, Z= true X || Y && Z true • X=true, Y=false, Z= false X || Y && Z true
  36. 36. If a = 3, b = 5, x = true, y = false, find the value of the expression: ( a < b ) AND y OR x ( a < b ) && y || x True False True (the final result) Find the value of the following Expression
  37. 37. What is the output of the following code: Program #include <iostream.h> void main() { int a=10, b=3; cout<<"n a+b= t"<<a+b; cout<<"n a+b*2= t"<<a+b*2; cout<<"n (a+b)*2 t"<<(a+b)*2<<endl; cout<<a<<“<“<<b<<" ist"<<(a<b); cout<<"n a+b != a+3 is t"<<(a+b != a+3); cout<<"n a+b >= b*2 || a>b+9 is t"<<(a+b >= b*2 || a>b+9); cout<<endl; }
  38. 38. Problem : Read any number from the user, then print positive if it is positive and print negative otherwise. Program #include <iostream.h> void main() { int Num; cout<<"nPlease Enter Number:"; cin>>Num; if (Num < 0) cout<<"nNegativen"; else cout<<"nPositiven"; }
  39. 39. Problem : Read Two numbers from the user, then print the greatest one. Program #include <iostream.h> void main() { int x,y; cout<<"nPlease Enter two numbers:"; cin>>x>>y; cout<<"Max = "; if (x > y) cout<<x<<endl; else cout<<y<<endl; }
  40. 40. Problem : Read three numbers to print the smallest one. Program #include <iostream.h> void main() { int a, b, c; cout<<"nPlease Enter three numbers:"; cin>>a>>b>>c; cout<<"nMin= "; if ((a < b) && (a < c)) cout<<a; if ((b < a) && (b < c)) cout<<b; if ((c < a) && (c < b)) cout<<c; cout<<endl; }
  41. 41. Program2 (Nested if) #include <iostream.h> void main() { int a, b, c; cout<<"nPlease Enter three numbers:"; cin>>a>>b>>c; cout<<"nMin= "; if (a < b) if (a < c) cout<<a; else cout<<c; else if (b < c) cout<<b; else cout<<c; cout<<endl; }
  42. 42. Problem : Read number, if it is positive, Add number 10 to it and print the Number “is positive”, but otherwise, subtract number 10 from it and print the Number “is negative”. Program #include <iostream.h> void main() { int Number; cout<<"nPlease enter Number:"; cin>>Number; if (Number>0) { Number = Number + 10; cout<<Number<<" is Positiven";} else { Number = Number - 10; cout<<Number<<" is Negativen";} }
  43. 43. Example on dangling else if ( x>y) if ( x<z) cout<<“ Hello”; else cout<<“Hi”;
  44. 44. Another idea if ( x>y) {if ( x<z) cout<<“ Hello”;} else cout<<“Hi”;
  45. 45. Assignment Statement Simple Assignment: Max = 5 ; Max = A ; F = A+B*2; Compound Assignment: A += 10 ;  A = A + 10; A -= C ;  A = A – C; I *= 4 ;  I = I * 4; r /= 2;  r = r / 2; S %= 3 ;  S = S % 3 ; B &= true;  B = B && true; B |= true;  B = B || true;
  46. 46. Increment and Decrement Postfix C++;  use the value of C, then increment (C = C+1) it. C--;  use the value of C, then decrement (C = C-1) it. Prefix ++C; increment the value of C (C = C+1), then use it . --C; Decrement the value of C (C = C-1), then use it .
  47. 47. What is the output of the following C++ Source Code Program#include <iostream.h> void main( ) { int A=10, B=4, R; cout<<"A="<<A<<"tB="<<B; A += B; B *= 2; cout<<"nA="<<A<<"tB="<<B; R = ++A % B--; cout<<"nR="<<R; R = A++ + --B ; cout<<"nA="<<A<<"tB="<<B<<"tR="<<R; bool a=true, b=false; a &= b; if (a == 0) cout<<"n a = falsen"; else cout<<"n a = truen"; }
  48. 48. Examples X=5; Y=7; Z=X++ + Y; // Z=X+Y; X=X+1; cout<<X<<“ “<<Y<<“ “<<Z<<endl; Z=++X +Y; // X=X+1; Z=X+Y; cout<<X<<“ “<<Y<<“ “<<Z<<endl; Z=X++ + Y++; // Z=X+Y; X++;Y++; cout<<X<<“ “<<Y<<“ “<<Z<<endl;
  49. 49. Loop (iteration statements) used to repeat subcode number of times there three loop techniques: 1- for Loop. 2- while Loop. 3- do … while Loop
  50. 50. For Loop Technique General Form: for (counter_var=initial_val; condition; increasing or decreasing counter_var) { . Statement(s); . } Statements will be executed repeatedly while condition is true. When the condition become false, the loop will be terminated and the execution sequence will go the first statement after for loop. If the loop body contains only one statement, there is no need to begin{ and end } the loop body.
  51. 51. Problem : Print the word “Amman” five times. Program #include <iostream.h> void main( ) { for (int i=1; i<=5; i++) cout<<"Ammann"; } Another Program #include <iostream.h> void main() { for (int i=5; i>=1; i--) cout<<"Ammann"; }
  52. 52. Problem : Print the following numbers. 1 3 5 7 9 11 Program #include <iostream.h> void main( ) { for (int k=1; k<=11; k+=2) cout<<k<<“t”; cout<<endl; }
  53. 53. Problem : Print the following numbers. 20 17 14 11 8 5 2 Program #include <iostream.h> void main() { for (int m=20; m>=2; m-=3) cout<<m<<“t”; cout<<endl; }
  54. 54. Another Version of the previous example #include <iostream.h> void main( ) { int m; for (m=20; m>=2; m-=3) cout<<m<<“t”; cout<<endl; }
  55. 55. Problem : Print the following numbers. 1 2 3 4 … n(entered by user) Program #include <iostream.h> void main() { int n; cout<<"nPlease enter the upper limit:"; cin>>n; for (int i=1; i<=n; i++) cout<<i<<“t”; cout<<endl; }
  56. 56. Problem : Print the following numbers. L (entered By user) (L+1) (L+2) … U (entered By user) Program#include <iostream.h> void main() { int L,U; cout<<"nPlease enter the Lower limit:"; cin>>L; cout<<"nPlease enter the Upper limit:"; cin>>U; for (int i=L; i<=U; i++) cout<<i<<“t”; cout<<endl; }
  57. 57. Problem : Read five numbers from the user and print the positive numbers only. Program #include <iostream.h> void main() { int num; for (int i=1; i<=5; i++) { cout<<"nPlease Enter No"<<i<<':'; cin>>num; if (num > 0) cout<<num; } }
  58. 58. Problem : Read five numbers from the user and print the positive numbers only. Program #include <iostream.h> void main() { int num; for (int i=1; i<=5; i++) { cout<<"nPlease enter the next number:"; cin>>num; if (num<0) continue; cout<<num; } }
  59. 59. Problem : Compute and print S, Where S = 1+ 2+ 3+ 4+ 5 Program #include <iostream.h> void main() { int S=0; for (int i=1; i<=5; i++) S+=i; cout<<"nS="<<S<<endl; }
  60. 60. Problem : Compute and print S, Where Sum = 1+ 3+ 5+ 7+ … + n Program #include <iostream.h> void main() { int Sum=0, n; cout<<"nPlease Enter n"; cin>>n; for (int i=1; i<=n; i+=2) Sum+=i; cout<<"nSum="<<Sum<<endl; }
  61. 61. Problem : Compute and print the summation of any 10 numbers entered by the user. Program #include <iostream.h> void main() { int S=0, N; for (int i=10; i>=1; i--) { cout<<"nPlease Enter the next number:"; cin>>N; S+=N;} cout<<"nS="<<S<<endl; }
  62. 62. Problem : Compute and Print the factorial of the number 5. (Fact = 5 * 4 * 3 * 2 * 1) Program #include <iostream.h> void main( ) { int Fact=1; for (int j=5; j>=1; j--) Fact *= j; cout<<"5!= "<<Fact<<endl; }
  63. 63. A program to find n! #include <iostream.h> void main( ) { int Fact=1,n; cout<<“Enter an integer to find its factorial”; cin>>n; for (int j=n; j>=1; j--) Fact *= j; cout<<n<<"!= "<<Fact<<endl; } Try it on n = 17 ???
  64. 64. Problem : Compute and Print the value of M where M = 2 * 4 * 6 * … * n Program #include <iostream.h> void main( ) { long M=1; int n; cout<<"please enter the upper Limit:"; cin>>n; for (int i=2; i<=n; i+=2) M *= i; cout<<"M= "<<M<<endl; }
  65. 65. Problem : Compute and Print Mn Program #include <iostream.h> void main() { long Result=1; int M, n; cout<<"please enter the Base number:"; cin>>M; cout<<"nplease enter the exponent:"; cin>>n; for (int i=1; i<=n; i++) Result *= M; cout<<"nResult= "<<Result<<endl; }
  66. 66. Write a program that finds Mn for positive & negative n • H.W.
  67. 67. Print the following shape ***** ***** ***** ***** ***** cin>>n; for(int i=1;i<=n;i++) { for (int j=1;j<=n;j++) cout<<“*”; cout<<endl; } Nested for
  68. 68. Problem : Draw the following shape * ** *** **** ***** #include <iostream.h> void main( ) { for (int raw=1; raw<=5; raw++) { for (int C=1; C<=raw; C++) cout<<'*'; cout<<endl; } } Nested for
  69. 69. Problem : Draw the following shape ***** **** *** ** * #include <iostream.h> void main() { for (int i=1; i<=5; i++) { for (int j=i; j<=5; j++) cout<<'*'; cout<<endl; } }
  70. 70. What is the output for the following program for(int i=1;i<=5;i++) { for (int j=1;j<=5;j++) if (i==j) cout<<“*”; else if (i+j==6) cout<<“*“; else cout<<“ “; Cout<<endl;}
  71. 71. Problem : display the multiplication table for the number 3. #include <iostream.h> void main() { for (int i=1; i<=10; i++) cout<<"3 x "<<i<<" = "<<3*i<<endl; }
  72. 72. Problem : display the multiplication table for the numbers from 1 to 5. 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
  73. 73. for (int i=1;i<=5;i++) { for(int j=1;j<=5;j++) cout<<i*j<<“t”; cout<<endl; }
  74. 74. Problem : Read any number from the user and print Prime if it is a prime number, or Not prime otherwise. #include <iostream.h> void main() { bool Prime = true; int i, num; cout<<"Please enter the number:"; cin>>num; for ( i=2; i<num; i++) if (num%i==0) { Prime = false; break; } if (Prime) cout<<num<<" is a Prime numbern"; else cout<<num<<" is not a Prime numbern"; }
  75. 75. S=m0 + m1 + … +mn #include <iostream.h> void main() {int s=0,n,m; int t=1; cout<<"Enter m please "; cin>>m; cout<<"Enter n please "; cin>>n; for (int i=0;i<=n;i++) { t=1; for (int j=1;j<=i;j++) t=t*m; s=s+t; } cout<<s<<endl;
  76. 76. #include <iostream.h> void main() {int s=0,n,m; int t=1; cout<<"Enter m please "; cin>>m; cout<<"Enter n please "; cin>>n; for (int i=0;i<=n;i++) { s=s+t; t=t*m; } cout<<s<<endl; }
  77. 77. While Technique General Form: while (Condition) { . Statement(s); . } Statements will be executed repeatedly while condition is true. When the condition become false, the loop will be terminated and the execution sequence will go to the first statement after While loop. If the loop body contains only one statement, there is no need to begin{ and end } the loop body.
  78. 78. Problem : Print the word “Amman” five times. Program #include <iostream.h> void main() { int i=1; while (i<=5) { cout<<"Ammann"; i++; } }
  79. 79. #include <iostream.h> void main() { int i=1; while (i++<=5) { cout<<"Ammann"; } cout<<i<<endl; }
  80. 80. Problem : Print the following numbers. 1 3 5 7 9 11 Program#include <iostream.h> void main() { int i=1; while (i <= 11) { cout<<i<<'t'; i+=2; } } Remark: Write ((i+=2) <= 11 ) condition instead of the above one. What changes you have to do to produce the same output.
  81. 81. Problem : Print the following numbers. 20 17 14 … n Program #include <iostream.h> void main() { int n, k=20; cout<<"Enter the lower limit:"; cin>>n; while ( k >= n) { cout<<k<<'t'; k -= 3; } } Remark: Write k-=3 instead of k in the above condition. What you have to do to produce the same output.
  82. 82. Problem : Read five numbers from the user and print the positive numbers only. Program #include <iostream.h> void main() { int num, j=0; while ( j++ < 5 ) { cout<<"Enter the next num:"; cin>>num; if (num > 0) cout<<num<<endl; } } Remark: Solve the above problem by using continue statement.
  83. 83. #include <iostream.h> void main() { int sum=0,i,x,y; cout<<"Enter x,y please: "; cin>>x>>y; i=x; while ( i <=y) { sum=sum+i; i=i+1; } cout<<"The Sum for the numbers from "<<x<<" to "<<y<<" = "<<sum<<endl; }
  84. 84. Problem : Compute and print S, Where Sum = 1+ 3+ 5+ 7+ … + n Program #include <iostream.h> void main() { int n, Sum=0, i=1; cout<<"Enter the upper limit:"; cin>>n; while ( i <= n ) { Sum += i; i += 2; } cout<<"nSum="<<Sum; }
  85. 85. Problem : Read 10 numbers by the user and compute and print the summation of numbers, which are divisible by 3. Program #include <iostream.h> void main() { int Num, Sum=0, i=1; while ( i <= 10 ) { cout<<"Enter a number:"; cin>>Num; if (Num % 3 == 0) Sum += Num; i++; } cout<<"nSum="<<Sum; }
  86. 86. Problem : Compute and Print the value of M where M = 2 * 4 * 6 * … * n Program #include <iostream.h> void main() { int N, M=1, i=2; cout<<"Enter the upper limit:"; cin>>N; while ( i <= N ) { M *= i; i += 2; } cout<<"nM="<<M; }
  87. 87. #include <iostream.h> void main() { int N, M=1, i=2; cout<<"Enter the upper limit:"; cin>>N; cout<<"nM=1"; while ( i <= N ) { M *= i; cout<<"x "<<i; i += 2; } cout<<"="<<M<<endl; }
  88. 88. Nested Loops #include <iostream.h> void main() { int i,j=1; while(j<=4){ i=1; while(i<=4){ cout<<i<<"t"; i++; } j++; cout<<endl; } } 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
  89. 89. Problem : Draw the following shape * ** *** **** ***** #include <iostream.h> void main() { int i=1; while (i<=5) { int j=1; while (j<=i) { cout<<'*'; j++;} cout<<endl; i++; } }
  90. 90. Do .. While Technique General Form: do { . Statement(s); . } while (Condition) ; Statements will be executed repeatedly while condition is true. When the condition become false, the loop will be terminated and the execution sequence will go to the first statement after the loop. The loop body will be executed at least one.
  91. 91. Problem : Print the word “Amman” five times. Program #include <iostream.h> void main() { int i = 1; do { cout<<"Ammann"; i++; } while (i <= 5); }
  92. 92. Execute the following program #include <iostream.h> void main() { int Choice, Num; do { cout<<"n Enter the New Number"; cin>>Num; if (Num % 2 == 0) cout<<Num<<" is Evenn"; else cout<<Num<<" is Oddn"; cout<<"Select your choice.n"; cout<<"1- Exit. (Terminate the Run)n"; cout<<"2- Enter New Number to Check.n"; cin>>Choice; } while (Choice != 1); }
  93. 93. #include <iostream.h> void main() { int Num; char Choice; do { cout<<"n Enter the New Number"; cin>>Num; if (Num % 2 == 0) cout<<Num<<" is Evenn"; else cout<<Num<<" is Oddn"; cout<<“Enter Y to continue, any other character to exit n”; cin>>Choice; } while (Choice == ‘Y’); }
  94. 94. #include <iostream.h> void main() { int Num; char Choice; do { cout<<"n Enter the New Number"; cin>>Num; if (Num % 2 == 0) cout<<Num<<" is Evenn"; else cout<<Num<<" is Oddn"; cout<<"Enter Y to continue, any other character to exit n"; cin>>Choice; } while ((Choice == 'Y') || (Choice=='y')); }
  95. 95. Homework Resolve all problems in the presentation 5 and 6 by using the three loop techniques: For, While, and Do … while Loops.
  96. 96. 1 1 2 1 2 4 1 2 4 8 for (int i=1;i<=4;i++) {int x=1; for(int j=1;j<=i;j++) {cout<<x<<“ “; x=x*2;} cout<<endl;}
  97. 97. for (int i=1;i<=4;i++) {for(int j=0;j<i;j++) {int x=1; for( int k=1;k<=j;k++) x=2*x; cout<<x<<“ “;} cout<<endl;}
  98. 98. Functions Chapter 3
  99. 99. Topics to be covered • C++ pre defined functions: – Math library functions – Random function – Examples on rand with switch statments • User Functions: – Function proto type – Function definition: • Square, Cube examples • Examples on the four forms of functions, And their meaning ( when to use each form): – void F(void) – void F(int) – int F(void) – int F(int)
  100. 100. • Call by value & call By reference • Functions on arrays • Scope of variables &Global variables • Recursion : – Factorial – Febonacci, – Sum of numbers from x to y
  101. 101. • Math library functions: – ceil(x),floor(x) – fabs(x), fmod(x,y), pow(x,y),sqrt(x) – sin(x), cos(x), tan(x) • These functions are of type double, and take also double arguments • They belong to the library – #include <cmath>
  102. 102. Examples cout<<ceil(5.2); ceil(0.1); ceil(-0.1); ceil(-1.1); floor(5.2); floor(0.1); floor(-0.1); floor(-1.1); ceil(5.2/3); floor(ceil(5.2/3)); fabs(-17.231); fmod(5,3) ≡ 5%3 fmod(4.2,2); fmod(5.1,2.5) double Y; Y=pow( 5,4); Y=pow(5,-4); Y=pow(5.2,3); Y=pow(16,0.25); Y=pow(0.01,0.5); Y=pow(-4,0.5); runtime error Y=pow(x*3/7,y-1); Y=pow(floor(x/3),ceil(x/4)); Y=sqrt(9); Y=sqrt(10); Y=sqrt(0.09);
  103. 103. #include <iostream.h> #include <cmath> void main() { double A,B,C,X,Y; cout<<"Enter a number :"; cin>>X; Y=X/180*3.141592; A=sin(Y); B=cos(Y); C=tan(Y); cout<<“sin("<<X<<") = "<<A<<endl; cout<<"cos("<<X<<") = "<<B<<endl; cout<<"tan("<<X<<") = "<<C<<endl; }
  104. 104. Problem : Read any number from the user and print it is prime if it is, or not prime otherwise. #include <iostream.h> #include <cmath> void main() { bool Prime = true; int i, num; cout<<"Please enter the number:"; cin>>num; for ( i=2; i<=sqrt(num); i++) if (num%i==0) { Prime = false; break; } if (Prime) cout<<num<<" is a Prime numbern"; else cout<<num<<" is not a Prime numbern"; }
  105. 105. Random number generator • #include <cstdlib> • X=rand(); // gives a random number // between 0.. 32767
  106. 106. #include <iostream.h> #include <cstdlib> void main() { int x; for( int i=1;i<=100;i++) {x=rand(); cout<<x<<endl;} }
  107. 107. Generate 20 random numbers between 0 - 9 #include <iostream.h> #include <cstdlib> void main() { int x; for( int i=1;i<=20;i++) {x=rand()%10; cout<<x<<endl;} }
  108. 108. 20 numbers between 1 - 10 #include <iostream.h> #include <cstdlib> void main() { int x; for( int i=1;i<=20;i++) {x=rand()%10+1; cout<<x<<endl;} }
  109. 109. Generate 10 integer random numbers between 5 - 7
  110. 110. Using srand function #include <cstdlib> void main() { int x,seed; cout<<"Enter the seed for the random generater "; cin>>seed; srand(seed); for( int i=1;i<=10;i++) { x=rand(); cout<<x<<endl;} }
  111. 111. Q: Write a program that generates 1200 random numbers between 1-6, and also counts the occurrence of each number? Its expected that the occurrence of each number will be about 200 times. But remember we are talking about random number. No exact values.
  112. 112. #include <iostream.h> #include <cstdlib> void main() { int x,count1=0, count2=0, count3=0, count4=0, count5=0, count6=0; for( int i=1;i<=1200;i++) { x=rand()%6 +1; if (x==1) count1++; if (x==2) count2++; if (x==3) count3++; if (x==4) count4++; if (x==5) count5++; if (x==6) count6++; cout<<x<<endl;} cout<<1<<" : "<<count1<<endl; cout<<2<<" : "<<count2<<endl; cout<<3<<" : "<<count3<<endl; cout<<4<<" : "<<count4<<endl; cout<<5<<" : "<<count5<<endl; cout<<6<<" : "<<count6<<endl; }
  113. 113. #include <iostream.h> #include <cstdlib> void main() { int x,count[7]={0}; for( int i=1;i<=1200;i++) { x=rand()%6 +1; if (x==1) count[1]++; if (x==2) count[2]++; if (x==3) count[3]++; if (x==4) count[4]++; if (x==5) count[5]++; if (x==6) count[6]++; cout<<x<<endl;} for(i=1;i<=6;i++) cout<<i<<" : "<<count[i]<<endl; } A program to count the occurrence of each random number
  114. 114. The same example using Switch statement #include <iostream.h> #include <cstdlib> void main() { int x,count[7]={0}; for( int i=1;i<=1200;i++) { x=rand()%6 +1; switch(x) { case 1: count[1]++; break; case 2: count[2]++; break; case 3: count[3]++; break; case 4: count[4]++; break; case 5: count[5]++; break; case 6: count[6]++; } } for(i=1;i<=6;i++) cout<<i<<" : "<<count[i]<<endl; }
  115. 115. • Do the same prev. example, • Count the number of even numbers, and the number of odd numbers.
  116. 116. #include <iostream.h> #include <cstdlib> void main() { int x,even=0,odd=0; for( int i=1;i<=1200;i++) { x=rand()%6 +1; switch(x) { case 1: case 3: case 5: odd++; break; case 2: case 4: case 6: even++; } } cout<<"Even count is "<<even<<endl; cout<<"Odd count is "<<odd<<endl; }
  117. 117. #include <iostream.h> #include <cstdlib> void main() { int x,count[7]={0}; for( int i=1;i<=1200;i++) { x=rand()%6 +1; count[x]++; cout<<x<<endl;} for(i=1;i<=6;i++) cout<<i<<" : "<<count[i]<<endl; }
  118. 118. User Defined Functions • Write a function that calculates and returns the square value of a double number:
  119. 119. #include <iostream.h> double square(double); // function prototype void main( ) {double x,y; cout<<“Enter a number :”; cin>>x; y=square(x); cout<<x<<“ squared = “<<y<<endl; } double square(double a) { double b; b=a*a; return b; }
  120. 120. Another user defined function • Write a program to calculate and print a rectangle area, the program should use a function to calculate and returns the area of a rectangle to the main program? • This function should take the length and the width , and should return the area
  121. 121. #include <iostream.h> double area(double,double); // function prototype void main( ){ double L,W,A; cout<<“Enter the length:”; cin>>L; cout<<“Enter the width:”; cin>>W; A=area(L,W); cout<<“The area of the recangle is “<<A; } double area(double X,double Y) { double Z; Z=X*Y; return Z; }
  122. 122. • Write a program that finds and prints the maximum of three integer numbers, The program should use a function to find the maximum value.
  123. 123. #include <iostream.h> int max(int,int,int); void main(){ int x,y,z; cout<<"Enter 3 numbers please :"; cin>>x>>y>>z; cout<<"The Maximum is "<<max(x,y,z)<<endl; } int max(int a,int b,int c) {int m; m=a; if (m<b) m=b; if (m<c) m=c; return m;}
  124. 124. #include <iostream.h> #include <cmath> bool prime(int); void main(){ int x; cout<<"Enter a number please :"; cin>>x; if (prime(x)) cout<<x<<" is a prime numbern"; else cout<<x<<" is not a prime numbern"; } bool prime(int a) {bool p=true; for(int i=2;i<=sqrt(a);i++) if (a%i==0) { p=false; break;} return p;}
  125. 125. Build your own fabs function #include <iostream.h> double fabs(double); void main(void) { double x,y; cout<<"Enter a number "; cin>>x; y=fabs(x); cout<<"The absolute value of "<<x<<" is "<<y<<endl; } double fabs(double m) { if (m>=0) return m; else return -m; }
  126. 126. Forms of functions • Functions that take inputs and returns output: – double square(double), int max(int a, int b, int c) …. • Functions that take inputs but don’t return output – void Printsum(int x,int y) • Functions that don’t take any inputs but returns an output: • int Read_number(void); • Functions that don’t take and inputs and don’t return any input • void Print_hello(void);
  127. 127. Write a program that uses a function to calculate and print the sum of two numbers. #include <iostream.h> void print_sum(int,int); void main() {int x,y; cout<<“Enter two numbers please :”; cin>>x>>y; print_sum(x,y); } void print_sum(int x,int y) {int s; s=x+y; cout<<x<<“+”<<y<<“ = “<<s<<endl; }
  128. 128. Write a program that reads two numbers and prints the sum of them, This program should use a function to read the numbers and use another function to calculate and print the sum of two numbers
  129. 129. #include <iostream.h> void print_sum(int,int); int read_number(void); void main() {int x,y; x=read_number(); y=read_number(); print_sum(x,y); } void print_sum(int x,int y) {int s; s=x+y; cout<<x<<“+”<<y<<“ = “<<s<<endl; } int read_number(void) {int A; cout<<“Enter a number please “; cin>>A; return A; }
  130. 130. Write a progam that uses a function to print a welcome message #include <iostream.h> void print_welcome(void); void main(){ print_welcome(); } void print_welcome(void) { cout<<“Hello, Welcome in C++ functionsn”; }
  131. 131. • Modify the previous example, make the main calls the print function 10 times • Also, make the print_welcome function print a random message from 3 different messages
  132. 132. #include <iostream.h> #include<cstdlib> void print_welcome(void); void main(){ for(int i=1;i<=10;i++) print_welcome(); } void print_welcome(void) {int x=rand()%3; switch(x) {case 0: cout<<“Hello n”; break; case 1: cout<<“Welcome n”;break; case 2: cout<<“Hi, how are u n”; } }
  133. 133. Inputs for any function • The inputs for a function could be: – constants: x=sqrt( 9); – Variables x=sqrt(y); – Expression x=sqrt(y+3*z); – Or even another function x=sqrt(ceil(y/3)); • This is valid for library functions , and user defined functions also
  134. 134. Scope of variables with functions #include <iostream.h> int x=10; // global variables int f1(int); void f2(int); int f3(void); // int f3(); void main(void) {cout<<x<<endl; int x=15; cout<<x<<endl; cout<<::x<<endl; for (int i=1;i<3;i++) { int x=5; int y=x+::x; cout<<y<<" "<<x<<" "<<::x<<endl; } cout<<x<<endl; cout<<f1(x)<<endl; cout<<::x<<endl; }
  135. 135. int f1(int a) { cout<<x<<endl; int x=13; cout<<x<<endl; f2(x); cout<<::x<<endl; return x+a; } void f2(int b) {cout<<x<<endl; x=x-b; cout<<x<<endl; }
  136. 136. Aliasing #include<iostream.h> int main() { int x; int &y=x; x=5; int &z=y; cout<<x<<"t"<<y<<"t"<<z<<endl; y=7; cout<<x<<"t"<<y<<"t"<<z<<endl; y=x+z-3; cout<<x<<"t"<<y<<"t"<<z<<endl; return 0; }
  137. 137. Call By value & call By reference #include <iostream.h> int square(int); void main() { int x,y; cout<<"Enter a number "; cin>>x; y=square(x); cout<<x<<" squared is "<<y<<endl; } int square(int a) // call by value { a=a*a; return a; }
  138. 138. #include <iostream.h> void square(int &); void main() { int x; cout<<"Enter a number "; cin>>x; cout<<x<<" squared is “; square(x); cout<<x<<endl; } void square(int & a) // call by reference { a=a*a; }
  139. 139. #include<iostream.h> void read_two_numbers(int &,int &); void main() {int x,y; read_two_numbers (x,y); cout<<x<<" "<<y<<endl; } void read_two_numbers (int & a,int &b) { cout<<“Enter two numbers please “ cin>>a>>b; }
  140. 140. Static variables and default arguments #include <iostream.h> void f(int x=10 ); void main() { f(); f(5); f(7); } void f(int x) {static int abc=17; abc++; cout<<abc<<"t"<<x<<endl; }
  141. 141. Recursive functions • Factorial • Febonacci series • Sum between X, Y
  142. 142. #include <iostream.h> int fact(int); void main() { int x; cout<<"Enter a number to calculate its factorial "; cin>>x; cout<<x<<"! = "<<fact(x)<<endl; } int fact(int n) { if (n==1) return 1; else return n*fact(n-1); } Recursive fact
  143. 143. Recursive fact #include <iostream.h> int fact(int); void main() { int x; cout<<"Enter a number to calculate its factorial "; cin>>x; cout<<x<<"! = "<<fact(x)<<endl; } int fact(int n) { if (n==1) {cout<<"Now returning fact 1n"; return 1; } else {cout<<"Now calling fact "<<n-1<<endl; return n*fact(n-1); } }
  144. 144. #include <iostream.h> int fact(int); void main() { int x; cout<<"Enter a number to calculate its factorial "; cin>>x; cout<<x<<"! = "<<fact(x)<<endl; } int fact(int n) { if (n==1) {cout<<"Now returning fact 1n"; return 1; } else {cout<<"Now calling fact "<<n-1<<endl; int m= n*fact(n-1); cout<<"Returning "<<n<<"!="<<m<<endl; return m; } }
  145. 145. • Feb(0)=0 • Feb(1)=1 • Feb(n)=feb(n-1)+feb(n-2)
  146. 146. #include <iostream.h> int feb(int); void main() { int x; cout<<"Enter a number to calculate its febonacci "; cin>>x; cout<<"Feb("<<x<<") = "<<feb(x)<<endl; } int feb(int n) { if (n==0) return 0; else if (n==1) return 1; else return feb(n-1)+feb(n-2); }
  147. 147. #include <iostream.h> int feb(int); void main() { int x; cout<<"Enter a number to calculate its febonacci "; cin>>x; cout<<feb(x)<<endl; } int feb(int n){ if (n==0) return 0; else if (n==1) return 1; else return feb(n-1)+feb(n-2); }
  148. 148. Febonacci using for #include <iostream.h> int feb(int); void main() { int x; cout<<"Enter a number to calculate its febonacci "; cin>>x; cout<<feb(x)<<endl; } int feb(int n){ int fn_2=0; int fn_1=1; int fn; for(int i=2;i<=n;i++) {fn=fn_2+fn_1; fn_2=fn_1; fn_1=fn; } return fn; }
  149. 149. Sum of numbers from 1 to n #include <iostream.h> int sum(int); void main() { int x; cout<<"Enter a number to calculate the sum "; cin>>x; cout<<“Sum of the series “<<sum(x)<<endl; } int sum(int n) { if (n==1) return 1; else return n+sum(n-1); }
  150. 150. • Write a function that returns the sum of numbers from X to Y. The function should calculate the sum recursively • ∑ i = y+ ∑ i i=x y i=x y-1
  151. 151. Sum of numbers from X to Y #include <iostream.h> int sum(int,int); void main() { int x,y; cout<<"Enter two numbers to calculate the sum "; cin>>x>>y; cout<<“Sum of the series “<<sum(x,y)<<endl; } int sum (int a, int b) { if (a==b) return b; else return b+sum(a,b-1); }
  152. 152. ArrayArray Array is a set of adjacent memory locations of the same data type. All of them have one name, which is the array name. each location has subscript number started by zero. One Dimensional arrayOne Dimensional array Data_Type array_name[How many elements] ; Two Dimensional arrayTwo Dimensional array Data_Type array_name[#Rows][#Columns] ;
  153. 153. One Dimensional arrayOne Dimensional array int List[5]; 100 30 10 -20 5 List[0] List[1] list[2] list[3] list[4] Read Elements List[0] = 100; List[1] = 30; List[2] = 10; List[3] = -20; List[4] = 5; Print Elements for(i=0; i<5; i++) cout<<List[i];
  154. 154. Definitions and initial values int X[4]={4,2,3,1}; int A[10]={0}; int B[100]={1}; int C[7]={1,2,6}; int d[5]; int E[ ]={4,6,2};
  155. 155. Not accepted Statements int A[4]={4,2,4,5,2}; int E[ ]; int n=5; int X[n]; Corrected by: const int n=5; int X[n];
  156. 156. #include <iostream.h> void main() { int A[5] = {10,20,15,100,30}; for (int i=0; i<5; i++) cout<<A[i]<<'t'; for (i=0; i<5; i++) { cout<<"nPlease Enter A["<<i<<"]:"; cin>>A[i]; } for (i=0; i<5; i++) cout<<A[i]<<'t'; cout<<endl; }
  157. 157. #include <iostream.h> void main() { int A[5] = {10,20,15,100,30}; for (int i=0; i<5; i++) cout<<A[i]<<'t'; for (i=0; i<5; i++) { cout<<"nPlease Enter A["<<i<<"]:"; cin>>A[i]; } for (i=0; i<5; i++) cout<<A[i]<<'t'; cout<<endl; }
  158. 158. #include <iostream.h> void main() { const int Size = 10; char KeyBSym[Size]={ ')', '!', '@', '#', '$', '%', '^', '&', '*', '(' }; for (int i=0; i<Size; i++) cout<<"Shift + number "<<i<<" Give Symbol "<<KeyBSym[i]<<endl; }
  159. 159. #include <iostream.h> const int S = 10; void main() { int A[S]; for(int i=0; i<S; i++) { cout<<"nEnter A["<<i<<"]:"; cin>>A[i]; } int PositiveSum = 0, EvenSum = 0, Gthan10_Count = 0; for (i=0; i<S; i++) { if (A[i]>0) PositiveSum += A[i]; if (A[i]%2 == 0) EvenSum += A[i]; if (A[i]>10) Gthan10_Count++; } cout<<"nSummation of positive Elements: "<<PositiveSum; cout<<"nSummation of Even Elements: "<<EvenSum; cout<<"n# Element, which are greater than 10: "<<Gthan10_Count; cout<<endl; }
  160. 160. #include <iostream.h> const int S = 10; void main() { int A[S]; for(int i=0; i<S; i++) { cout<<"nEnter A["<<i<<"]:"; cin>>A[i]; } long Even_Position_Mul = 1, Odd_Position_Mul = 1; for (i=0; i<S; i++) if(i%2==0) Even_Position_Mul *= A[i]; else Odd_Position_Mul *=A[i]; cout<<"nMultiplication of elements at Even position: "<<Even_Position_Mul; cout<<"nMultiplication of elements at Odd position: "<<Odd_Position_Mul; cout<<endl; }
  161. 161. Find the Maximum elementFind the Maximum element #include <iostream.h> const int Size = 10; void main() { int Vector[Size]; for(int i=0; i<Size; i++) cin>>Vector[i]; for(i=0; i<Size; i++) cout<<Vector[i]<<'t'; cout<<endl; int Max = Vector[0]; for(i=1; i<Size; i++) if (Max<Vector[i]) Max=Vector[i]; cout<<"nMax= "<<Max<<endl; }
  162. 162. SearchSearch #include <iostream.h> const int Size = 10; void main() { int Vector[Size]; for(int i=0; i<Size; i++) cin>>Vector[i]; cout<<endl; int Element; cout<<"What is the element that you looking for"; cin>>Element; bool Found = false; for(i=0; i<Size; i++) if(Element = = Vector[i]){ Found = true; break; } cout<<endl; if (Found) cout<<Element<<" Found at position "<<i<<endl; else cout<<Element<<" is not in the array n";}
  163. 163. Another version of search exampleAnother version of search example #include <iostream.h> const int Size = 10; void main() { int Vector[Size]; for(int i=0; i<Size; i++) cin>>Vector[i]; cout<<endl; int Element; cout<<"What is the element that you are looking for: "; cin>>Element; bool Found = false; for(i=0; i<Size; i++) if(Element == Vector[i]){ cout<<Element<<" is found at position "<<i<<endl; Found=true; } if (!Found) cout<<Element<<" is not in the array n"; }
  164. 164. Sort the elements:Sort the elements:#include <iostream.h> const int Size = 5; void main() { int Vector[Size]; for(int i=0; i<Size; i++) cin>>Vector[i]; for(i=0; i<Size; i++) cout<<Vector[i]<<'t'; cout<<endl; for(i=0; i<Size - 1; i++) for(int j=i+1; j<Size; j++) if (Vector[i]>Vector[j]) { int Temp = Vector[i]; Vector[i] = Vector[j]; Vector[j] = Temp;} for(i=0; i<Size; i++) cout<<Vector[i]<<'t'; cout<<endl; }
  165. 165. build a swap function function void swap(int & x,int & y) { int temp; temp=x; x=y; y=temp; }
  166. 166. Bubble sort using the swap function #include <iostream.h> void swap(int &,int &); const int Size = 5; void main() { int Vector[Size]; for(int i=0; i<Size; i++) cin>>Vector[i]; for(i=0; i<Size - 1; i++) for(int j=i+1; j<Size; j++) if (Vector[i]>Vector[j]) swap(Vector[i],Vector[j]); for(i=0; i<Size; i++) cout<<Vector[i]<<'t'; cout<<endl; } void swap(int & x,int & y) { int temp; temp=x; x=y; y=temp; }
  167. 167. Arrays and Call by reference • We can’t return the array using return statement. • We need to use the call by reference technique. • BUT when passing an array to a function, it is sent as call by reference. • No need to declare it as int &[ ]
  168. 168. Write a function that return the sum of an array#include <iostream.h> int Arr_Sum(int [ ],int); void main( ) { int A[5]={2,3,4,5,6}; int B[4]={5,3,1,7}; cout<<"The sum of A is "<<Arr_Sum(A,5)<<endl; cout<<"The sum of B is "<<Arr_Sum(B,4)<<endl; } int Arr_Sum(int x[ ],int size) {int S=0; for(int i=0;i<size;i++) S=S+x[ i ]; return S; }
  169. 169. Functions to Read and print arrays #include <iostream.h> void Arr_read(int [ ],int); void Arr_print(int[ ],int); void main(){ int A[5]; int B[4]; Arr_read(A,5); Arr_read(B,4); Arr_print(A,5); Arr_print(B,4);} void Arr_read(int x[ ],int size) { for(int i=0;i<size;i++) {cout<<"Enter a number please "; cin>>x[i];} } void Arr_print(int x[ ],int size) {for(int i=0;i<size;i++) cout<<x[i]<<" "; cout<<endl; }
  170. 170. Function to calculate the sum of two arrays#include <iostream.h> void sum(int [ ],int [ ],int[ ],int); void main() { int a[4]={4,3,2,1}; int b[4]={2,2,4,4}; int c[4]; sum(a,b,c,4); Arr_print(c,4); } void sum(int x[ ],int y[ ],int z[ ],int s) { for (int i=0;i<s;i++) z[i]=x[i]+y[i]; }
  171. 171. cout statement with setw( ) #include <iostream.h> #include <iomanip.h> void main() { for(int i=1; i<= 5;i++) // without using setw( ) cout<<i<<" "<<i*i<<" "<<i*i*i<<endl; cout<<endl; for(i=1; i<= 5;i++) // with using setw( ) cout<<setw(4)<<i<<setw(4)<<i*i<<setw(4)<<i*i*i<<endl; }
  172. 172. Strings #include <iostream.h> void main() { char n[10]; char a[10]={'A','h','m','e','d'}; for(int i=0; a[i]!=0 ; i++) cout<<a[i]<<endl; cout<<endl; }
  173. 173. Q1 in the exam #include <iostream.h> void main() { int a[4][3]; for(int i=0;i<4;i++) for(int j=0;j<3;j++) { cout<<"Enter a number "; cin>>a[i][j]; } for(int k=0;k<3;k++) { int s=0; for(int m=0;m<4;m++) s=s+a[m][k]; cout<<s<<endl; } }
  174. 174. Two Dimensional arrayTwo Dimensional array int Matrix[3][4]; 30 Assign values to Elements Matrix[0][1] = 30; Matrix[1][0] = 100; Matrix[1][2] = 10; Matrix[2][3] = -20; Matrix[2][0]=Matrix[1][2]; Print Elements for(i=0; i<3; i++){ for(j=0; j<4; j++) cout<<Matrix[i][j]<<“t”; cout<<endl; } 100 10 10 -20 0 1 2 3 0 1 2
  175. 175. int A[2][3] = { {1 ,2 , 3 }, {10,20,30}}; int Matrix[3][4]= {{0,30 }, {100,0,10}, {0,0,0,-20}};
  176. 176. #include <iostream.h> void main() { int A[2][3] = {{1,2,3},{10,20,30}}; int B[2][3] = {100,200,300,40,50,60}; int C[2][3] = {{15,25},{105,205}}; for( int i=0; i<2; i++){ for( int j=0; j<3; j++) cout<<A[i][j]<<'t'; cout<<endl; } cout<<endl; for( i=0; i<2; i++){ for( int j=0; j<3; j++) cout<<B[i][j]<<'t'; cout<<endl; } cout<<endl; for( i=0; i<2; i++){ for( int j=0; j<3; j++) cout<<C[i][j]<<'t'; cout<<endl; } }
  177. 177. #include <iostream.h> const int Rows = 3, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i<Rows; i++) for (int j=0; j<Columns; j++) { cout<<"nEnter A["<<i<<"]["<<j<<"]:"; cin>>A[i][j]; } for (i=0; i<Rows; i++){ for(int j=0; j<Columns; j++) cout<<A[i][j]<<'t'; cout<<endl; } }
  178. 178. #include <iostream.h> int A_sum(int [ ][2],int); void main(){ int x[3][2]={6,5,4,3,2,1}; int y[4][2]={5,4,3,2,3,4,1}; cout<<"The sum of the array x is “ <<A_sum(x,3)<<endl; cout<<"The sum of the array y is “ <<A_sum(y,4)<<endl; } int A_sum(int a[ ][2],int r) { int s=0; for(int i=0;i<r;i++) for(int j=0;j<2;j++) s=s+a[i][j]; return s; } Find The sum of 2-D arrays using functions`
  179. 179. Diagonal SummationDiagonal Summation #include <iostream.h> const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i<Rows; i++) for (int j=0; j<Columns; j++) { cout<<"nEnter A["<<i<<"]["<<j<<"]:"; cin>>A[i][j]; } int DSum = 0; for (i=0; i<Rows; i++) DSum += A[i][i]; cout<<"Diagonal Sum = "<<DSum<<endl; }
  180. 180. Inverse Diagonal SummationInverse Diagonal Summation #include <iostream.h> const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i<Rows; i++) for (int j=0; j<Columns; j++) { cout<<"nEnter A["<<i<<"]["<<j<<"]:"; cin>>A[i][j]; } int DSum = 0; for (i=0; i<Rows; i++) for (int j=0; j<Columns; j++) if ( i+j= = 3) DSum += A[i][j]; cout<<"Diagonal Sum = "<<DSum<<endl; }
  181. 181. Lower Triangular MultiplicationLower Triangular Multiplication #include <iostream.h> const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i<Rows; i++) for (int j=0; j<Columns; j++) { cout<<"nEnter A["<<i<<"]["<<j<<"]:"; cin>>A[i][j]; } long LTmul = 1; for (i=1; i<Rows; i++) for(int j=0; j<i; j++) LTmul *= A[i][j]; cout<<"Lower Traingular Mul = "<<LTmul<<endl; }
  182. 182. Lower Triangular MultiplicationLower Triangular Multiplication #include <iostream.h> const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns]; for (int i=0; i<Rows; i++) for (int j=0; j<Columns; j++) { cout<<"nEnter A["<<i<<"]["<<j<<"]:"; cin>>A[i][j]; } long LTmul = 1; for (i=0; i<Rows; i++) for(int j=0; j<Columns,; j++) if (i>j) LTmul *= A[i][j]; cout<<"Lower Traingular Mul = "<<LTmul<<endl; }
  183. 183. Write a Program that copies an array to another #include <iostream.h> const int R = 4, C= 3; void main() { int A[R][C]; int B[R][C]; for (int i=0; i<R; i++) for (int j=0; j<C; j++) { cout<<"nEnter A["<<i<<"]["<<j<<"]:"; cin>>A[i][j]; } for (i=0 ;i<R;i++) for(int j=0;i<C;j++) B[i][j]=A[i][j]; for (i=0; i<R; i++){ for(int j=0; j<C; j++) cout<<B[i][j]<<'t'; cout<<endl; } }
  184. 184. Write a function that copies a 2-D array to another void copyA(int x[ ][3],int y[ ][3],int r) { for(int i=0;i<r;i++) for(int j=0;j<3;j++) y[i][j]=x[i][j]; }
  185. 185. Write a Program that copies an array to another #include <iostream.h> const int R = 4, C= 3; void main() { int A[R][C]; int B[R][C]; for (int i=0; i<R; i++) for (int j=0; j<C; j++) { cout<<"nEnter A["<<i<<"]["<<j<<"]:"; cin>>A[i][j]; } copyA(A,B,4); for (i=0; i<R; i++){ for(int j=0; j<C; j++) cout<<B[i][j]<<'t'; cout<<endl; } }
  186. 186. Store the following symbols in theStore the following symbols in the array Symbol.array Symbol. * $ $ $ # * $ $ # # * $ # # # * #include <iostream.h> const int Rows = 4, Columns = 4; void main() { char Symbol[Rows][Columns]; for (int i=0; i<Rows; i++) for (int j=0; j<Columns; j++) if (i == j) Symbol[i][j] = '*'; else if (i > j) Symbol[i][j] = '#'; else Symbol[i][j] = '$'; for (i=0; i<Rows; i++){ for(int j=0; j<Columns; j++) cout<<Symbol[i][j]; cout<<endl; } }
  187. 187. Matrix Matrix SummationMatrix Matrix Summation #include <iostream.h> const int Rows = 4, Columns = 4; void main() { int A[Rows][Columns], B[Rows][Columns], C[Rows][Columns]; cout<<"nEnter Matrix A elements:n"; for (int i=0; i<Rows; i++) for( int j=0; j<Columns; j++) cin>>A[i][j]; cout<<"nEnter Matrix B elements:n"; for (i=0; i<Rows; i++) for( int j=0; j<Columns; j++) cin>>B[i][j]; for(i=0; i<Rows; i++) for(int j=0; j< Columns; j++) C[i][j] = A[i][j] + B[i][j]; for(i=0; i<Rows; i++){ for(int j=0; j<Columns; j++) cout<<C[i][j]<<'t'; cout<<endl; } }
  188. 188. Write a function to add two Arrays void add(int x[ ][4],int y[ ][4],int z[ ][4],int r) { }
  189. 189. Compute the average for 5 marks for 10 students int marks [10][5]; for(int i=0;i<10;i++) for(int j=0;j<5;j++) { cout<<“Enter mark”<<j+1<<“ for student”<<i+1; cin>>marks[i][j];} float av[10]; for(i=0;i<10;i++) { float sum=0; for(int j=0;j<5;j++) sum=sum+marks[i][j]; av[i]=sum/5;} printing……
  190. 190. int A[3][4], B[4][3]; for(int i=0;i<3;i++) for(int j=0;j<4;j++) cin>>A[i][j]; for(i=0;i<3;i++) for(int j=0;j<4;j++) B[ j][i]=A[i][j] Printing B ……..
  191. 191. Function to calculate the Transpose of an array 3x4 void trans34(int x[3][4],int y[4][3]) { for(int r=0;r<3;r++) for(int c=0;c<4;c++) y[c][r]=x[r][c]; }
  192. 192. HomeworkHomework 1- Write program to compute and print the result of Matrix A[n][n] multiplied by Matrix B[n][n] and store the result within Matrix C[n][n]. 2- Write program to Compute and print the result of Matrix A[n][n] multiplied by Vector V[n] and store the result within Vector C[n].
  193. 193. Calculate an accurate value for Pi double Pi=0; for(int i=0;i<=1000;i++) if( i%2==0) Pi=Pi+4.0/(2*i+1); else Pi=Pi-4.0/(2*i+1);
  194. 194. double pi; int t=1; for(int i=1;i<=1000;i=i+2) { pi=pi+t*4.0/i; t=t*-1; }
  195. 195. Strings #include <iostream.h> void main() { char n[10]; char a[10]={'A','h','m','e','d'}; for(int i=0; i<5 ; i++) cout<<a[i]<<endl; }
  196. 196. #include <iostream.h> void main() { char a[10]={'I','b','r','a','h','e','e','m‘}; for(int i=0; a[i]!=0 ; i++) cout<<a[i]<<endl; }
  197. 197. #include <iostream.h> void main() { char a[10]={'A','h','m','e','d'}; for(int i=0; a[i]!=0 ; i++) {for(int j=0;j<i;j++) cout<<" "; cout<<a[i]<<endl; } }
  198. 198. #include <iostream.h> void main() { char a[10]=“Ahmed“; for(int i=0; a[i]!=0 ; i++) {for(int j=0;j<i;j++) cout<<" "; cout<<a[i]<<endl; } }
  199. 199. #include <iostream.h> void main() { char a[10]; cout<<"Enter a name : "; cin>>a; cout<<a<<endl; for(int i=0; a[i]!=0 ; i++) {for(int j=0;j<i;j++) cout<<' '; cout<<a[i]<<endl; } }
  200. 200. #include <iostream.h> void main() { char a[10]; char b[10]; cout<<"Enter ur first name : "; cin>>a; cout<<"Enter ur second name : "; cin>>b; cout<<"Hello "<<a<<" "<<b<<endl; for(int i=0; a[i]!=0 ; i++) {for(int j=0;j<i;j++) cout<<' '; cout<<a<<endl; } }
  201. 201. #include <iostream.h> void main() { char a[10]; cout<<"Enter a name : "; cin>>a; cout<<a<<endl; for(int i=0; a[i]!=0 ; i++) {for(int j=0;j<i;j++) cout<<' '; cout<<a<<endl; } cout<<i<<endl; }
  202. 202. Final exam question • Write a function that returns the length of a string or array of characters. • The function prototype is • int length(char[ ]);
  203. 203. int length(char name[ ]) { for(int i=0;name[i]!=0;i++) ; return i; }
  204. 204. #include <iostream.h> void main() { char name[10]; cout<<"Enter ur name : "; cin>>name; for(int i=0; name[i]!=‘0’ ; i++); for(int j=i-1;j>=0;j--) cout<<name[j]; cout<<endl; }
  205. 205. Write a program that prints the name inversed( from the last char to the first character • See the prev. slide
  206. 206. Pointers #include <iostream.h> void main() { int x=5; int* y; // pointer to an integer y=&x; cout<<x<<endl<<&x<<endl; cout<<y<<endl<<*y<<endl; }
  207. 207. #include <iostream.h> void main() { char a[10]="Ahmad"; // prints Ahmed cout<<a<<endl; int b[10]={1,2,3,4,5}; cout<<b<<endl; // prints the address of //the first element in the array }
  208. 208. #include <iostream.h> void main() { char a[10]="Ahmad"; // prints Ahmed cout<<a<<endl; int b[10]={1,2,3,4,5}; cout<<b<<endl; // prints the address of //the first element in the array int x=5; int* y; // pointer to an integer y=&x; cout<<x<<endl<<&x<<endl; cout<<y<<endl<<*y<<endl; }
  209. 209. 1- do-while statement. 2- nested for loop 3- nested while statement 4- math library functions. 5- functions prototype and definitions. 6- rand () and srand() functions 7- scope rules (local, global and static variables) 8- Recursion 9- call by value and reference 10- Inline function 11- :: scope resolution operator. 12- one dim array only ( definition and passing one dim array to a function).

×