c++ programming language - كلية...

42
C++ LECTURES ABDULMTTALIB. A. H. ALDOURI [ 1 ] C++ PROGRAMMING LANGUAGE INTRODUCTION A program is a sequence of instructions for a computer to execute. Every program is written in some programming language. The C++ (pronounced “see-plus-plus”) language is one of the newest and most powerful programming languages available. It allows the programmer to write efficient, structured, object-oriented programs. Prior to 1983, Bjarne Stroustrup added features to C language and formed what is called "C with Classes". During the 1990s, C++ became one of the most popular commercial programming languages. STRUCTURE OF A C++ PROGRAM // This is our first program (comment) # include <iostream.h> (header file) void main() (main function) { ←the starting brace Statements; { }←the end brace 1. Comments : make programming simple and help us to understand the program. They are not execution statements. In C++, comments can be given in two ways: a) Single line comments: They start with // (double slash) symbol. For example: int a ; // declares the variable a of integer type C b) Multi line comments: Start with a /* symbol and terminate with a */ symbol. 2. Header files: The second statement directs the compiler to include the header file <iostream.h> (input/output stream) which includes two objects cin and cout for performing input and output. The program may contain more than one header file like <math.h>, <string.h> , <stdio.h> … etc. 3. Void main ( ) : indicates the beginning of the program. Every program in C++ must have only one main ( ) function. 4. The body of the program: The code lines after void main ( ) and enclosed between the curly braces „{ }‟ form the body of the program. The body of the program

Upload: hoangdung

Post on 09-Jun-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[1]

C++ PROGRAMMING LANGUAGE

INTRODUCTION

A program is a sequence of instructions for a computer to execute. Every program is written

in some programming language. The C++ (pronounced “see-plus-plus”) language is one of

the newest and most powerful programming languages available. It allows the programmer to

write efficient, structured, object-oriented programs.

Prior to 1983, Bjarne Stroustrup added features to C language and formed what is

called "C with Classes". During the 1990s, C++ became one of the most popular commercial

programming languages.

STRUCTURE OF A C++ PROGRAM

// This is our first program (comment)

# include <iostream.h> (header file)

void main() (main function)

←the starting brace

Statements;

←the end brace 1. Comments : make programming simple and help us to understand the program. They

are not execution statements. In C++, comments can be given in two ways:

a) Single line comments: They start with // (double slash) symbol. For example:

int a ; // declares the variable a of integer type C

b) Multi line comments: Start with a /* symbol and terminate with a */ symbol.

2. Header files: The second statement directs the compiler to include the header file

<iostream.h> (input/output stream) which includes two objects cin and cout for

performing input and output. The program may contain more than one header file like

<math.h>, <string.h> , <stdio.h> … etc.

3. Void main ( ) : indicates the beginning of the program. Every program in C++

must have only one main ( ) function.

4. The body of the program: The code lines after void main ( ) and enclosed between the curly braces „ ‟ form the body of the program.

The body

of the

program

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[2]

BASIC DATA TYPES IN C++

The basic data types available in C++ language are given in the following table:

Data

Type

Range Size Usage

int -32768 to 32767 2 bytes (16 bits) For storing numbers without

decimal.

long -2147483648 to 2147483647 4 bytes (32 bits) For storing integers. Has

higher range than „int ‟.

char 0 to 255 1 byte (8 bits) For storing characters.

float

-3.4 * 1038 to 3.4 * 1038

4 bytes (32 bits) For storing floating point

numbers. It has seven digits

of precision.

double

±1.7*10 ±308 (15 digits) 8 bytes (64 bits) It is used to store double

precision floating point

numbers.

DECLARATION OF VARIABLES

A variable may be declared as below:

type variable_name ;

type variable_name = initial value;

type variable_name ( value) ;

type is the data type such as int , float or double, char, etc.

C++ allows long descriptive variable or identifier names. The rules for forming a variable

name also apply to function names. The rules are:

1. The first character must be a letter, either lowercase or uppercase;

2. Case is significant, uppercase and lowercase letters are different;

3. Variable names are composed of lowercase letters, numbers, and the underscore

character

4. Defined constants are traditionally made up of all uppercase characters

5. The number of characters allowed in a variable name is compiler dependent, but the

variable must be unique in the first eight characters in order to be safe across

compilers;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[3]

6. Make variable names descriptive;

7. Do not make a variable name the same as a reserved word.

The Reserved Words for C++ Language are:

volatile double int struct break else long switch

register typedef for extern union char void const

unsigned return do sizeof float auto case static

continue default if signed short goto enum while

Examples:

int my_Age; ( to declare an integer variable.)

long Fact=5376894; (to declare a long integer variable with initial value.)

float AVERAGE2; (to declare a real (floating point) variable.)

double x (2.12356724); (to declare a double precision floating point variable

with initial value.)

char ch; (to declare a character variable.)

char CH = „A‟; (to declare a character variable with initial value.)

int x1, x2, x3=0; (to declare more than one integers.)

CONSTANTS

C++ allow for the programmer to define constants that represent decimal, hexadecimal octal,

string and character constants. The #define directive can be used to define constants and it is

placed after headers files.

#define PI 3.14156

#define MYNAME "JOHN DOE"

#define LIMIT 10

