You are on page 1of 272

www.aabu.edu.

jo
C++ Programming

1
‫وائل قصاص‬
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

2
‫وائل قصاص‬
General form of C++ Program
#include <iostream>
using namespace std;
void main() {
.
.
C++ statements
.
.
}
Remark: C++ language is case sensitive
3
‫وائل قصاص‬
Problem : Compute and print the summation
of two numbers.
Program
#include <iostream>
using namespace std;

void main() {
int a, b, s;
cout<<"Please Enter two numbers:";
cin>>a>>b;
s = a + b;
cout<<"s="<<s<<endl;
} 4
‫وائل قصاص‬
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.
5
- \n or endl: to start new line at output screen.‫وائل قصاص‬
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
6
‫وائل قصاص‬
Data Types
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.)

Variable declaration
Type Variable_name
7
‫وائل قصاص‬
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

8
‫وائل قصاص‬
Variable names
• int X,x,Number, IF,If,iF,a7,Total_sum;
• float _abc;

9
‫وائل قصاص‬
Problem : Compute and print the average of
three numbers.
Program
#include <iostream>
using namespace std;

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<<"Average = \t"<<average<<endl;
}
Remark: \t to leave tab spaces 10
‫وائل قصاص‬
Problem : Compute the area of the circle.
Where area = π x R2
Program
#include <iostream>
using namespace std;
void main() {
const double Pi = 3.14;
int r;
cout<<"Please enter r : ";
cin>>r;
double a;
a = Pi * r * r;
cout<<"Circle's Area = "<<a<<endl;} 11
‫وائل قصاص‬
Examples on integer division
#include <iostream>
using namespace std;
void main( )
{
int x;
x=1/3*3; // 1/3=0
cout<<x<<endl;
x=1.0/3*3;
cout<<x<<endl;
}
12
‫وائل قصاص‬
Boolean variables and relational
operations
#include <iostream>
using namespace std;
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; 13
} ‫وائل قصاص‬
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; 14
‫وائل قصاص‬
Priority
• * , / , % have the same priority ( High )
• + , - have the same priority (Low)

15
‫وائل قصاص‬
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
……………………..
16
‫وائل قصاص‬
If Statement in C++
One way if
if ( Condition )
statement;

if ( Condition ) {
statements; }

17
‫وائل قصاص‬
Problem : Read any number from the user,
then print positive if it is positive.

Program
#include <iostream>
using namespace std;
void main() {
int Num;
cout<<"Please Enter an integer number:";
cin>>Num;
if (Num > 0)
cout<<" Positive\n";
} 18
‫وائل قصاص‬
Another Version
#include <iostream>
using namespace std;
void main() {
int Num;
bool w;
cout<<"Please Enter an integer number:";
cin>>Num;
w=Num>0;
if (w)
cout<<" Positive\n";
19
} ‫وائل قصاص‬
If Statement in C++
Two way if
if ( Condition )
statement;
else
statement;

if ( Condition ) {
statements; }
else {
statements;}
20
‫وائل قصاص‬
Write a program that reads a mark,
if mark is 60 or greater, the program
prints PASS, else it will print FAIL
#include <iostream>
using namespace std;
void main() {
int mark;
cout<<"Please Enter your mark: ";
cin>>mark;
if (mark>=60)
cout<<" PASS\n";
else
cout<<"FAIL\n";
} 21
‫وائل قصاص‬
More than one statement in the if
#include <iostream>
using namespace std;
void main() {
int mark;
cout<<"Please Enter your mark: ";
cin>>mark;
if (mark>=60)
{
cout<<" PASS\n";
cout<<" you can take Object course now\n";
}
else
{
cout<<"FAIL ";
cout<<"You must take this course again\n";
} 22
} ‫وائل قصاص‬
Write a program that prints the the
fraction from the format a/b to c d/b
example: 7/3= 2 1/3

#include <iostream>
using namespace std;
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; 23
} ‫وائل قصاص‬
Enhancement on the previous example
#include <iostream>
using namespace std;
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; 24
} ‫وائل قصاص‬
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.

25
‫وائل قصاص‬
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

26
‫وائل قصاص‬
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

27
‫وائل قصاص‬
Evaluating Logical
Expressions
• The truth table
(1) AND table

&& True False


True True False
False False False

28
‫وائل قصاص‬
(2) OR table
|| True False
True True True
False True False

(3) NOT table


! True False
False True
29
‫وائل قصاص‬
Arithmetic  Relational  Logical
• NOTES
1) A relational expression may contain arithmetic
2) subexpressions,
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 ) 30
‫وائل قصاص‬
Operator Precedence
Operator Description Precedence
() parentheses Highest
+, – , ! unary plus, unary minus,
Not
*, /, %
+, - Binary plus, binary minus
<, <=, >, >=
== , != Equal, not equal
&&
||
= Assignment Lowest
31
‫وائل قصاص‬
Examples
• Find the value of the following expression:
(1) 5 + 8 * 2 / 4

16

9 (This is the final result)


32
‫وائل قصاص‬
Find the value of the following expression

(9 + 3) - 6 / 3 + 5

12