#define ESC 0x1B

Also we can use const to define constants as follows :

const int diameter = 10 ;

const float PI = 3.14159;

const char ch= 'a';

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[4]

INPUT AND OUTPUT STATEMENTS

The input statement has the following syntax:

cin>> variable_name;

cin>> var1>> var2>> var3>>……… ;

Examples:

cin>>age;

cin>>x1>>x2>>x3;

The output statement has the following syntax:

cout<<variable_name;

cout<<var1<<" "<<var2<<" " <<var3<<………;

cout<<var1<<endl<<var2<<endl<<var3; [endl means new line]

Examples:

cout<<age;

cout<<x1<<" "<<x2<<" "<<x3;

cout<<x1<<endl<<x2<<endl<<x3;

cout<<"x1="<<x1;

cout<<"Hello my friends";

the following program prints the value of a variable in decimal, octal, and hexadecimal.

#include <iostream.h>

void main()

int i = 500;

cout << dec << i << endl;

cout << hex << i << endl;

cout << oct << i << endl;

This produces the following output: 500

1F4

764

setw( ) : The 'setw( )' manipulator is used to set the field width for the next insertion operator. The header file <iomanip.h> must be included in the program as follows:

#include <iostream.h>

#include <iomanip.h>

main()

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[5]

int i = 100;

cout << setw(6) << dec << i;

cout << setw(6) << hex << i;

cout << setw(6) << oct << i;

return 0;

This produces the following output: 100 64 144

OPERATORS IN C++ LANGUAGE

1. Assignment Operator:

The basic assignment operator is ( = ) which is often called equal to. Consider the

following assignments.

int x = 5,y = 10, z, w; // Declaration and initialization

z = x; // assignment

w = x + y; // assignment

x=(b=3, b+2);//first assign 3 to variable b and then calculate x

y =(x = 5)+2 ; // assign the value 5 to x, then assign x+2 to y

a = b = c = 5; // assign the value 5 to a, b, and c

2. Arithmetic Operators:

Arithmetic operators are used to perform the basic arithmetic operations. They are

explained in the following table:

Operator Usage Examples

+ Used for addition Sum = a + b

- Used for subtraction Difference = a – b

* Used for multiplication Product = a * b

/ Used for division Quotient = a / b

%

This operator is called the remainder or the

modulus operator. It is used to find the

remainder after the division. This operator

cannot be used with floating type variables.

Remainder = a % b

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[6]

3. Compound Assignment Operators

C++ allows combining the arithmetic operators with assignment operator as in the

following table.

Operator C++ expression Equivalent expression Explanation and use

+= B + = 5; B = B +5; int B= 4;

B+=5 ; // B=9

–= C – = 6; C = C – 6; int C = 10;

C–= 6 ; // C=4

*= D * = 2; D = D*2; int D = 10;

D*=2; // D=20

/= E / = 3; E = E/3; int E = 21;

E/=3; // E = 7

%= F % = 4; F = F % 4 ; int F=10;

F%=4 ; // F=2

4. Relational Operators:

The relational operators are explained in the following table:

Operator Usage Example Explanation

< Less than A<B A is less than B.

> Greater than A>B A is greater than B.

<= Less than or equal to A<=B A is less than or equal to B.

>= Greater than or equal to A>=B A is greater than or equal to B.

== Equality A == B A equal to B.

!= Not equal to A != B A is not equal to B.

5. Logical Operators

The logical operators are used to combine multiple conditions (logical statements). The following table describes the logical operators:

Operator Usage Example

&& (logical AND) The compound condition is true,

if both conditions are true.

((a>b) && (a>c))

|| (logical OR) The compound statement is true,

if any or both conditions are true.

(( a>b) || (a>c))

! (logical NOT) It negates the condition. !(a>b)

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[7]

Examples

y= ((2 == 4) && (7>5));

z= !(1 > 4);

w= ((2 > 0) || (5<0));

the results are:

y=0 , z=1 , w=1

The following program illustrates the application of logical operators.

#include <iostream.h>

main()

int p=1, q=0, r=1, s,t,x, y, z;

s = p||q;

t = !q;

x = p&&q;

y = (p || q && r||s);

z = (!p || !q && !r || s);

cout << "s = "<<s << ", t = " <<t <<", x = "<<x << endl;

cout << “y = ” <<y <<“, z = ”<<z<< endl; return 0;

The expected output are given below :

s = 1, t = 1, x = 0

y = 1, z = 1

6. Bitwise Operators

Bitwise operation means convert the number into binary and perform the operation on each

bit individually. The bitwise operators are listed in the table below:

Operator Description Example of code

& Bitwise AND A & B;

| Bitwise OR A | B;

^ Bitwise Exclusive OR A ^ B;

~ complement ~A;

<< Shift Left A<<2; //shift left by 2 places

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[8]

>> Shift Right A>>2;//shift right by 2 places

&= Bitwise AND assign A &= B;// A=A&B

|= Bitwise OR assign A |= B; // A=A|B

^= Bitwise XOR assign A ^= B; // A=A^B

<<= Bitwise shift left assign A <<= 2;//Shift left by 2

places and assign to A

>>=

Bitwise shift right assign

A >>= 1;//Shift right by 1

place and assign to A

Example

#include<iostream.h>

void main()

int A=42, B=12, C=24, D;

D = A^B;

C <<= 1;

A <<=2;

B >>=2 ;

cout<<"A="<<A<<endl;

cout<<"B="<<B<<endl;

cout<<"C="<<C<<endl;

cout<<"D="<<D;

The expected outputs are given below :

A = 168

B = 3

C = 48

D = 38

#include<iostream.h>

void main()

int A =20, D , E, F;

int B = 18, C = 30;

D = C^B;

E = A &B ;

F = C|A ;

cout <<"E="<<E<<endl;

cout <<"F="<<F<<endl;

cout <<"D="<<D<<endl;

The expected outputs are given below :

E = 16

F = 30

D = 12

7. Increment and Decrement Operators

They are used for increasing and decreasing a variable by unity. These operators may be

placed before or after the variable name as shown in the following table.

Operator Pre or post Description

++k Pre-increment First increase the value of k by one then evaluate the

current statement by taking incremented value.

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[9]

k++ Post-increment First use the current value of k to evaluate the current

statements then increase k by unity.

– –k Pre-decrement First decrease the value of k by unity then evaluate the

statement.

k– – Post-decrement First use the current value of k to evaluate the current

statements then decrease k by unity.

Pre-increment Post-increment

int a= 10, b= 11, c;

c=a+ ++b; //c=10+12=22, b=12

int a= 10, b= 11, c;

c=a+ b++; //c=10+11=21 , b=12

The following program illustrates the increment and decrement operators.

#include <iostream.h>

void main()

int a = 6, p = 4,r=3,n =5,A,B,C,K ;

A = 6 * ++n ;

cout << "A = "<<A <<"\t n = " <<n <<endl;

K = 5 * a–– ; cout<<"K = "<<K<<"\t a = " <<a << endl;

B =r++ * r++ ;

cout<< “B = "<<B<<"\t r = "<< r << endl; C = p–– * p––; cout<<"C = "<< C<<"\t p = "<< p << endl;

The expected output is given below:

A = 36 n = 6

K = 30 a = 5

B = 9 r = 5

C = 16 p = 2

H.W.

Evaluate the following expressions for m = 6, n = 2 , a = 0, b = 0, c = 0, d = 0, and e = 0

(i) a+=4+ ++m*n ;

(ii) b*=3+ ––m*m ; (iii) c+=2 +m * ++m ;

(iv) d*=2* + m*m–– ; (v) e––=2* ++m/m–– ;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[11]

PRECEDENCE OF OPERATORS

Precedence is an important aspect of operators. A list of operators and their precedence

are given in the following table:

Operator Description

( )

Highest precedence given to parentheses. In case of several pairs of

parentheses without nesting, they are evaluated from left to right.

++ and – – Increment and decrement operators have the precedence over the other

arithmetic operators. In case of several such operators, they are

evaluated from left to right.

* , / , % Multiplication, division and remainder operators are evaluated after

increment and decrement operators. In case of several such operators,

they are evaluated from left to right.

+ , – Plus and minus are evaluated last. If there are several such operators

then they are evaluated from left to right.

Example

Evaluate the value stored in the variable „result‟ in the following expressions using

precedence of operators if a=5, b=20, c=10, d=4, e=7;

(a) result = a * b + c – d % e; (b) result = a * ++b + c – d % e; (c) result = ++a * b + (c – d) % ––e; (d) result = a * ( b + c) – ++d % e;

Solution

(a) result = 5 * 20 + 10 – 4 % 7 =110

(b) result = 5 * ++20 + – – 10 – 4 % 7 = 114 , b = 21, c = 9

(c) result = 5++ *20 + (10 – 4) % – –7 = 101 , a=6 , e=6

(d) result = ++5 * ( 20 + 10) – ++4 % 7 = 180 , a=6 , d=5

H.W.

Evaluate the following expressions if y=2:

a) Z = 5 *y + 3*y*( 10*y + 5/2);

b) Z = 7* y % 2 + 2*(3 +( y % 3 + 2));

c) Z = 7 % y *(y + 6*7) –5; d) Z = 2* ++y + 3 * ––y;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[11]

The sizeof( ) operator

This operator accepts one parameter, which can be either a type or a variable itself and

returns the size in bytes of that type or object :

int x;

int y=sizeof(x);

a = sizeof (char);

Most of the mathematical functions are declared in the <math.h> header file, as shown in

the table below.

Function Description Example

sin(x) sine of x (x in radians) sin(2) returns 0.909297

cos(x) cosine of x (x in radians) cos (2) returns -0.416147

tan(x) tangent of x (x in radians) tan(2) returns -2.18504

asin(x) inverse sine of x (x in radians) asin(0.2) returns 0.201358

acos(x) inverse cosine of x (x in radians) acos(0.2) returns 1.36944

atan(x) inverse tangent of x (x in radians) atan(0.2) returns 0.197396

exp(x) exponential of x (base e) exp(2) returns 7.38906

fabs(x) absolute value of x fabs(-2) returns 2.0

log(x) natural logarithm of x (base e)[Ln(x)] log(2) returns 0.693147

log10(x) common logarithm of x (base 10) Logl0(2) returns 0.30103