10`

15 (this is the final result)


33
‫وائل قصاص‬
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)

34
‫وائل قصاص‬
Another example
• X=true, Y=false, Z= true

X || Y && Z
true

• X=true, Y=false, Z= false


X || Y && Z
true
35
‫وائل قصاص‬
Find the value of the following Expression

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)


36
‫وائل قصاص‬
What is the output of the following code:
Program
#include <iostream>
using namespace std;

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<<" is\t"<<(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; 37
‫وائل قصاص‬
}
Problem : Read any number from the user,
then print positive if it is positive and print
negative otherwise.
Program
#include <iostream>
using namespace std;
void main() {
int Num;
cout<<"Please Enter Number:";
cin>>Num;
if (Num < 0)
cout<<"Negative\n";
else
cout<<"Positive\n";
} 38
‫وائل قصاص‬
Problem : Read Two numbers from the user,
then print the greatest one.
Program
#include <iostream>
using namespace std;
void main() {
int x,y;
cout<<"Please Enter two numbers:";
cin>>x>>y;
cout<<"Max = ";
if (x > y)
cout<<x<<endl;
else
cout<<y<<endl; 39
} ‫وائل قصاص‬
Problem : Read three numbers to print the
smallest one.
Program
#include <iostream>
using namespace std;
void main() {
int a, b, c;
cout<<"Please Enter three numbers:";
cin>>a>>b>>c;
cout<<"Min= ";
if ((a < b) && (a < c))
cout<<a;
if ((b < a) && (b < c))
cout<<b;
if ((c < a) && (c < b))
cout<<c;
40
cout<<endl;
‫وائل قصاص‬
}
Program2 (Nested if)
#include <iostream>
using namespace std;
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; 41
cout<<endl;} ‫وائل قصاص‬
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>
using namespace std;
void main() {
int Number;
cout<<"Please enter Number:";
cin>>Number;
if (Number>0) {
Number = Number + 10;
cout<<Number<<" is Positive\n";}
else {
Number = Number - 10;
cout<<Number<<" is Negative\n";}}
42
‫وائل قصاص‬
Example on dangling else
if ( x>y)
if ( x<z)
cout<<" Hello";
else
cout<<"Hi";

43
‫وائل قصاص‬
Another idea
if ( x>y)
{if ( x<z)
cout<<" Hello";}
else
cout<<"Hi";

44
‫وائل قصاص‬
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; 45
‫وائل قصاص‬
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 .

46
‫وائل قصاص‬
What is the output of the following C++
Source Code Program
#include <iostream>
using namespace std;
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 = false\n";
else 47
cout<<"\n a = true\n"; ‫وائل قصاص‬
}
#include <iostream> Examples
using namespace std;
void main ( )
{int X=5;
int Y=7;
int z;
X++;
cout<<X<<endl;
++X;
cout<<X<<endl;
cout<<X++<<endl;
cout<<++X<<endl;
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;} 48
‫وائل قصاص‬
Loop (iteration statements)
used to repeat subcode number of times

there are three loop techniques:


1- for Loop.
2- while Loop.
3- do … while Loop

49
‫وائل قصاص‬
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. 50
‫وائل قصاص‬
Problem : Print the word "Amman" five
times.
Program
#include <iostream>
using namespace std;
void main( ) {
for (int i=1; i<=5; i++)
cout<<"Amman\n";
}
Another Program
#include <iostream>
using namespace std;
void main() {
for (int i=5; i>=1; i--)
cout<<"Amman\n";
51
}
‫وائل قصاص‬
Problem : Print the following numbers.
1 3 5 7 9 11

Program
#include <iostream>
using namespace std;
void main( ) {
for (int k=1; k<=11; k+=2)
cout<<k<<"\t";
cout<<endl;
}

52
‫وائل قصاص‬
Problem : Print the following numbers.
20 17 14 11 8 5 2

Program

#include <iostream>
using namespace std;
void main() {
for (int m=20; m>=2; m-=3)
cout<<m<<"\t";
cout<<endl;
}

53
‫وائل قصاص‬
Another Version of the previous
example
#include <iostream>
using namespace std;
void main( ) {
int m;
for (m=20; m>=2; m-=3)
cout<<m<<"\t";
cout<<endl;
} 54
‫وائل قصاص‬
Another Version of the previous
example
#include <iostream>
using namespace std;
void main( ) {
int m=20;
for (; m>=2; m-=3)
cout<<m<<"\t";
cout<<endl;
} 55
‫وائل قصاص‬
Quiz

• Write a program that prints the numbers


from X to Y, with step Z , using for
statement. The program should read X, Y,
Z then start the loop

56
‫وائل قصاص‬
Problem : Print the following numbers.
1 2 3 4 … n(entered by user)

Program
#include <iostream>
using namespace std;
void main() {
int n;
cout<<"\nPlease enter the upper limit:";
cin>>n;
for (int i=1; i<=n; i++)
cout<<i<<"\t";
cout<<endl;
} 57
‫وائل قصاص‬
Problem : Print the following numbers.
L (entered By user) (L+1) (L+2) … U (entered By user)

#include <iostream> Program


using namespace std;
void main() {
int L,U;
cout<<"Enter the start value:";
cin>>L;
cout<<"Enter the end value:";
cin>>U;
for (int i=L; i<=U; i++)
cout<<i<<"\t";
cout<<endl;
58
} ‫وائل قصاص‬
Problem : Read five numbers from the user and print
the positive numbers only.
Program
#include <iostream>
using namespace std;
void main()
{
int num;
for(int i=1; i<=5; i++)
{
cout<<"Please Enter No "<<i<<':';
cin>>num;
if (num > 0)
cout<<num<<" is positive\n";}
}
59
‫وائل قصاص‬
Problem : Read five numbers from the user and print
the positive numbers only.

#include <iostream>
using namespace std;
void main()
{ int num;
for (int i=1; i<=5; i++)
{ cout<<"Please Enter No "<<i<<':';
cin>>num;
if (num < 0)
continue;
cout<<num<<" is positive\n";
}
} 60
‫وائل قصاص‬
Problem : Compute and print S, Where
S = 1+ 2+ 3+ 4+ 5
Program

#include <iostream>
using namespace std;
void main() {
int S=0;
for (int i=1; i<=5; i++)
S+=i;
cout<<"Sum is "<<S<<endl;
}
61
‫وائل قصاص‬
Problem : Compute and print S, Where
Sum = 1+ 3+ 5+ 7+ … + n
Program
#include <iostream>
using namespace std;
void main( ) {
int Sum=0, n;
cout<<"Please Enter n";
cin>>n;
for (int i=1; i<=n; i+=2)
Sum+=i;
cout<<"Sum="<<Sum<<endl;
62
} ‫وائل قصاص‬
Problem : print the following formula
Sum = 1+ 3+ 5+ 7+ … + n
Program
#include <iostream>
using namespace std;
void main( ) {
int n;
cout<<"Please Enter n";
cin>>n;
cout<<"Sum= ";
for (int i=1; i<=n; i+=2)
cout<<i<<"+";
cout<<"\b \n";
} 63
‫وائل قصاص‬
Problem : Compute and print the summation
of any 10 numbers entered by the user.

Program
#include <iostream>
using namespace std;
void main() {
int S=0, N;
for (int i=10; i>=1; i--)
{cout<<"Please Enter the next number:";
cin>>N;
S+=N;}
cout<<"S="<<S<<endl;}

64
‫وائل قصاص‬
Problem : Compute and Print the factorial of
the number 5. (Fact = 5 * 4 * 3 * 2 * 1)

Program

#include <iostream>
using namespace std;
void main( ) {
int Fact=1;
for (int j=5; j>=1; j--)
Fact *= j;
cout<<"5! = "<<Fact<<endl;
}
65
‫وائل قصاص‬
A program to find n!
#include <iostream>
using namespace std;
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;
}
66
Try it on n = 17 ??? ‫وائل قصاص‬
Problem : Compute and Print the value of M
where M = 2 * 4 * 6 * … * n
Program
#include <iostream>
using namespace std;
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;
}
67
‫وائل قصاص‬
Problem : Compute and Print Mn
Program
#include <iostream>
using namespace std;
void main() {
long Result=1;
int M, n;
cout<<"Enter the Base number:";
cin>>M;
cout<<"Enter the exponent:";
cin>>n;
for (int i=1; i<=n; i++)
Result *= M;
cout<<"Result= "<<Result<<endl;} 68
‫وائل قصاص‬
Write a program that finds Mn for
positive & negative n
• H.W.

69
‫وائل قصاص‬
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. 70
‫وائل قصاص‬
Problem : Print the word "Amman" five
times.
Program

#include <iostream>
using namespace std;
void main() {
int i=1;
while (i<=5)
{
cout<<"Amman\n";
i++;
}
}
71
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main() {
int i=1;
while (i++<=5)
{
cout<<"Amman\n";
}
cout<<i<<endl;
}

72
‫وائل قصاص‬
Problem : Print the following numbers.
1 3 5 7 9 11
Program
#include <iostream>
using namespace std;
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 73
output. ‫وائل قصاص‬
Problem : Print the following numbers.
20 17 14 … n
Program
#include <iostream>
using namespace std;
void main() {
int n, k=20;
cout<<"Enter the lower limit:";
cin>>n;
while ( k >= n) {
cout<<k<<'\t';
k -= 3; }
cout<<endl;}

Remark:
Write k-=3 instead of k in the above condition. What you 74
have to do to produce the same output. ‫وائل قصاص‬
Problem : Read five numbers from the user and print
the positive numbers only.
Program
#include <iostream>
using namespace std;
void main() {
int num, j=0;
while ( j++ < 5 ) {
cout<<"Enter the next num:";
cin>>num;OH
if (num > 0)
cout<<num<<endl; }}

Remark:
Solve the above problem by using continue statement. 75
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main() { Sum for the
int sum=0,i,x,y; numbers from
cout<<"Enter x,y please: "; X to y
cin>>x>>y;
i=x;
while ( i <=y) {

sum+=i;
i++;

}
cout<<"The Sum for the numbers from "<<x<<" to "
<<y<<" = "<<sum<<endl;
}
76
‫وائل قصاص‬
Problem : Compute and print S, Where
Sum = 1+ 3+ 5+ 7+ … + n
Program

#include <iostream>
using namespace std;
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;
} 77
‫وائل قصاص‬
Problem : Read 10 numbers by the user and
compute and print the summation of
numbers, which are divisible by 3.
Program
#include <iostream>
using namespace std;
void main() {
int Num, Sum=0, i=1;
while ( i <= 10 ) {
cout<<"Enter a number:";
cin>>Num;
if (Num % 3 == 0)
Sum += Num;
i++;
}
78
cout<<"\nSum="<<Sum;
‫وائل قصاص‬
}
Problem : Compute and Print the value of M
where M = 2 * 4 * 6 * … * n
Program
#include <iostream>
using namespace std;
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;
} 79
‫وائل قصاص‬
#include <iostream>
using namespace std;
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;
}
80
‫وائل قصاص‬
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.


81
‫وائل قصاص‬
Problem : Print the word "Amman" five
times.
Program

#include <iostream>
using namespace std;
void main( ) {
int i = 1;
do {
cout<<"Amman\n";
i++;
} while (i <= 5);
}
82
‫وائل قصاص‬
Execute the following program
#include <iostream>
using namespace std;
void main() {
int Choice, Num;
‫نفّذ‬
do {
cout<<"\n Enter the New Number";
cin>>Num;
if (Num % 2 == 0)
cout<<Num<<" is Even\n";
else
cout<<Num<<" is Odd\n";
cout<<"Select your choice.\n";
cout<<"1- Exit. (Terminate the Run)\n";
cout<<"2- Enter New Number to Check.\n";
cin>>Choice;
83
} while (Choice != 1);
‫وائل قصاص‬
}
#include <iostream>
using namespace std;
void main() {
int Num; char Choice;
do {
cout<<"\n Enter the New Number";
cin>>Num;
if (Num % 2 == 0)
cout<<Num<<" is Even\n";
else
cout<<Num<<" is Odd\n";
cout<<"Enter Y to continue, any other character to exit
\n";
cin>>Choice;
} while (Choice == 'Y' );
}
84
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main() {
int Num; char Choice;
do {
cout<<"\n Enter the New Number";
cin>>Num;
if (Num % 2 == 0)
cout<<Num<<" is Even\n";
else
cout<<Num<<" is Odd\n";
cout<<"Enter Y to continue, any other character to exit
\n";
cin>>Choice;
} while ((Choice == 'Y') || (Choice=='y')); 85
‫وائل قصاص‬
}
Homework

Resolve all problems in the presentation 5 and 6 by using the


three loop techniques: For, While, and Do … while Loops.

86
‫وائل قصاص‬
2.10 break and continue
Statements
• break statement
– Immediate exit from while, for, do/while,
switch
– Program continues with first statement after
structure
• Common uses
– Escape early from a loop
– Skip the remainder of switch

87
‫وائل قصاص‬
1 // Fig. 2.26: fig02_26.cpp
2 // Using the break statement in a for structure.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11
12 int x; // x declared here so it can be used after the loop
13
14 // loop 10 times
15 for ( x = 1; x <= 10; x++ ) {
16
Exits for structure when
17 // if x is 5, terminate loop break executed.
18 if ( x == 5 )
19 break; // break loop only if x is 5
20
21 cout << x << " "; // display value of x 88
22 ‫وائل قصاص‬
23 } // end for
24
25 cout<< "\nBroke out of loop when x became "<< x <<endl;
26
27 return 0; // indicate successful termination
28
29 } // end function main

1234
Broke out of loop when x became 5

89
‫وائل قصاص‬
2.10 break and continue
Statements
• continue statement
– Used in while, for, do/while
– Skips remainder of loop body
– Proceeds with next iteration of loop
• while and do/while structure
– Loop-continuation test evaluated immediately
after the continue statement
• for structure
– Increment expression executed
90
– Next, loop-continuation test evaluated ‫وائل قصاص‬
1 // Fig. 2.27: fig02_27.cpp
2 // Using the continue statement in a for structure.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function main begins program execution
9 int main()
10 {
11 // loop 10 times
12 for ( int x = 1; x <= 10; x++ ) { Skips to next iteration of the
loop.
13
14 // if x is 5, continue with next iteration of loop
15 if ( x == 5 )
16 continue; // skip remaining code in loop body
17
18 cout << x << " "; // display value of x
19 91
20 } // end for structure ‫وائل قصاص‬
21
22 cout<< "\nUsed continue to skip printing the value 5"
23 << endl;
24
25 return 0; // indicate successful termination
26
27 } // end function main

1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5

92
‫وائل قصاص‬
2.8 switch Multiple-Selection Structure
• switch
– Test variable for multiple values
– Series of case labels and optional default case
switch ( variable ) {
case value1: // taken if variable == value1
statements
break; // necessary to exit switch

case value2:
case value3: // taken if variable == value2 or ==
value3
statements
break;

default: // taken if variable matches no other


cases
statements 93
break; ‫وائل قصاص‬
}
94

2.8 switch Multiple-Selection


Structure

94
‫وائل قصاص‬
#include<iostream> 95
using namespace std; Example on
void main() switch
{ int a;
cout<<" Enter an Integer between 0 and 10: "; statement
cin>>a;
switch(a)
{ case 0:
case 1: cout<<"hello ";
case 2: cout<<"there ";
case 3: cout<<"Welcome to ";
case 4: cout<<"C++ "<<endl;
break;
case 5: cout<<"How ";
case 6:
case 7:
case 8: cout<<"are you "<<endl;
break;
case 9: break;
case 10: cout<<"Have a nice day. "<<endl;
break;
default: cout<<"Sorry, the number is out of range."<<endl; } 95
cout<< " out of switch structure."<<endl; } //main ‫وائل قصاص‬
#include <iostream> 96
using namespace std;
void main( ) { Another switch example
int score;
char grade;
cout<<"enter your score";
cin>>score;
switch(score/10){
case 0: case 1: case 2:
case 3: case 4: case 5: grade = 'F';
break;
case 6: grade = 'D';
break;
case 7: grade = 'C';
break;
case 8: grade = 'B';
break;
case 9: case 10: grade = 'A';
break;
default: cout<<"Invalid test score."<<endl; }
cout<<"Grade is"<<grade<<endl;
} // end main 96
‫وائل قصاص‬
97

switch examples
#include <iostream>
using namespace std;
void main( )
{
char grade;
cout <<" Enter grade as a letter : ";
cin>>grade;
switch(grade)
{case 'A': cout<<"The Grade is A\n";
break;
case 'B': cout<<"The Grade is B\n";
break;
case 'C': cout<<"The Grade is C\n";
break;
case 'D': cout<<"The Grade is D\n";
break;
case 'F': cout<<"The Grade is F\n";
break;
default: cout<< "The Grade is invalid\n";
}
}
97
‫وائل قصاص‬
98
switch examples

#include <iostream>
using namespace std;
void main( )
{
int age;
cout<<"Enter your age: ";
cin>>age;
switch (age>=18)
{
case 1: cout<<"old enough to take a driving license."<<endl;
cout<< "old enough to vote."<<endl;
break;

case 0: cout<<"Not old enough to take a driving license"<<endl;


cout<< "Not old enough to vote."<<endl;
}
}
98
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main()
{int score;
cout<<"Enter ur mark ";
cin>>score;
char grade;
switch(score/10)
{ case 0: case 1: case 2: case 3: case 4: case 5:
grade = 'F'; break;
case 6: grade = 'D';
break;
case 7: grade = 'C';
break;
case 8: grade = 'B';
break;
case 9: case 10: grade = 'A';
break;
default: cout<<"Invalid test score."<<endl; } //End of switch

cout<<"Your grade is "<<grade<<endl; 99


} ‫وائل قصاص‬
Nested for
Print the following shape
#include <iostream>
using namespace std; *****
void main(){ *****
*****
int n; *****
cin>>n; *****
for(int i=1;i<=n;i++)
{ for (int j=1;j<=n;j++)
cout<<"*";
cout<<endl;
}} 100
‫وائل قصاص‬
Nested for
Problem : Draw the following shape
*
**
***
****
*****

#include <iostream>
using namespace std;
void main( ) {
for (int raw=1; raw<=5; raw++)
{
for (int C=1; C<=raw; C++)
cout<<'*';
cout<<endl; }} 101
‫وائل قصاص‬
PROBLEM : DRAW
THE FOLLOWING
SHAPE
*
#include <iostream>
using namespace std;
**
void main(){ ***
for(int i=1;i<=5 ; i++){ ****
for(int j=1 ; j<=i ; j++)
*****
cout<<"*";cout<<endl;}
for(int x=1;x<=4 ; x++){
****
for(int j=4;j>=x ; j--) ***
cout<<"*";cout<< endl;}} **
* 102
‫وائل قصاص‬
Problem : Draw the following shape
*****
****
***
**
*

#include <iostream>
using namespace std;
void main() {
for (int i=1; i<=5; i++) {
for (int j=i; j<=5; j++)
cout<<'*';
cout<<endl; }}

103
‫وائل قصاص‬
Problem : Draw the following shape
*****
****
***
**
*

#include <iostream>
using namespace std;
void main() {
for (int i=1; i<=5; i++) {
for (int j=5; j>=i; j--)
cout<<'*';
cout<<endl; }}

104
‫وائل قصاص‬
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;}
105
‫وائل قصاص‬
‫‪1,1‬‬ ‫‪1,2‬‬ ‫‪1,3‬‬ ‫‪1,4‬‬ ‫‪1,5‬‬

‫‪2,1‬‬ ‫‪2,2‬‬ ‫‪2,3‬‬ ‫‪2,4‬‬ ‫‪2,5‬‬

‫‪3,1‬‬ ‫‪3,2‬‬ ‫‪3,3‬‬ ‫‪3,4‬‬ ‫‪3,5‬‬

‫‪4,1‬‬ ‫‪4,2‬‬ ‫‪4,3‬‬ ‫‪4,4‬‬ ‫‪4,5‬‬

‫‪5,1‬‬ ‫‪5,2‬‬ ‫‪5,3‬‬ ‫‪5,4‬‬ ‫‪5,5‬‬

‫‪106‬‬
‫وائل قصاص‬
Problem : display the multiplication table for
the number 3.

#include <iostream>
using namespace std;
void main() {
for (int i=1; i<=10; i++)
cout<<"3 x "<<i<<" = "<<3*i<<endl;
}

107
‫وائل قصاص‬
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

108
‫وائل قصاص‬
for (int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
cout<<i*j<<"\t";
cout<<endl;
}

109
‫وائل قصاص‬
Problem : Read any number from the user
and print Prime if it is a prime number, or Not
prime otherwise.
#include <iostream>
using namespace std;
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 number\n";
else
cout<<num<<" is not a Prime number\n";
110
}
‫وائل قصاص‬
S=m0 + m1 + … +mn
#include <iostream>
using namespace std;
void main()
{int s=0,n,m,t;
cout<<"Enter m please 1 ";
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*=m;
s+=t;
}
cout<<s<<endl;
111
} ‫وائل قصاص‬
The same
#include <iostream>
using namespace std; as the
void main()
{int s=0,n,m,t=1; previous
cout<<"Enter m please ";
cin>>m; example
cout<<"Enter n please ";
cin>>n;
for (int i=0;i<=n;i++)
{
s=s+t;
t=t*m;
}
cout<<s<<endl;
} 112
‫وائل قصاص‬
Nested Loops
#include <iostream> 1234
using namespace std; 1234
void main() 1234
{
int j=1;
1234
while(j<=4){
int i=1;
while(i<=4){
cout<<i<<"\t";
i++;
}
j++;
cout<<endl;
}
} 113
‫وائل قصاص‬
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++; }
114
} ‫وائل قصاص‬
1
12
124
1248

for (int i=1;i<=4;i++)


{int x=1;
for(int j=1;j<=i;j++)
{cout<<x<<" ";
x=x*2;}
cout<<endl;}
115
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main()
{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;}
} 116
‫وائل قصاص‬
Functions

Chapter 3

117
‫وائل قصاص‬
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)
118
‫وائل قصاص‬
• Call by value & call By reference
• Functions on arrays
• Scope of variables &Global variables
• Recursion :
– Factorial
– Febonacci,
– Sum of numbers from x to y

119
‫وائل قصاص‬
• 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>
120
‫وائل قصاص‬
double Y; double Y;
cout<<ceil(5.2);
Y=pow( 5,4);
Y=ceil(0.1);
Y=ceil(-0.1); Y=pow(5,-4);
Y=ceil(-1.1); Y=pow(5.2,3);
Y=floor(5.2);
Y=floor(0.1); Y=pow(16,0.25);
floor(-0.1); Y=pow(0.01,0.5);
floor(-1.1); Examples Y=pow(-4,0.5); runtime error
ceil(5.2/3);
floor(ceil(5.2/3)); Y=pow(x*3/7,y-1);
fabs(-17.231);
Y=pow(floor(x/3),ceil(x/4));
fmod(5,3) ≡ 5%3
fmod(4.2,2); Y=sqrt(9);
fmod(5.1,2.5)
Y=sqrt(10);
fmod(7.7,2.5)
Y=sqrt(0.09);
121
Y=sqrt(-16); runtime error ‫وائل قصاص‬
#include <iostream>
using namespace std;
#include <cmath>

void main()
{
double A,B,C,X,Y;
cout<<"Enter an Angle : ";
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; 122
} ‫وائل قصاص‬
Problem : Read any number from the user
and print it is prime if it is, or not prime
otherwise.
#include <iostream>
using namespace std;
#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 number\n";
else
123
cout<<num<<" is not a Prime number\n";
‫وائل قصاص‬
}
Random number generator
• #include <cstdlib>
• X=rand(); // gives a random number
// between 0.. 32767

124
‫وائل قصاص‬
Program that gives 100 random
number
#include <iostream>
using namespace std;
#include <cstdlib>
void main()
{
int x;
for( int i=1;i<=100;i++)
{x=rand();
cout<<x<<endl;}
} 125
‫وائل قصاص‬
Generate 20 random numbers
between 0 - 9
#include <iostream>
using namespace std;
#include <cstdlib>
void main()
{
int x;
for( int i=1;i<=20;i++)
{x=rand()%10;
cout<<x<<endl;}
} 126
‫وائل قصاص‬
20 numbers between 1 - 10
#include <iostream>
using namespace std;
#include <cstdlib>
void main()
{
int x;
for( int i=1;i<=20;i++)
{x=rand()%10+1;
cout<<x<<endl;}
} 127
‫وائل قصاص‬
Generate 10 integer random
numbers between 5 - 7

128
‫وائل قصاص‬
Using srand function
#include <iostream>
using namespace std;
#include <cstdlib>
void main()
{
int x,seed;
cout<<"Enter the seed for the random generator ";
cin>>seed;
srand(seed);
for( int i=1;i<=10;i++)
{
x=rand();
cout<<x<<endl;} 129
} ‫وائل قصاص‬
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. 130
‫وائل قصاص‬
#include <iostream>
using namespace std;
#include <cstdlib>
void main()
{ int x,a1=0, a2=0, a3=0, a4=0, a5=0, a6=0;
for( int i=1;i<=1200;i++)
{
x=rand()%6 +1;
if (x==1) a1++;
if (x==2) a2++;
if (x==3) a3++;
if (x==4) a4++;
if (x==5) a5++;
if (x==6) a6++;
cout<<x<<endl;}
cout<<1<<" : "<<a1<<endl;
cout<<2<<" : "<<a2<<endl;
cout<<3<<" : "<<a3<<endl;
cout<<4<<" : "<<a4<<endl;
cout<<5<<" : "<<a5<<endl;
131
cout<<6<<" : "<<a6<<endl;
‫وائل قصاص‬
}
#include <iostream>
using namespace std; A program to count
#include <cstdlib> the occurrence of
void main() each random number
{ 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(int i=1;i<=6;i++)
cout<<i<<" : "<<count[i]<<endl;
132
} ‫وائل قصاص‬
#include <iostream.h>
#include <cstdlib>
void main()
{ int x,count[7]={0}; The same example
for( int i=1;i<=1200;i++)
{
x=rand()%6 +1;
using Switch statement
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++) 133
cout<<i<<" : "<<count[i]<<endl; ‫وائل قصاص‬
}
• Do the same prev. example,
• Count the number of even numbers, and
the number of odd numbers.

134
‫وائل قصاص‬
#include <iostream>
using namespace std;
#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;
} 135
‫وائل قصاص‬
#include <iostream>
using namespace std;
#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(int i=1;i<=6;i++)
cout<<i<<" : "<<count[i]<<endl;
} 136
‫وائل قصاص‬
User Defined Functions
• Write a function that calculates and returns
the square value of a double number:

137
‫وائل قصاص‬
#include <iostream>
using namespace std;
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; 138

} ‫وائل قصاص‬
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

139
‫وائل قصاص‬
#include <iostream>
using namespace std;
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 rectangle is "<<A<<endl;
}

double area(double X,double Y)


{ double Z;
Z=X*Y;
return Z;
} 140
‫وائل قصاص‬
• Write a program that finds and prints the
maximum of three integer numbers, The
program should use a function to find the
maximum value.

141
‫وائل قصاص‬
#include <iostream>
using namespace std;
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;
142
return m;} ‫وائل قصاص‬
#include <iostream>
using namespace std;
#include <cmath>
bool prime(int);

void main(){
int x;
cout<<"Enter a number please :";
cin>>x;
if (prime(x))
cout<<x<<" is a prime number\n";
else
cout<<x<<" is not a prime number\n";
}

bool prime(int a)
{bool p=true;
for(int i=2;i<=sqrt(a);i++)
if (a%i==0)
{ p=false;
break;}

return p;} 143


‫وائل قصاص‬
Build your own fabs function
#include <iostream>
using namespace std;
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; 144

} ‫وائل قصاص‬
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 Print sum(int x,int y)
• Functions that don’t take any inputs but returns an
output:
• int Read_number(void);
• Functions that don’t take an inputs and don’t
return any output
• void Print_hello(void);
145
‫وائل قصاص‬
#include <iostream>
using namespace std;
void print_sum(int,int); Write a program
void main() that uses a
{int x,y;
cout<<"Enter two numbers please :"; function to
cin>>x>>y; calculate and print
print_sum(x,y);
print_sum(y,x); the sum of two
print_sum(5,7);
} numbers.
void print_sum(int x,int y)
{int s;
s=x+y;
cout<<x<<"+"<<y<<" = "<<s<<endl;
} 146
‫وائل قصاص‬
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

147
‫وائل قصاص‬
#include <iostream>
using namespace std;
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;
148
return A;
‫وائل قصاص‬
}
#include <iostream>
using namespace std;
void print_sum(int,int);
int read_number(void);
void main()
{
print_sum(read_number(),read_number());
}

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;
149
}
‫وائل قصاص‬
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++ functions\n";
150
} ‫وائل قصاص‬
ّ
‫حول‬
• 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

151
‫وائل قصاص‬
#include <iostream>
using namespace std;
#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";
}
} 152
‫وائل قصاص‬
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

153
‫وائل قصاص‬
Scope of variables with functions
#include <iostream>
using namespace std;
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; 154
cout<<::x<<endl; ‫وائل قصاص‬
}
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;
}

155
‫وائل قصاص‬
Aliasing
#include <iostream>
using namespace std;
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; 156

} ‫وائل قصاص‬
Call By value & call By reference
#include <iostream>
using namespace std;
int square(int); call by value
void main()
{
int x;
cout<<"Enter a number ";
cin>>x;
cout<<x<<" squared is "<<square(x)<<endl;
}
int square(int a) // call by value
{
a=a*a;
return a; } 157
‫وائل قصاص‬
#include <iostream>
using namespace std; call by reference
void square(int &);

void main() Entered by user


{
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;
} 158
‫وائل قصاص‬
#include <iostream>
using namespace std;
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; 159
‫وائل قصاص‬
}
Static variables
#include <iostream>
using namespace std;
void f(int x );
void main()
{
f(2);
f(5);
f(7);
}

void f(int x)
{static int abc=17;
abc++;
cout<<abc<<"\t"<<x<<endl;
} 160
‫وائل قصاص‬
Default arguments
#include <iostream>
using namespace std;
void f(int x=10,int y=20 );
void main()
{
f();
f(5);
f(7,8);
}

void f(int x,int y)


{
cout<<x<<"\t"<<y<<endl;
} 161
‫وائل قصاص‬
Recursive functions
• Factorial
• Febonacci series
• Sum between X, Y

162
‫وائل قصاص‬
#include <iostream>
using namespace std; Recursive fact
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==0)
return 1;
else
return n*fact(n-1);
} 163
‫وائل قصاص‬
#include <iostream>
using namespace std; Recursive
int fact(int);
void main() fact
{
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 1\n";
return 1;
}
else
{cout<<"Now calling fact "<<n-1<<endl;
return n*fact(n-1);
164
}
‫وائل قصاص‬
}
#include <iostream>
using namespace std;
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 1\n";
return 1;
}
else
{cout<<"Now calling fact "<<n-1<<endl;
int m= n*fact(n-1);
cout<<"Returning "<<n<<"!="<<m<<endl;
return m;
}
} 165
‫وائل قصاص‬
The structure of Febonacci
series

• Feb(0)=0
• Feb(1)=1
• Feb(n)=feb(n-1)+feb(n-2)

166
‫وائل قصاص‬
#include <iostream>
using namespace std;
int feb(int);
void main()
{
int x;
cout<<"Enter a number to calculate its febonacci : "; Enrered by
cin>>x; user
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);
167
}
‫وائل قصاص‬
#include <iostream>
using namespace std;
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); 168
} ‫وائل قصاص‬
#include <iostream>
using namespace std;
int feb(int);
Fibonacci
void main()
{
using for
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;
}
169
return fn;
‫وائل قصاص‬
}
Sum of numbers from 1 to n
#include <iostream>
using namespace std;
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;
}
We can put >>if (n==0)return 0;
int sum(int n)
{
if (n==1)
return 1;
else
170
return n+sum(n-1);
‫وائل قصاص‬
}
• Write a function that returns the sum of
numbers from X to Y. The function should
calculate the sum recursively
y y-1
• ∑ i = y+ ∑ i
i=x i=x

171
‫وائل قصاص‬
Sum of numbers from X to Y
#include <iostream>
using namespace std;
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) We can return “a”(the same)


{
if (a==b)
return b;
else
return b+sum(a,b-1); 172
} ‫وائل قصاص‬
Array
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 array


Data_Type array_name[How many elements] ;

Two Dimensional array


Data_Type array_name[#Rows][#Columns] ;

173
‫وائل قصاص‬
One Dimensional array
int List[5];
100 30 10 -20 5
List[0] List[1] list[2] list[3] list[4]

Read Elements Print Elements


List[0] = 100; for(i=0; i<5; i++)
List[1] = 30; cout<<List[i];
List[2] = 10;
List[3] = -20;
List[4] = 5;

174
‫وائل قصاص‬
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};

175
‫وائل قصاص‬
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];
176
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main() {

int A[5] = {10,20,15,100,30};

{ for (int i=0; i<5; i++)


cout<<A[i]<<'\t';
}
{ for (int i=0; i<5; i++) {
cout<<"\nPlease Enter A["<<i<<"]:";
cin>>A[i]; }

}
{ for (int i=0; i<5; i++)
cout<<A[i]<<'\t';
cout<<endl; 177
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main() {
const int Size = 10;
char r[Size]={ ')', '!', '@', '#', '$', '%', '^', '&', '*', '(' };
for (int i=0; i<Size; i++)
cout<<"Shift + number "<<i<<" Give Symbol "<<r[i]<<endl;
}

178
‫وائل قصاص‬
#include <iostream>
using namespace std;
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 (int 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;
179
cout<<endl;
‫وائل قصاص‬
}
#include <iostream>
using namespace std;
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 (int 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;
} 180
‫وائل قصاص‬
Find the Maximum element
#include <iostream>
using namespace std;
const int Size = 10;
void main() {
int Vector[Size];
cout<<"Enter 10 numbers to find the maximum\n";
for(int i=0; i<Size; i++)
cin>>Vector[i];

for(int i=0; i<Size; i++)


cout<<Vector[i]<<'\t';
cout<<endl;

int Max = Vector[0];


for(int i=1; i<Size; i++)
if (Max<Vector[i])
Max=Vector[i];
181
cout<<"\nMax= "<<Max<<endl;
‫وائل قصاص‬
}
#include <iostream>
using namespace std;
const int Size = 10; We can use it like this:
void main() { int pos;
int Vector[Size];
cout<<"Enter 10 numbers to find the maximum\n";
for(int i=0; i<Size; i++)
cin>>Vector[i];

int Max = Vector[0]; The


int pos=0;
for(int i=1; i<Size; i++)
same but
if (Max<Vector[i])
{Max=Vector[i];
with
pos=i;} position
cout<<"\nMax= "<<Max<<" at pos "<<pos<<endl; 182
} ‫وائل قصاص‬
the Same as the previous example
#include <iostream>
using namespace std;
const int Size = 10;
void main() {
int Vector[Size];
cout<<"Enter 10 numbers to find the maximum\n";
for(int i=0; i<Size; i++)
cin>>Vector[i];

int pos=0;
for(int i=1; i<Size; i++)
if (Vector[pos]<Vector[i]) pos=i;

cout<<"Max= "<<Vector[pos]<<" at pos "<<pos<<endl; 183


‫وائل قصاص‬
}
#include <iostream>
using namespace std;
const int Size = 10;
Search
void main() {
int Vector[Size];
cout<<"enter 10 numbers";
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;
int i;
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 184
cout<<Element<<" is not in the array \n";} ‫وائل قصاص‬
Another version of search example
#include <iostream>
using namespace std;
const int Size = 10;
void main() {
int Vector[Size];
cout<<"enter 10 numbers";
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(int i=0; i<Size; i++)
if(Element == Vector[i]){
cout<<Element<<" is found at position "<<i<<endl;
Found=true; }

if (!Found) // if (found==false) 185


cout<<Element<<" is not in the array \n"; ‫وائل قصاص‬
}
Sort the elements:
#include <iostream>
using namespace std;
const int Size = 5;
void main() {
int Vector[Size];
cout<<"enter 5 numbs :";
for(int i=0; i<Size; i++)
cin>>Vector[i];

for(int i=0; i<Size; i++)


cout<<Vector[i]<<'\t';
cout<<endl;

for(int pass=1; pass<Size; pass++)


for(int i=0; i<Size-1; i++)
if (Vector[i]>Vector[i+1]) {
int Temp = Vector[i];
Vector[i] = Vector[i+1];
Vector[i+1] = Temp;}

for(int i=0; i<Size; i++)


186
cout<<Vector[i]<<'\t';
‫وائل قصاص‬
cout<<endl; }
#include <iostream>
using namespace std;
const int Size = 5;
void main() {
int Vector[Size];
cout<<"enter 5 numbers: ";
for(int i=0; i<Size; i++)
cin>>Vector[i];

for( int i=0; i<Size; i++)


cout<<Vector[i]<<'\t';
cout<<endl;

for(int pass=1; pass<Size; pass++)


{ cout<<"pass "<<pass<<endl;
for(int i=0; i<Size-1; i++)
if (Vector[i]>Vector[i+1]) {
cout<<"Swap"<<Vector[i]<<" "<<Vector[i+1]<<endl;
int Temp = Vector[i];
Vector[i] = Vector[i+1];
Vector[i+1] = Temp;}
for(int j=0; j<Size; j++)
cout<<Vector[j]<<'\t';
cout<<endl;
} 187
}
‫وائل قصاص‬
build a swap function function
void swap(int & x,int & y)
{
int temp;
temp=x;
x=y;
y=temp;
}
188
‫وائل قصاص‬
#include <iostream>
using namespace std;
void swap(int &,int &);
Bubble sort using
const int Size = 5;

void main() {
the swap
int Vector[Size];
cout<<"enter 5 numbers\n"; function
for(int i=0; i<Size; i++)
cin>>Vector[i];

for(int 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(int 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;
} 189
‫وائل قصاص‬
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 &[ ]

190
‫وائل قصاص‬
Write a function that return the sum
#include <iostream>
of an array
using namespace std;
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;
191
} ‫وائل قصاص‬
#include <iostream>
using namespace std;
void Arr_read(int [ ],int);
Functions to Read and
void Arr_print(int[ ],int);
void main(){
print arrays
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;
} 192
‫وائل قصاص‬
Function to calculate the sum of
#include <iostream>
using namespace std;
two arrays
void sum(int [ ],int [ ],int[ ],int);
void Arr_print(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];
}
void Arr_print(int x[ ],int size)
{for(int i=0;i<size;i++)
cout<<x[i]<<" ";
193
cout<<endl;
} ‫وائل قصاص‬
cout statement with setw( )

#include <iostream>
using namespace std;
#include <iomanip>
void main()
{
for(int i=1; i<= 5;i++) // without using setw( )
cout<<i<<" "<<i*i<<" "<<i*i*i<<endl;

cout<<endl;

for(int i=1; i<= 5;i++) // with using setw( )


cout<<setw(4)<<i<<setw(4)<<i*i<<setw(4)<<i*i*i<<endl;
194
} ‫وائل قصاص‬
Strings
#include <iostream>
using namespace std;
void main()
{
char n[10];
char a[10]={'A','h','m','e','d'}; //0,0,0…etc
for(int i=0; a[i]!=0 ; i++) null
cout<<a[i]<<endl;
cout<<endl;
}
195
‫وائل قصاص‬
Q1 in the exam
#include <iostream>
using namespace std;
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;
} 196
} ‫وائل قصاص‬
Two Dimensional array
int Matrix[3][4];
0 1 2 3

0 30
1 100 10
2 10 -20

Assign values to Elements


Matrix[0][1] = 30; Print Elements
Matrix[1][0] = 100; for(i=0; i<3; i++){
Matrix[1][2] = 10; for(j=0; j<4; j++)
Matrix[2][3] = -20; cout<<Matrix[i][j]<<"\t";
Matrix[2][0]=Matrix[1][2]; cout<<endl; }
197
‫وائل قصاص‬
int A[2][3] = { {1 ,2 , 3 },
{10,20,30}};

int Matrix[3][4]= {{0,30 },


{100,0,10},
{0,0,0,-20}};

198
‫وائل قصاص‬
#include <iostream>
using namespace std;
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(int i=0; i<2; i++){
for( int j=0; j<3; j++)
cout<<B[i][j]<<'\t';
cout<<endl; }
cout<<endl;
for(int i=0; i<2; i++){
for( int j=0; j<3; j++)
cout<<C[i][j]<<'\t'; 199
cout<<endl; }} ‫وائل قصاص‬
#include <iostream>
using namespace std;
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 (int i=0; i<Rows; i++){
for(int j=0; j<Columns; j++)
cout<<A[i][j]<<'\t';
cout<<endl; }}

200
‫وائل قصاص‬
#include <iostream> Find The sum of 2-D
using namespace std; arrays using functions`
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;
201
} ‫وائل قصاص‬
Diagonal Summation
#include <iostream>
using namespace std; ‫قطري‬
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 (int i=0; i<Rows; i++)