sqrt(x) square root of x sqrt(2) returns 1.41421

pow(x,p) x to the power p pow(2,3) returns 8.0

ceil(x) ceiling of x (rounds up) ceil(3.141593) returns 4.0

floor(x) floor of x (rounds down) floor(3.141593) returns 3.0

Ex: Write a program to evaluate the area and circumference of a circle.

#include<iostream.h>

#define PI 3.14159

void main( )

float radius, area, circum;

cout<<"enter the radius of the circle"<<endl;

cin>>radius;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[12]

area=PI*radius*radius;

circum=2*PI*radius;

cout<<"area="<<area<<endl;

cout<<"circumference="<<circum;

Ex: 6Ω, 3Ω resisters are connected in series across a 36v source, write a program to find

the total current and the voltage of each resister.

#include<iostream.h>

void main( )

float R1, R2, V,I,V1,V2;

cin>> R1>> R2>> V;

I=V/(R1+R2);

V1=I*R1;

V2=I*R2;

cout<<"I="<<I<<endl;

cout<<"V1="<<V1<<" V2="<<V2;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[13]

CONDITIONAL SELECTION STATEMENTS

C++ programming language provides three conditional selection statements. They are: 1. if statement.

2. if .... else statement.

3. switch statement.

1. if STATEMENT :

The if statement allows to execute an

instruction or block of instructions only if the

specified condition is true. It has the

following syntax:

if ( conditional expression ) statement ;

If there are more than one statement to be

executed , they are enclosed in curly braces :

if ( conditional expression )

Block_of_statements ;

if (x %2==0)

cout << "x is even";

if (x %2==0)

cout << "x is even";

cout << x;

2. if .... else STATEMENT.

This statement is used when we have two choices, it is written as follows:

if (condition)

Block1_of_statements ;

else

Block2_of_statements ;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[14]

if (x %2== 0)

cout << "x is even";

else

cout << "x is odd";

The following program uses the if....else to test for divisibility ( るقابليるالقسم ) of an integer.

#include<iostream.h>

main( )

int n, m ;

cout << "Enter two integer numbers: " ;

cin>>n >>m ;

if (n % m==0)

cout<<n<< " is divisible by"<<m ;

else

cout<<n<<" is not divisible by "<< m ;

return (0) ;

A chain of if .. else expressions is used if there are more than two choices. The

following program selects the name of the day of the week out of 7 choices.

#include<iostream.h>

void main( )

int day ;

cout<<"Enter the day number(1-7)"<<endl;

cin>> day ;

if (day == 1)

cout<<"It is Sunday "<<endl;

else if (day == 2)

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[15]

cout<<"It is Monday "<<endl;

else if (day == 3)

cout<<"It is Tuesday "<<endl;

else if (day == 4)

cout<<"It is Wednesday "<<endl;

else if (day == 5)

cout<<"It is Thursday "<<endl;

else if (day == 6)

cout<<"It is Friday "<<endl;

else if(day==7)

cout<<"It is Saturday "<<endl;

else

cout<<"The number is not in range.";

Ex: Write a program to find the roots of a quadratic equation Ax2 + Bx + C = 0

#include<iostream.h>

#include<stdio.h>

void main( )

float A, B, C, D,x1,x2;

cout<< "Enter the coefficients : " ;

cin>>A>>B>>C ;

D=B*B-4*A*C;

if(D<0)

cout<<"complex roots";

else if (D>0)

x1=(-B/(2*A))+sqrt(D)/(2*A);

x2=(-B/(2*A))-sqrt(D)/(2*A);

cout<<"x1="<<x1;

cout<<"x2="<<x2;

else

x1=-B/(2*A);

x2=x1;

cout<<"x1="<<x1;

cout<<"x2="<<x2;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[16]

Note: Relational and logical operators are often used with if and if….else statements.

Ex: Write a program to find the maximum of three integers

#include<iostream.h>

void main( )

int A, B, C, max;

cout<< "Enter the three numbers : " ;

cin>>A>>B>>C ;

if (A>B && A>C)

max=A;

else if (B>C)

max=B;

else

max=C;

cout<<"the maximum integer is "<<max;

H.W Write a program receives student's marks (8 marks) and evaluates the average:

If 50<=average<60 print "poor".

If 60<=average<70 print "medium".

If 70<=average<80 print "good".

If 80<=average<90 print "very good".

If 90<=average<=100 print "excellent".

Otherwise print "fail".

CONDITIONAL SELECTION OPERATOR ( ? : )

If there are two options to choose from, the conditional selection operator ( ? : ) may be

used in place of if … else . The syntax is illustrated below :

condition ? statement 1 : statement 2

The above expression means that if the condition is true then statement1 will be executed,

otherwise statement2 will be executed. For example:

m>n ? max = m : max = n ;

y=(x>3) ? 100:200;

z=(x>3) ? x*x : 2*x+1;

Ex: Use the selection operator ( ? : ) to find the maximum of four integers.

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[17]

#include<iostream.h>

void main( )

int A, B, C, D, max;

cout<< "Enter four numbers : " ;

cin>>A>>B>>C>>D ;

int max1=(A > B) ? A:B ;

int max2=(C > D) ? C:D ;

max=(max1 > max2) ? max1:max2 ;