DSum += A[i][i];

cout<<"Diagonal Sum = "<<DSum<<endl; 202


‫وائل قصاص‬
}
Inverse Diagonal Summation
#include <iostream>
using namespace std;
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 (int 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; 203
} ‫وائل قصاص‬
Lower Triangular Multiplication
#include <iostream>
using namespace std;
const int Rows = 4, Columns = 4;
void main() { 1 1 1 1
int A[Rows][Columns];
2 1 1 1
for (int i=0; i<Rows; i++)
for (int j=0; j<Columns; j++) { 2 2 1 1
cout<<"\nEnter A["<<i<<"]["<<j<<"]:"; 2 2 2 1
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;


} 204
‫وائل قصاص‬
Lower Triangular Multiplication
#include <iostream>
using namespace std;
const int Rows = 4, Columns = 4; 1 1 1 1
void main() { 2 1 1 1
int A[Rows][Columns];
2 2 1 1
for (int i=0; i<Rows; i++)
for (int j=0; j<Columns; j++) { 2 2 2 1
cout<<"\nEnter A["<<i<<"]["<<j<<"]:";
cin>>A[i][j]; }
long LTmul = 1;

for (int 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; 205

} ‫وائل قصاص‬
Write a Program that copies an
#include <iostream>
using namespace std; array to another
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 (int i=0 ;i<R;i++)
for(int j=0;i<C;j++)
B[i][j]=A[i][j];

for (int i=0; i<R; i++){


for(int j=0; j<C; j++)
cout<<B[i][j]<<'\t'; 206
cout<<endl; } ‫وائل قصاص‬
}
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];
}

207
‫وائل قصاص‬
Write a Program that copies an
#include <iostream>
using namespace std; array to another
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 (int i=0; i<R; i++){


for(int j=0; j<C; j++)
cout<<B[i][j]<<'\t';
cout<<endl; }
} 208
‫وائل قصاص‬
#include <iostream>
using namespace std;
void read(int[],int);
int max(int[],int);
float avg (int [],int);
int count(int[],int,int);
void main (){
const int n=10 ;int c;int x[n];
read(x,n);
cout<<"please enter a num u r searching about";cin>>c;
cout<<"the elements found in "<<count(x,n,c)<<" places"<<endl;

cout<<"max="<<max(x,n)<<endl;cout<<"average"<<avg(x,n)<<endl;
}

void read(int a[],int s){


cout<<"enter" <<s<<" elements:"<<endl;
for(int i=0;i<s;i++)
cin>>a[i];}

float avg(int a[],int s){


float sum=0;
for (int i=0;i<s;i++)sum+=a[i];return sum/s;}

int max (int a[] , int n){


int m= a[0];
for (int i=1 ;i<n; i++)
if (a[i] > m)m=a[i];
return m ;}

int count(int a[],int b,int c){


int n=0;
for(int i=0;i<b;i++)
if(c==a[i])
209
n++;
return n;} ‫وائل قصاص‬
Store the following symbols in the
array Symbol. * $ $ $
# * $ $
#include <iostream> # # * $
using namespace std; # # # *
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 (int i=0; i<Rows; i++){
for(int j=0; j<Columns; j++)
cout<<Symbol[i][j]; 210
cout<<endl; } } ‫وائل قصاص‬
Matrix Matrix Summation
#include <iostream>
using namespace std;
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 (int i=0; i<Rows; i++)
for( int j=0; j<Columns; j++)
cin>>B[i][j];
for(int i=0; i<Rows; i++)
for(int j=0; j< Columns; j++)
C[i][j] = A[i][j] + B[i][j];
for(int i=0; i<Rows; i++){
for(int j=0; j<Columns; j++)
cout<<C[i][j]<<'\t' ; 211

cout<<endl; }} ‫وائل قصاص‬