cout<< "Maximum of four numbers = "<< max;

max=((A>B?A:B)>(C>D?C:D)?(A>B?A:B):(C>D?C:D));

H.W Use the selection operator ( ? : ) to find the maximum of six integers.

3. The switch STATEMENT (Multiple Choice Statement)

When a multiple selection is required we may use switch statement which is illustrated

below:

switch (expression or variable )

case value1 : statement1; break;

case value2 : statement2; break;

.................

case value n : statement n; break;

default : statement;

During execution of the program, the expression is evaluated and compared with the

values mentioned in different cases of switch expression. If the value matches a value of a

particular case, the statements in that case are executed. If no case-value matches with the

value of the expression the program goes to the last statement which is a default statement as

shown in figure below:

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[18]

Note The word break means exit from switch statement.

The following program illustrate the switch statement.

#include<iostream.h>

void main( )

int day;

cout<<" Enter the week day (1-7)";

cin>> day;

switch (day)

case 1: cout<<"The day is Sunday" ; break;

case 2: cout<<"The day is Monday" ; break ;

case 3: cout<<"The day is Tuesday" ; break;

case 4: cout<<"The day is Wednesday" ; break;

case 5: cout<<"The day is Thursday" ; break;

case 6: cout<<"The day is Friday" ; break;

case 7: cout<<"The day is Saturday" ; break;

default: cout<<"The number is not in range.";

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[19]

Ex: Write a program to receive an arithmetic operator and two integers, the program

performs the arithmetic operation on the two numbers (use switch statement).

#include<iostream.h>

void main( )

char ch;

int x,y;

cout<<"Enter the arithmetic operator : "<<endl;

cin>>ch;

cout<<"Enter the two numbers : "<<endl;

cin>>x>>y;

switch(ch)

case '+' : cout<<x + y ; break;

case '–' : cout<<x - y ; break; case '*' : cout<<x * y; break;

case '/' : cout<<x / y; break;

case '%' : cout<<x % y; break;

default : cout<<" Error try again";

H.W.

Write a program to find the value of y from the following (using switch statement).

√岫 岻 sin岫 岻

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[21]

LOOP AND OTHER CONTROL STATEMENTS

In C++ programming language, there are three loop statements, they are:

1. The while statement (loop) .

2. The do…while statement (loop) .

3. The for statement (loop).

1. THE while STATEMENT.

The while statement or loop is as illustrated below :

while (conditional expression)

Block_of_statements ;

This means that as long as the condition is true,

Block_of_statements will be executed.

Ex: while (i <= n)

sum +=i++;

Ex: Use while loop to find the sum of numbers from 1 to 10.

#include <iostream.h>

void main( )

int n = 10, i= 0, sum = 0;

while (i <= n)

Sum += ++i;

cout<< "Sum = "<< sum;

The following loop is called endless loop because the condition is always true:

while (true)

statement;

Ex: Write a program to find the sum of squares of integers.

#include<iostream.h>

main( )

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[21]

int i = 1, n, sum = 0;

cout << "Enter a positive integer:";

cin>>n;

while (i <= n)

sum += i*i;

i++;

cout << " sum = " << sum ;

return 0;

THE NESTED while STATEMENTS

When more than one parameter such as i and j are to be varied in a program, two loops

are required. The i loop is the outer loop and j loop is the inner loop. The code may be written

is illustrated below.

while (int i < n)

while (int j < m)

statements ;

The following program illustrates nested while loops by finding the the value of Z:

∑∑

#include <iostream.h>

//The program illustrates nested while loop

void main()

int i=0, Z=0;

while (i<=5) // outer while loop

int j = 0;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[22]

while (j<=4) // inner while loop

Z+=(i*j);

++j

++i;

cout<<"Z="<<Z;

2. THE do…while LOOP

The do...while statement is almost the same as the while statement. Its syntax is:

do

Block_of_statements;

while (condition);

The only difference between while and

do…while is that the do...while statement

executes the statements first and then tests

the condition. These two steps are

repeated until the condition becomes false.

A do...whi1e loop always iterates at least

once, regardless of the value of the

condition, because the statement executes

before the condition is evaluated.

Ex: Write a program to evaluate the factorial of an integer.

#include<iostream.h>

void main()

int n, f = 1;

cout << "Enter a positive integer: ";

cin >> n;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[23]

do

f *= n;

--n;

while (n > 1);

cout <<"factorial of"<<n<<" is"<< f ;

3. THE for LOOP

The for loop is written as given below: -

for (initial value ; condition ; increment /decrement)

Block_of_statements ;

The for loop is controlled by three expressions: an initialization, a condition, and update

(increment/decrement).

Ex:

for (i=0 ; i<=10 ; i++)

x=i+2 ;

The statement (x=i+2) is executed repeatedly

as long as (i< = 10 ).

Ex: Write a program to evaluate the factorial of an integer.

#include<iostream.h>

void main()

int n, f=1,i;

cout << "Enter a positive integer: ";

cin >> n;

for(i=1;i<=n;++i)

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[24]

f *= n;

cout <<"factorial= "<< f ;

NESTED for LOOPS

If a function involves more than one variable and we want to evaluate it for different

values of all the variables, we will have to use a nested for loop, as illustrated below:

for ( int n=0; n<= A; n++)

for ( int m=0; m<= B ; m++)

Statements;

Ex : Write a program finds the value of Z form the following formula: ∑ ∑

#include<iostream.h>

void main()

int i, j, sum=0;

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

for(j=0;j<=4;++j)

Z+=(i*j);

cout<<"Z="<<Z;

Ex: Write a program receives 25 integers and find the sum and the average.

#include<iostream.h>

void main()

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[25]

int i, x, sum=0;

float av;

for (i=1; i<=25; ++i)

cin>>x;

sum+=x;

av=sum/i;

cout<<"sum= "<<sum<<endl;

cout<<" average= "<<av;

Ex: Write a program prints the following form.

0

21012

3210123

9876543210123456789

#include<iostream.h>

void main()

int i,j,k,m;

for (i=1; i<=10; i++)

for (j=10;j>=i; j--)

cout<<" ";

for (k=i; k>=1; k--)

cout<<k;

for(m=2; m<=i; m++)

cout<<m;

cout<<endl;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[26]

Ex: Write a program to find the sum of the following series.

#include<iostream.h>

void main( )

int i, j=2, r, n;

long f;

float p, x, sum=0;

cin>>x>>n;

while(j<=n)

i=r=f=1;

while(i<=j)

f*=i;

++i;

p=pow(x,j)

sum=sum+(f/p)*r;

j+=2;

r*=-1;

cout<<"sum="<<sum;

ENDLESS for LOOP

If for loop is written as below it is called endless loop:

for (int i = 0 ; i<10 ; )

for ( ; ; )

THE break STATEMENT

We have already seen the break statement used in the switch statement. It is also used in

while, do…while, and for loops. When it is executed, it terminates the loop, “breaking out” of

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[27]

the iteration at that point. The following program illustrates the use of endless loop and break

statement:

#include<iostream.h>

void main( )

int i =1,sum=0 ;

for( ; ; ) //endless for loop

sum += i;

if (sum >25)

break;//break to end the loop.

i++;

cout<<"sum="<<sum;

THE continue STATEMENT

The continue statement goes back to the beginning of the loop to begin the next iteration.

#include<iostream.h>

main( )

int n;

for (;;)

cout<< "Enter an integer:";

cin >> n;

if (n%2 == 0) continue;

if (n%3 == 0) break;

cout<< "Hello my friend."<<endl;

cout << "Outside of loop";