Write a function to add two Arrays
void add(int x[ ][4],int y[ ][4],int z[ ][4],int r)
{

212
‫وائل قصاص‬
#include <iostream>
using namespace std;
void add(int[][4],int [][4],int[][4],int);
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 (int i=0; i<Rows; i++)
for( int j=0; j<Columns; j++)
cin>>B[i][j];
cout<<"the sum of matrix arry is\n";
add(A,B,C,4);
for(int i=0; i<Rows; i++){
for(int j=0; j<Columns; j++)
cout<<C[i][j]<<'\t' ;
cout<<endl;
}}

void add(int A[][4],int B[][4],int C[][4],int r)


{
for(int i=0; i<Rows; i++)
for(int j=0; j< Columns; j++)
C[i][j] = A[i][j] + B[i][j];
} 213
‫وائل قصاص‬
Compute the average for 5 marks for 10 students
#include <iostream>
using namespace std;
void main() {
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(int i=0;i<10;i++)
‫من اول وجديد‬
{ float sum=0;
for(int j=0;j<5;j++)
sum+=marks[i][j];
av[i]=sum/5;}
for(int i=0; i<10; i++){for(int j=0; j<5; j++)
cout<<av[i]<<'\t' ;
cout<<endl; } 214
} ‫وائل قصاص‬
Transpose
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 ……..
215
‫وائل قصاص‬
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];
}