Ex: Write a program to find the sum of the series (the sum doesn't exceed 50000):

13 + 33 + 55 + 77 + … # include <iostream.h>

# include <math.h>

void main()

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[28]

int i =1,sum=0;

cin>>n;

while ( i>0)

sum = sum + pow(i,i) ;

if (sum>50000)

break;

i+= 2 ;

cout<<" The sum of the series = "<<sum<<endl;

Ex: Write a program to find the sum of the following series:

1 + 1/2! + 1/3! + … 1/n!

# include <iostream.h>

void main()

int i,j,n;

long fact;

float sum=0;

cout<<" Enter the value of n :"<<endl;

cin>>n;

for (i=1;i<=n;i++)

fact=1;

for (j=1;j<=i;j++)

fact = fact * j;

sum+= 1/float(fact);

cout<< " The sum of the series "<< sum;

H.W Write a program prints the following form:

* ***

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

*********

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[29]

FUNCTIONS

A function is a group of statements used to perform a certain operation. It is called

from some point of the main program or another function. There are several (تستدعى)

advantages of using functions:

Functions allow for breaking down the program into discrete units.

Programs that use functions are easier to design, program, debug and maintain.

Functions are of two types:

1. Functions return a value to the main program end with return statement.

2. Functions do not return a value defined by the word void.

1. FUNCTIONS RETURN A VALUE:

The function definition is illustrated below:

type function_name (type parameter1, type parameter2, …… )

statements ;

return value;

In the above definition the first word is the type of the function, it is the type of data it returns.

The second item is the name of the function. (type parameter1, type parameter2, ……) are

called arguments of the function. For example:

int sum(int x, int y)

int sum=x+y;

return sum;

ACCESSING A FUNCTION (The Call of the Function) استدعاء الدالة The main program calls the function by declaring a variable followed by the function

name and its arguments, as follows:

type variable_name=function_name(arguments)

For example:

int s1=sum(a, b) ;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[31]

Ex: Write a function finds the sum of two numbers, the main program calls the function

to find the sum of four numbers.

#include<iostream.h>

float sum(int x, int y)

float z=x+y;

return z;

main( )

float a,b,c,d;

cin>>a>>b>>c>>d;

float s1=sum(a,b);

float s2=sum(c,d); float s=sum(sum(a,b),sum(c,d));

float s=sum(s1,s2);

cout<<"sum= "<<s;

return 0;

Ex: Write a program includes a function receives a character and returns its type

(number, lowercase alphabet, uppercase alphabet, or symbol )

#include <iostream.h>

int chkletter( char c)

if(c >= 'A' && c <= 'Z')

return (1);

else if(c >= 'a' && c <= 'z')

return (2);

else if (c>='0' && c<='9')

return (0);

else return(3);

main()

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[31]

int type;

char ch;

cout << "Enter the character:"<<endl;

cin >> ch;

type = chkletter( ch );

switch(type)

case 0: cout << "It is a number"; break;

case 1: cout << "It is an uppercase alphabet"; break;

case 2: cout << "It is a lowercase alphabet"; break;

default: cout<<" It is a symbol";

return 0;

Ex: Write a program includes two functions, the first is named power receives two

numbers and return the power and the second is named octal receives an octal

number and returns the decimal value by using the first function.

#include<iostream.h>

int power(int x, int y)

int p=1;

if (x==0)

return p;

else

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

p*=y;

return p;

int octal(int z)

int m=0, sum=0;

while(z!=0)

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[32]

int y=z%10;

int k=power(m, 8);

sum+=k*y;

z/=10;

++m;

return sum;

main( )

int A;

cin>>A;

int n=octal(A);

cout<<n;

Ex: Write a function that finds the factorial of an integer, the main program calls the

function to compute “y” from the following formula.

y=k!*m!/(k-m)!

#include<iostream.h>

long fact (int n)

long f=1;

int i;

for(i=1; i<=n; i++)

f*=i;

return f;

main( )

long y;

int k, m;

cin>>k>>m;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[33]

if (m>k)

long f1=fact(k);

long f2=fact(m);

long f3=fact(k-m); y=fact(k)*fact(m)/fact(k-m);

y=f1*f2/f3;

cout<<"y="<<y;

else cout<<"Error";

return 0;

2. VOID FUNCTIONS

A function does not return a value to the main program and is known as a procedure or a

subroutine. In C++, such a function is identified simply by placing the word void before

the name of the function as shown below:

void function_name (arguments)

For example :

void AA(int x, int y)

int sum;

sum=x+y;

cout<<sum;

This type of functions is called by its name without using any variable as shown:

AA(a, b) ;

Ex: Write a function that find and print the square of an integer, the main program

calls this function to find the squares of 0-10.

#include<iostream.h>

void square(int x)

int z;

z=;

cout<<x<<"\t"<< x*x <<endl;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[34]

main( )

cout<<"x\t"<<"x*x"<<endl;

cout<<"--\t"<<"----"<<endl;

int i;

for(i=0; i<=10; i++)

square(i);

return 0;

The following function does not receive arguments form the main program and does not

return value to the main program. The definition is as shown below:

void AA(void)

cout<<”this is a C++ program”;

The call of this function is as shown below:

AA( );

H.W. (1) Write a program to find the sum of the following series:

S=(1) + (1+2) + (1+2+3) + (1+2+3+4) +…………+ (1+2+3+……….+n) (2) Write a program include two functions, the first is named fact receives one integer and returns its factorial, and the second is named pow receives two integers and returns the power of them. The main program uses the two functions to find the value of Z from the following series.

n

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[35]

ARRAYS AND MATRICES

In an array, multiple values of the same data type can be stored with one variable name. In

computer, array elements are stored in a sequence of adjacent memory locations. Arrays are

of two types:

1. One dimensional array.

2. Multi-dimensional array.

1. ONE DIMENSOINAL ARRAY

The position of an element in array is called array index or subscript. In the case of

an array of five elements A[4]=6 , 7, 8, 9,, their index or subscript values are 0, 1, 2,

and 3 . Note that count for array elements or subscripts starts from 0 as shown below.

A[0] = 6 0 1 2 3

A[1] = 7

A[2] = 8

A[3] = 9

The declaration of one dimensional array is done as illustrated below.

type name [number of elements in the array] ;

for example:

int A[10]; // Array „A‟ has 10 elements of type integer.

float B[20]; // Array „B‟ has 20 elements of type float.

double D[15]; // Array „D‟ has 15 elements of type double.

char name[20]; // Array 'name' has 20 elements of type char.

INPUT/OUTPUT OF ONE DIMENSOINAL ARRAY

The input/output of an array is carried out element by element either a for loop or while

loop may be used. For example, an array Bill[5] having n elements are to be read as follow:

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

cin>> Bill[i] ;

An array can be read by another way called “static initialization” as shown:

int Bill[5]=10, 20, 30,40, 50; るعند تعريف المصفوف りاشرらإعطاء قيم م

Index

Element

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[36]

and the output (printing) is as follows:

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

cout<< Bill[i]<<" " ; لطらاعتها على شكل صف

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

cout<< Bill[i]<<endl ; لطらاعتها على شكل عمود

2. TWO DIMENSIONAL ARRAYS (MATRIX)

The two dimensional array is represented by ith rows and jth columns. The figure below

shows an array of two rows and five columns.

A[0][0] = 5 0 1 2 3 4

A[0][1] = 2 0

A[1][0] = 6 1

A[1][3] = 9

A two dimensional array can be declared as below.

type name [number of rows][number of columns];

For example:

int A[2][5];

float B[10][20];

INPUT/OUTPUT OF TWO DIMENSOINAL ARRAY

The two dimensional array A[m][n] can be read as follow:

for(i=0; i<m; i++)

for(j=0; j<n; j++)

cin>>A[i][j];

We can use the static initialization with the two dimensional array as follow:

float M[2][5]= 5.1, 2.2, 3.8, 2.5, 4.7, 6.1, 7.2, 8.8, 9.0, 8.4;

float M[2][5]= 5.1, 2.2, 3.8, 2.5, 4.7, 6.1, 7.2, 8.8, 9.0, 8.4;

To print a two dimensional array we can use the following form: for(i=0; i<m; i++)

for(j=0; j<n; j++) cout<<A[i][j]<<" "; cout<<endl;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[37]

Ex: Write a program to read an array of 50 real numbers, the program calculates the

sum and the average and the maximum element of the array.

#include<iostream.h>

void main( )

float A[50];

int i;

for (i=0; i<50; i++)

cin>>A[i];

float max=A[0];

for (i=0; i<50; i++)

float sum+=a[i];

if (A[i]>max)

max=A[i];

float av=sum/50;

cout<<sum<<av<<max;

Ex: Write a program to sort an array of 10 integers in an ascending order.

#include<iostream.h>

void main( )

int A[10]= 10,7,0,20,3,125,15,75,5,34;

int i, j, t;

for(i=0; i<9; i++)

for(j=i+1; j<10; j++)

if(A[i]>A[j])

t=A[i];

A[i]=A[j];

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[38]

A[j]=t;

for(i=0; i<10; i++)

cout<<A[i]<<" ";

Ex: Write a program to find the average of even and odd numbers in an array of 10

numbers.

#include<iostream.h>

void main( )

int A[10], se=0, so=0, i, ke=0, kn=0;

float ave, avo;

for(i=0; i<10; i++)

cin>>A[i];

for(i=0; i<10; i++)

if(A[i]%2==0)

se+=A[i];

++ke;

else

so+=A[i];

++ko;

ave=float(se)/ke;

avo=float(so)/ko;

cout<<"Average of even= "<<ave<<endl;

cout<<"Average of odd= "<<avo;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[39]

Ex: Write a program to read two matrices A[3][3] and B[3][3], and then to find the sum

and the difference of them.

#include<iostream.h>

main( )

int A[3][3], B[3][3], C[3][3], D[3][3];

int i, j;

for(i=0; i<3; i++)

for(j=0; j<3; j++)

cin>>A[i][j];

for(i=0; i<3; i++)

for(j=0; j<3; j++)

cin>>B[i][j];

for(i=0; i<3; i++)

for(j=0; j<3; j++)

C[i][j]=A[i][j]+B[i][j];

D[i][j]=A[i][j]-B[i][j];

for(i=0; i<3; i++)

for(j=0; j<3; j++)

cout<<C[i][j]<<” “; cout<<endl;

for(i=0; i<3; i++)

for(j=0; j<3; j++)

cout<<D[i][j]<<” “; cout<<endl;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[41]

Ex: Write a program to find the product of two matrices S[3][3] and P[3][3].

#include<iostream.h>

void main()

int S[3][3] = 1,2,3,4,5,6,7,8,9;

int P[3][3] = 9,8,7,6,5,4,3,2,1;

int C[3][3] = 0, i,j,k;

for (i =0 ; i<3; i++)

for (j = 0; j<3; j++)

for (k = 0; k<3; k++)

C[i][j] += S[i][k] * P[k][j] ;

for (i =0 ; i<3; i++)

for (j = 0; j<3; j++)

cout<<C[i][j]<<“ ”; cout<<endl;

Ex: Write a program reads a matrix A[4][4] of real numbers, and then generates an

array of four elements, the first element is the sum of the diagonal elements of the

matrix, the second is the sum of the upper triangular elements, the third is the sum

of the lower triangular elements, and the forth is the sum of the secondary diagonal

elements.

#include<iostream.h>

main( )

int i, j;

float A[4][4], B[4];

for(i=0; i<4; i++)

for(j=0; j<4 ;j++)

cin>>A[i][j];

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[41]

for(i=0; i<4; i++)

for(j=0; j<4;j++)

if(i==j) B[0]+=A[i][j];

else if(j>i) B[1]+=A[i][j];

else if(i>j) B[2]+=A[i][j];

B[3]+=A[i][3-i];

for(i=0; i<4; i++)

cout<<B[i]<<" ";

return 0;

Ex: Write a main program reads three arrays of 8 integers. The program calls two

functions max and min return the maximum and the minimum of an array to

generate a matrix, each row includes the max and min of each array.

#include<iostream.h>

int max(int x[8])

int n, max;

max=x[0];

for(n=1; n<8; n++)

if(x[n]>max) max=x[n];

return max;

int min(int y[8])

int n,min;

min=y[0];

for(n=1; n<8; n++)

if(y[n]<min) min=y[n];

return min;

C++ LECTURES ABDULMTTALIB. A. H. ALDOURI

[42]

main( )

int A[8], B[8], C[8], E[2][3];

int i,j;

for(i=0; i<8; i++)

cin>>A[i];

for(i=0; i<8; i++)

cin>>B[i];

for(i=0; i<8; i++)

cin>>C[i];

for(i=0; i<8; i++)

cin>>D[i];

E[0][0]=max(A);

E[0][1]=min(A);

E[1][0]=max(B);

E[1][1]=min(B);

E[2][0]=max(C);

E[2][1]=min(C);

for(i=0; i<3; i++)

for(j=0; j<2; j++)

cout<<E[i][j]<<" ";

cout<<endl;

return 0;