216
‫وائل قصاص‬
Homework

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].

217
‫وائل قصاص‬
Second exam topics
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 array218
to a function). ‫وائل قصاص‬
Strings
#include <iostream>
using namespace std;
void main()
{
char n[10];
char a[10]={'A','h','m','e','d'};
for(int i=0; i<5 ; i++)
cout<<a[i]<<endl;
} 219
‫وائل قصاص‬
#include <iostream>
using namespace std;
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;
} 220
‫وائل قصاص‬
#include <iostream>
using namespace std;
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;
}
} 221
‫وائل قصاص‬
#include <iostream>
using namespace std;
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;
}
} 222
‫وائل قصاص‬
#include <iostream>
using namespace std;
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;
}
223
} ‫وائل قصاص‬
#include <iostream>
using namespace std;
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++) If we put a[i]
cout<<' ';
cout<<a<<endl;
} 224
} ‫وائل قصاص‬
#include <iostream>
using namespace std;
void main()
{
char a[10];
cout<<"Enter a name : ";
cin>>a;
cout<<a<<endl;
int i;
for(i=0; a[i]!=0 ; i++)
{for(int j=0;j<i;j++)
cout<<' ';
cout<<a<<endl;
}
cout<<i<<endl;
} 225
‫وائل قصاص‬
Final exam question
• Write a function that returns the length of a
string or array of characters.

• The function prototype is


• int length(char[ ]);

226
‫وائل قصاص‬
int length(char name[ ])
{
for(int i=0;name[i]!=0;i++)
;
return i;
}

227
‫وائل قصاص‬
Ex: Write a program
#include <iostream>
that prints the name
using namespace std;
void main()
inversed( from the last
{ char to the first
char name[10]; character
cout<<"Enter ur name : ";
cin>>name;
int i;
for(i=0; name[i]!=0 ; i++);
for(int j=i-1;j>=0;j--)
cout<<name[j];
cout<<endl;
}
228
‫وائل قصاص‬
Chapter 5 - Pointers and
Strings
Outline
5.1 Introduction
5.2 Pointer Variable Declarations and Initialization
5.3 Pointer Operators
5.4 Calling Functions by Reference

5.7 Pointer Expressions and Pointer Arithmetic


5.8 The Relationship Between Pointers and Arrays
5.9 Arrays of Pointers

5.12 Introduction to Character and String Processing


5.12.1 Fundamentals of Characters and Strings
5.12.2 String Manipulation Functions of the
String-handling Library

229
‫وائل قصاص‬
5.1 Introduction
• Pointers
– Powerful, but difficult to master
– Simulate call-by-reference
– Close relationship with arrays and strings

230
‫وائل قصاص‬
5.2 Pointer Variable
Declarations and Initialization
• Pointer variables
– Contain memory addresses as their values
– Normal variables contain a specific value (direct reference)
– Pointers contain the address of a variable that has a specific
value (indirect reference)
• Indirection countPtr count
count

– Referencing a pointer value 7


7

• Pointer declarations
– * indicates variable is a pointer
int *myPtr;
declares a pointer to an int, a pointer of type int *
– Multiple pointers require multiple asterisks
int *myPtr1, *myPtr2;

231
‫وائل قصاص‬
5.2 Pointer Variable
Declarations and Initialization
• Can declare pointers to any data type
• Pointers initialization
– Initialized to 0, NULL, or an address
• 0 or NULL points to nothing

232
‫وائل قصاص‬
5.3 Pointer Operators
• & (address operator)
– Returns the address of its operand
– Example
int y = 5;
int *yPtr;
yPtr = &y; // yPtr gets address of y
– yPtr "points to" y
y yptr y
5 500000 600000 600000 5
yPtr

address of y
is value of 233
yptr ‫وائل قصاص‬
5.3 Pointer Operators
• * (indirection/dereferencing operator)
– Returns the value of what its operand points to
– *yPtr returns y (because yPtr points to y).
– * can be used to assign a value to a location in
memory
*yptr = 7; // changes y to 7
– Dereferenced pointer (operand of *) must be an
lvalue (no constants)
• * and & are inverses
– Cancel each other out
*&myVar == myVar
and
234
&*yPtr == yPtr
‫وائل قصاص‬
Pointer
Pointer is a memory location, which contains a memory
address of another memory location, which belong to a
variable. We say that the pointer points to the variable.
#include <iostream>
using namespace std;
void main() { ----------
12FF7C 10 a
int a = 10;
----------
int *ptr = &a;
cout<<ptr<<endl;
----------
cout<<&a<<endl; 12FB8D 12FF7C ptr
cout<<*ptr<<endl; ----------
cout<<a<<endl;
}

235
‫وائل قصاص‬
Pointers
#include <iostream>
using namespace std;
void main()
{
int x=5;
int* y; // pointer to an integer
y=&x;
cout<<x<<endl<<&x<<endl;
cout<<y<<endl<<*y<<endl;
236
} ‫وائل قصاص‬
Output
The address of a is 006AFDF4
The value of aPtr is 006AFDF4
The value of a is 7
The value of *aPtr is 7
Showing that * and & are inverses of each other.
&*aPtr = 006AFDF4
*&aPtr = 006AFDF4

237
‫وائل قصاص‬
Example 1
#include <iostream>
using namespace std;
void main( ) {
int a = 10, b = 20;
int *ptr_a, *ptr_b;
ptr_a = &a;
ptr_b = &b;
cout<<"a="<<*ptr_a<<'\t'<<"b="<<*ptr_b<<endl;
a += 10;
b += 20;
cout<<"a="<<*ptr_a<<'\t'<<"b="<<*ptr_b<<endl;
++*ptr_a;
++*ptr_b;
cout<<"a="<<a<<'\t'<<"b="<<b<<endl;
ptr_a = ptr_b;
cout<<"b="<<*ptr_a<<endl; 238
‫وائل قصاص‬
}
Example 2 (String)
St_name
-----
A
-----
#include <iostream> H
using namespace std; -----
void main() { m
char *St_name; -----
a
St_name = "Ahmad Ali"; -----
cout<<endl<<St_name<<endl; d
} -----

-----
A
-----
L
----- 239
i ‫وائل قصاص‬
Example 3 (String)
-----
A St_name[0]
-----
#include <iostream> H St_name[1]
using namespace std; -----
void main() { m St_name[2]
char St_name[20]; -----
a St_name[3]
cout<<"Please enter your name: ";
-----
cin.getline(St_name,20,'\n'); d St_name[4]
cout<<endl<<St_name<<endl; -----
} St_name[5]
-----
A St_name[6]
-----
L St_name[7]
-----
i St_name[8]
240
‫وائل قصاص‬
Example 4 (array name is a static
pointer) -----
B1 F1 Vector
#include <iostream>
-----
using namespace std; B2 F1 ptr
void main() { -----
float Vector[5] = {3.2, 2.2, 6.2, 4.2, 9.2};
float *ptr; -----
ptr = Vector; // ptr=&Vector[0];
-----
for (int i=0; i<5; i++) F1 1.2 Vactor[0]
{ -----
cout<<"\n"<<*ptr; F2 2.2 Vactor[1]
++ptr; } -----
F3 3.2 Vactor[2]
}
-----
F4 4.2 Vactor[3]
----- 241
F5 5.2 Vactor[4
‫وائل قصاص‬
]
5.4 Calling Functions by
Reference
• Call by reference with pointer arguments
– Pass address of argument using & operator
– Allows you to change actual location in memory
– Arrays are not passed with & because the array name is
already a pointer
– * operator used as alias/nickname for variable inside of
function
void doubleNum( int *number )
{
*number = 2 * ( *number );
}
– *number used as nickname for the variable passed in
– When the function is called, must be passed an address
doubleNum( &myNum );

242
‫وائل قصاص‬
1 // Fig. 5.7: fig05_07.cpp
2 // Cube a variable using call-by-reference
3 // with a pointer argument
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 void cubeByReference( int * ); // prototype
10
11int main()
12{
13 int number = 5;
14
15 cout << "The original value of number is " << number;
16 cubeByReference( &number );
17 cout << "\nThe new value of number is " << number << endl;
18 return 0;
19}
20
21void cubeByReference( int *nPtr )
22{ 243
23 *nPtr = *nPtr * *nPtr * *nPtr; // cube number in main
‫وائل قصاص‬
24}
The original value of number is 5
The new value of number is 125

244
‫وائل قصاص‬
5.7 Pointer Expressions and
Pointer Arithmetic
• Pointer arithmetic
– Increment/decrement pointer (++ or --)
– Add/subtract an integer to/from a pointer( + or += , - or -=)
– Pointers may be subtracted from each other
– Pointer arithmetic is meaningless unless performed on an array
• 5 element int array on a machine using 4 byte ints
– vPtr points to first element v[ 0 ], which is at location 3000
• vPtr = 3000 location

– vPtr += 2; sets vPtr to 3008 3000 3004 3008 3012 3016

• vPtr points to v[ 2 ] v[0] v[1] v[2] v[3] v[4]

pointer variable vPtr

245
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main( )
{
int v[5]={4,2,7,3,10};
int *vp;
vp=&v[0];
cout<<*vp<<endl;
cout<<*(vp+2)<<endl;
vp+=2;
cout<<*vp;
246
} ‫وائل قصاص‬
#include <iostream>
using namespace std;
void main( )
{
int v[5]={5,2,7,3,10};
int *vp;
vp=&v[0];
for(int i=0;i<5;i++)
cout<<*(vp++)<<endl;

} 247
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main( )
{
int v[5]={5,2,7,3,10};
int *vp;
vp=v; // v is a pointer to v[0]
for(int i=0;i<5;i++)
cout<<*(vp++)<<endl;

}
248
‫وائل قصاص‬
5.7 Pointer Expressions and
Pointer Arithmetic
• Subtracting pointers
– Returns the number of elements between two
addresses
vPtr2 = &v[ 2 ]; \\3008
vPtr = &v[ 0 ]; \\3000
vPtr2 - vPtr == 2

• Pointer comparison
– Test which pointer points to the higher
numbered array element
– Test if a pointer points to 0 (NULL)
249
if ( vPtr == ‘0’ )
‫وائل قصاص‬
statement
5.7 Pointer Expressions and
Pointer Arithmetic
• Pointers assignment
– If not the same type, a cast operator must be
used
– Exception: pointer to void (type void *)
• Generic pointer, represents any type
• No casting needed to convert a pointer to void
pointer
• void pointers cannot be dereferenced

250
‫وائل قصاص‬
5.8 The Relationship Between
Pointers and Arrays
• Arrays and pointers closely related
– Array name like constant pointer
– Pointers can do array subscripting operations
– Having declared an array b[ 5 ] and a
pointer bPtr
• bPtr is equal to b
bptr == b
• bptr is equal to the address of the first element of
b
bptr == &b[ 0 ]
251
‫وائل قصاص‬
5.8 The Relationship Between
Pointers and Arrays
• Accessing array elements with pointers
– Element b[ n ] can be accessed by *( bPtr + n )
• Called pointer/offset notation
– Array itself can use pointer arithmetic.
• b[ 3 ] same as *(b + 3)
– Pointers can be subscripted (pointer/subscript notation)
• bPtr[ 3 ] same as b[ 3 ]

252
‫وائل قصاص‬
Arrays and Pointers
#include <iostream>
using namespace std;
void main( )
{
int a[10]={1,5, 7, 4, 3, 2, 8, 9, 11, 12};
int *p;
p = a;
for (int i=0; i<10; i++)
cout<<a[i]<<endl; // ‫الطريقة التقليدية لطباعة المصفوفة‬
cout<<endl;
for (int i=0; i<10; i++)
{ cout<<*p<<endl; // ‫طريقة لطباعة المصفوفة عن باستخدام العناوين‬
p++; }
} 253
‫وائل قصاص‬
#include <iostream>
using namespace std;
void main( )
{
int a[10]={1,5, 7, 4, 3, 2, 8, 9, 11, 12};
int *p;
p = a;
for (int i=0; i<10; i++)
cout<<a[i]<<endl;
cout<<endl;
for (int i=0; i<10; i++)
cout<<*(p+i)<<endl; // ‫نفس المثال السابق ولكن بدون تعديل قيمة المؤشر‬
}
254
‫وائل قصاص‬
Example 2: Write a
program to compare two
#include <iostream> arrays if they are
using namespace std; equivalent or not.
void main( )
{int a[5]={1, 3, 5, 7, 9};
int b[5]={1, 3, 5, 8, 9};
bool flag=true;
for (int i=0; i<5; i++)
{
if (*(a+i)!=*(b+i)) // ‫ تكافئ‬if(a[i] != b[i])
{ flag = false; break; }
}
if (flag)
cout<<"Two arrays are equivalent ";
else
cout<<"Two arrays are not equivalent";
255
} ‫وائل قصاص‬
Difference between arrays of char
and arrays of int
#include <iostream>
using namespace std;
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
} 256
‫وائل قصاص‬
#include <iostream>
using namespace std;
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; 257
} ‫وائل قصاص‬
5.9 Arrays of Pointers
• Arrays can contain pointers
– Commonly used to store an array of strings
char *suit[ 4 ] = {"Hearts", "Diamonds",
"Clubs", "Spades" };
– Each element of suit is a pointer to a char * (a string)
– The strings are not in the array, only pointers to the strings are in
the array
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

suit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

– suit array has a fixed size, but strings can be of any size
258
‫وائل قصاص‬
5.12.1 Fundamentals of
Characters and Strings
• Character constant ‫االساسيات‬
– Integer value of a character
– Single quotes
– 'z' is the integer value of z, which is 122
• String
– Series of characters treated as one unit
– Can include letters, digits, special characters +, -, * ...
– String literal (string constants)
• Enclosed in double quotes, for example:
"I like C++"
– Array of characters, ends with null character '\0'
– Strings are constant pointers (like arrays)
• Value of string is the address of its first character 259
‫وائل قصاص‬
5.12.1 Fundamentals of
Characters and Strings
• String assignment
– Character array:
char color[] = "blue";
• Creates 5 element char array, color, (last
element is '\0')
– variable of type char *
char *colorPtr = "blue";
• Creates a pointer to string "blue", colorPtr,
and stores it somewhere in memory

260
‫وائل قصاص‬
5.12.1 Fundamentals of
Characters and Strings
• Reading strings
– Assign input to character array word[ 20 ]
cin >> word
• Reads characters until whitespace or EOF
• String could exceed array size
cin >> setw( 20 ) >> word;
• Reads 19 characters (space reserved for '\0')
• cin.getline ‫تجاوز‬
– Reads a line of text
– Using cin.getline
cin.getline( array, size, delimiter character);

261
‫وائل قصاص‬
5.12.1 Fundamentals of
Characters and Strings
• cin.getline
– Copies input into specified array until either
• One less than the size is reached
• The delimiter character is input
– Example
char sentence[ 80 ];
cin.getline( sentence, 80, '\n' );

262
‫وائل قصاص‬
5.12.2 String Manipulation Functions
of the String-handling Library
• String handling library <cstring> provides functions to
‫التالعب‬
– Manipulate strings
– Compare strings
– Search strings
– Tokenize strings (separate them into logical pieces)
• ASCII character code
– Strings are compared using their character codes
– Easy to make comparisons (greater than, less than, equal to)
• Tokenizing ‫منفصل‬
– Breaking strings into tokens, separated by user-specified
characters
– Tokens are usually logical units, such as words (separated by
spaces)
– "This is my string" has 4 word tokens (separated by 263
spaces) ‫وائل قصاص‬
5.12.2 String Manipulation Functions
of the String-handling Library
char *strcpy( char *s1, const Copies the string s2 into the character
char *s2 ); array s1. The value of s1 is returned.
char *strncpy( char *s1, const Copies at most n characters of the string s2 into the
char *s2, size_t n ); character array s1. The value of s1 is returned.

char *strcat( char *s1, const Appends the string s2 to the string s1. The first
char *s2 ); character of s2 overwrites the terminating null
character of s1. The value of s1 is returned.
‫يضيف‬
char *strncat( char *s1, const Appends at most n characters of string s2 to string s1.
char *s2, size_t n ); The first character of s2 overwrites the terminating null
character of s1. The value of s1 is returned.

int strcmp( const char *s1, Compares the string s1 with the string s2. The function
const char *s2 ); returns a value of zero, less than zero or greater than
zero if s1 is equal to, less than or greater than s2,
264
respectively.
‫وائل قصاص‬
‫على التوالي‬
5.12.2 String Manipulation Functions
of the String-handling Library (III)
int strncmp( const char *s1, const Compares up to n characters of the
char *s2, size_t n ); string s1 with the string s2. The
function returns zero, less than zero or
greater than zero if s1 is equal to, less
than or greater than s2, respectively.
char *strtok( char *s1, const char A sequence of calls to strtok breaks
*s2 ); string s1 into "tokens"—logical pieces
such as words in a line of text—
delimited by characters contained in
string s2. The first call contains s1 as
the first argument, and subsequent calls
to continue tokenizing the same string
contain NULL as the first argument. A
pointer to the current token is returned
by each call. If there are no more
tokens when the function is called,
NULL is returned.
size_t strlen( const char *s ); Determines the length of string s. The
number of characters preceding the
terminating null character is returned. 265
‫وائل قصاص‬
String Functions
To use string functions we must include the
<cstring> library or <string.h> library in
the top of the program
• #include <cstring>
• String functions that we will cover are:
– strcpy
– strncpy
– strcat
– Strncat
– Strcmp
– Strncmp 266

– strlen ‫وائل قصاص‬


Example on strcpy, strncpy
#include <iostream>
using namespace std;
#include<string.h>
void main( )
{
char x[ ]="Happy Birthday to You";
char y[25];
char z[15];
strcpy(y, x);
cout<<x<<" "<<y<<endl;
strncpy(z, x,14);
z[14]='\0'; // strncpy doesn’t add \0 at the end
cout<<z<<endl;
} 267
‫وائل قصاص‬
‫‪Output‬‬

‫‪268‬‬
‫وائل قصاص‬
Example on strcat, strncat
#include <iostream>
using namespace std;
#include<string.h>
void main( )
{
char s1[20]="Happy";
char s2[ ]="New Year";
char s3[40]=""; // this puts \0 in the whole array
cout<<s1<<" "<<s2<<endl;
strcat(s1, s2);
cout<<s1<<" "<<s2<<endl;
strncat(s3, s1, 5);
cout<<s1<<" "<<s3<<endl;
strcat(s3, s1);
cout<<s1<<" "<<s3<<endl;
269
} ‫وائل قصاص‬
‫‪Output‬‬

‫‪270‬‬
‫وائل قصاص‬
#include <iostream>
using namespace std;
#include<string.h>
void main( )
{
char s1[ ]="Happy New Year";
char s2[ ]="Happy New Year";
char s3[ ]="Happy Holidays";
cout<<s1<<"\n"<<s2<<"\n"<<s3<<"\n";
cout<<strcmp(s1, s2)<<"\n"
<<strcmp(s1, s3)<<"\n"
‫دكتور هيك‬
<<strcmp(s3, s1)<<endl;
cout<<strncmp(s1,s3,6)<<"\n"
‫الناتج بيطلع‬
<<strncmp(s1, s3, 7)<<"\n"
<<strncmp(s3, s1,7)<<endl; 271
} ‫وائل قصاص‬
Output
Happy New Year
Happy New Year
Happy Holidays
0
1
-1
0
1
-1
Press any key to continue
272
‫وائل قصاص‬

You might also like