0% found this document useful (0 votes)
11 views

C++ Chapter 1-5

Uploaded by

qusic8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

C++ Chapter 1-5

Uploaded by

qusic8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Q ) How to install C++ on your PC?

You need the BC4.5 package (Borland C++ )  CD:\Install CD:\Install\BC45\Install.exe

-------------------------------------------------------------------------------------------------------

Q ) How to open Borland C++ 4.5 ?

Start  Programs  Borland C++ 4.5  Borland C++

-------------------------------------------------------------------------------------------------------

Q ) How to save your program file ?

File menu  Save  Choose the path  Ok

-------------------------------------------------------------------------------------------------------
Q ) How to Run your C++ program?

Debug menu  Run or ( ctrl+F9 )

2
Chapter 1 : Introduction

Before considering the programming of a computer a brief overview of the basic structure of a Computer in
terms of its main components is given.

Every Computer perform three main operations:

1. Receive input : Raw fact (Data )


2. Process it according to predefined instructions.
3. Produce output : meaningful data (Information )

Input (data)  Process(CPU)  Output ( information )

1.1 Computer System

1. Hardware : physical components like Screen, Cables, keyboard, System Box and Printer .
2. Software : set of instructions that tells the computer what to do and how to do it .
3. User : people who use the software on the computer.

1.2 Computer structure

 A computer consists of a Central Processing Unit(CPU), memory and various devices which can be
categorised as Input/Output Devices.
 Information is communicated between these separate units by the Systems Bus.
 The Central Processing Unit (CPU) consists of a Control Unit and an Arithmetic/Logic Unit (ALU).
The control unit controls the operation of the peripheral devices and the transfer of information
between the units that make up the computer. The Arithmetic/Logic Unit performs calculation.
 The memory of the computer is split into main memory and external memory.
 Main memory is fast and limited in capacity. The CPU can only directly access information in main
memory. Main memory cannot retain information when the computer is switched of. Main memory
consists of a series of numbered locations called bytes, each byte being eight bits. The number
associated with a byte is the address of the byte.
 Secondary memory is slow and virtually unlimited in capacity. It retains information when the
computer is switched off. Information on external memory can only be accessed by the CPU if it is
first transferred to main memory.
 The internal representation of information in the computer and on external memory is in terms of the
Binary system using only the basic symbols 0 and 1.
 Programs to be executed by the computer are placed in main memory and the CPU fetches each
instruction in turn from memory and executes it.
 Each type of CPU has its own machine language, the set of instructions it can obey.

1.3 Programming Languages level

1. Machine language all computers have an internal machine language which they execute directly.
This language is coded in a binary representation and is very tedious to write.  ( 0,1)

2. Assembly Language are a more human friendly form of machine language.but the computer does
not directly understand assembly language this has to be translated into machine language by a
program called an assembler.

3. High level Languages are much closer to human language. One of these languages is C & C++.
3
the computer does not understand these high-level languages directly and hence they have to be
processed by passing them through a program called a compiler which translates them into internal
machine language before they can be executed.

 C++ is a High level Languages ( third generation language ).


 Derived from the C language ,C was derived from the B language , B was derived from the BCPL
language ( BCPL  B  C  C++ ). C++ was originally developed by Bjarne Stroustrup
 C++ is a case-sensitive. That is lower-case letters are distinct from upper-case letters.

H.w : Why has developed C language to the language of C++ not to C+?

1.4 Basics of typical C++ Environment

Phases of C++ Programs:

1. Edit
2. Preprocess
3. Compile
4. Link
5. Load
6. Execute

1.5 Getting Started with C++

A C++ program is a collection of commands, which tell the computer to do "something". This collection of
commands is usually called C++ source code, source code or just code. Commands are either "functions"
or "keywords". Keywords are a basic building block of the language, while functions are, in fact, usually
written in terms of simpler functions. C++ provides a great many common functions and keywords that you
can use.

But how does a program actually start? Every program in C++ has one function, always named main, that is
always called when your program first executes. From main, you can also call other functions whether they
are written by us or, as mentioned earlier, provided by the compiler.

1.6 Structure of a C++ program

# include < library.h > Preprocessor directive


int main ( ) main function (every C++ programs have a main function)

{ Beginning of main function


:
: Body of main function
:
return 0 ; indicate that program ended successfully

} Ending of main function

Note that input/output is defined in a library, so if you want your program to be able to do any simple I/O, which you
normally do, you need to use #include <iostream.h>.

4
A first program in C++.

// A first program in C++.


#include <iostream.h>
int main()
{
cout << "Hello, world!\n";

return 0;
}

Line 1

// A first program in C++

• Any line starts with a // indicating that the reminder of each line is a comment.

Why ?

1. To document program and improve program readability .


2. To help others understand your code.

What happened ?

Comments are simply text that is ignored by the C++ compiler, but that may inform the reader of what
you are doing at any particular point in your program.

Note: C++ programmers may also use C’s comment style in which a comment-possibly containing many lines-
begins with /* and ends with */  ( /* comments here */).

Line 2

#include <iostream.h>

Lines beginning with # are processed by the preprocessor before the program is compiled. Line 2 #include
<iostream.h> tells the preprocessor to include in the program the contents of the input/output stream header
file <iostream.h> . this file must be included for any program that outputs data to the screen or input data
from the keyboard.

Line 3

int main ( )

1. Part of every C++ program.

2. ( ) indicate that main is a program building block called a function.

3. C++ contain one or more functions.  function name : main

4. int indicate that main returns an integer value.  return type: int

5
Line 4

• left brace must begin the body of every function.

Line 5

cout << "Welcome to C++!\n";

1- each line ends with semicolon called statement.

2- cout Standard output stream

3- << Stream insertion operator

4- Value to right (right operand) inserted into output stream

5- \ Indicates “special” character output. \ n means position the screen cursor to the beginning of the next
line ( newline ).

Line 7

return 0;

• This line is necessary because the return type function (int main() ) is int
• It’s included at the end of most main function and it means we will use it to exit a function.
• The value 0 indicates that the program has terminated successfully.

Line 8

• Right brace must end the body of each function.

6
Chapter 2 : Elements of a C++ program

2.1 Output statement (cout) :


cout << : Displays output on the computer screen.

cout is the name of the standard output stream, normally the monitor.

The insertion operator (<<) evaluates the argument that follows it and places it in the output stream that
precedes it.
Here are some valid cout statements:

1- cout << "Hello"; // "Hello" is a string


2- cout << 27; // 27 is a value
3- cout << 2+3; // 2+3 is an expression
4- cout << "result" << 5+7; // you can concatenate << operators on a line

The insertion operator (<<) may be used more than once in a single statement:

1) cout << "First " << "Program " ;


2) cout << " Welcome " << " to " << " Jordan. "; Welcome to Jordan.
3) cout << "First"; First Program
cout << "Program"; FirstProgram

Note : To end a line of output you can use "\n" or << endl.

2) cout << "First" << endl ; First


cout << " Second " ; Second
or by another way
cout << "first" << endl << "Second";
or by using \n
cout << "First sentence.\n"; First sentence.
cout << "Second sentence.\nThird sentence."; Second sentence.
Third sentence.

-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
Hello there.
#include <iostream.h> Here is 3:3
int main()
{ // Beginning of main function Here is the sum of 3 and 4:7

cout << "Hello there.\n";


cout << "Here is 3: " << 3 << "\n";
cout << endl; // To print a blank line
cout << "Here is the sum of"<<" 3 and 4:" << 3+4 << endl;
return 0; // indicate that program ended successfully
} // ending of main function
-------------------------------------------------------------------------------------------------------
Ex. Write a C ++ program to print :
Welcome
To
# include <iostream.h> AHU
void main()
{
cout << "Welcome "<<endl<<"To"<<endl<<"AHU"; }

7
Ex. Write a C ++ program to print : Welcome
To
# include <iostream.h> AHU
main()
{
cout << "Welcome \n"<<"To"<<endl<<"AHU";
}

Note : we can write cout << "Welcome \n"<<"To\n"<<"AHU";


-------------------------------------------------------------------------------------------------------
Ex. Write a C ++ program to print :
*
#include <iostream.h> **
void main() ***
****
{
cout << "*"<<endl;
cout << "**"<<endl;
cout << "***"<<endl;
cout << "****";
}

Note : we can write cout << "*"<<endl<<"**"<<endl<<"***"<<endl<<"****";


-------------------------------------------------------------------------------------------------------
Ex. Write a C ++ program to print :
*******
*Hello*
#include <iostream.h>
* *
void main()
*******
{
cout << "*******"<<endl;
cout << "*Hello*"<<endl;
cout << "* *"<<endl;
cout << "*******";
}
-------------------------------------------------------------------------------------------------------
Ex. Write a C ++ program to print :
*
**
#include <iostream.h>
***
void main()
****
{
cout << "*"<<endl; ***
cout << "**"<<endl; **
*
cout << "***"<<endl;
cout << "****";
cout << "***"<<endl;
cout << "**"<<endl;
cout << "*"<<endl;
}
-------------------------------------------------------------------------------------------------------
Ex. Write a C ++ program to print :
*
#include <iostream.h> **
void main() ***
****
{
cout << " *"<<endl;
cout << " **"<<endl;
cout << " ***"<<endl;
cout << "****";
}
-------------------------------------------------------------------------------------------------------
8
2. 2 Escape characters

Notation Description
\n move to the next line (new line )
\t move to the next tab (Horizontal Tab )
\v vertical tab
\a Alert ( sound )
\r Carriage return (return to the first position )
\\ Used to print single backslash \
\' Used to print single quotation mark '
\" Used to print double quotation mark "
\b Backspace ( Erase one char from right to left )
\? Used to print question mark ?
\0 Null character

Ex. Trace the following program and show the output ?

#include <iostream.h>
void main()
{ A\\\B?"C'
cout << "A\\\\\\B\?\"C\'"<<endl; A\\B??"C'
cout << "A\\\\B\?\?\"C\'"<<endl; A CD
cout << "A\t CDE\b\0ABCD"<<endl;
}

Note : any string comes after the "\0" is ignored.


-------------------------------------------------------------------------------------------------------
2. 3 Constants
Constants are fixed value cannot change .for example 123, 12.33 , 'a',"abc" are constats
-------------------------------------------------------------------------------------------------------
2.4 Variables (identifiers):

variables are names for memory locations , the value stored in the variable can be changed.

Rules for Naming C++ Variables


1) They must begin with a letter or underscore ( _ )  Don't start a variable with a digits.
2) After the first initial letter, variable names can consist of a letters, digits or underscores .
 Don't use spaces or special characters such as $, &, * or %.
3) Don't use keywords (reserved words) as variable names  you could use Int as an identifier since it is
different from the reserved word int.

• A variable must be declared before it can be used.


• Tells the compiler the Type of data to store
• upper case and lower case characters are distinct  C++ is a case-sensitive language

Ex. which of the following is considered as legal variable name:

1. Ali 2. cout 3. if 4. Ab c 5. 123ab 6. Average 7. N_2 8. x123 9. ab*#c 10.COUT


1. legal 2. illegal 3. illegal 4. illegal 5. illegal 6. legal 7. legal 8. legal 9. illegal 10. legal

9
Data Types

Every variable in C++ can store a value. However, the type of value which the variable can store has to be
specified by the programmer. C++ supports the following inbuilt data types:- short, int and long int (to store
integer values), float, double and long double (to store decimal values) and char (to store characters), bool
(to store Boolean value either 0 or 1) and void (signifies absence of information).The types and size of
variables used in C++ programs are described in following table .

Data Type Size Range


short int 2 byte -32,768 to +32,767
unsigned short int 2 byte 0 to +65,535
int 4 byte -2,147,483,648 to +2,147,483,647
unsigned long int 4 byte 0 to +4,294,967,295
long int 4 byte -2,147,483,648 to +2,147,483,647
unsigned int 4 byte 0 to +4,294,967,295
char 1 byte -256character values
bool I byte True or false
float 4 bytes 1.2e-38 to 3.4e38
double 8 bytes 2.2e-308 to1.8e308

Declaration of variables

Type variable_ name ;


e.g. int x; char y; float m;
If you are going to declare more than one variable of the same type, you can declare all of them in a single
statement by separating their identifiers with commas.
e.g. float x, y, z ;
This declares three variables (x,y and z), all of them of type float, and has exactly the same meaning as:
float x ;
float y ;
float z ;

Initialization of variables

When declaring a regular local variable, its value is by default undetermined. But you may want a variable
to store a concrete value at the same moment that it is declared. In order to do that, you can initialize the
variable, by appending an equal sign followed by the value to which the variable will be initialized:

type variable_name = initial_value ;

For example, if we want to declare an integer variable called X initialized with a value of 10 at the moment
in which it is declared, we could write: int X = 10;

If you are declaring several variables of the same type in one line and you want to initialize them all, you
have to initialize each one separately. e.g.int x = 1, y = 3;
Ex. Find the summation of two integer values .
# include <iostream.h>
main()
{
int a,b,sum; // declare 3 variables
a=5; // assignment 5 to a The result is: 12
b=7; // assignment 7 to b
sum=a+b; // assignment result to sum
cout <<"The result is: "<< sum; // print sum
}
-------------------------------------------------------------------------------------------------------
10
The constant Variable
Constants are expressions with a fixed value.you can't modify constant variable after their
definition.

Declared constants (const)

With the const prefix you can declare constants with a specific type in the same way as you would do with a
variable:
int x = 4; // a normal variable that can be modified
x = 10; // legal
const int z = 2; // const variable can be initialized, not modified thereafter
z = 10; // error - cannot modify const variable
constants are like regular variables except that their values cannot be modified after their definition.
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h>
main()
{ /* all character store in ASCII code so 65 is the code of A , 66 is the code of B
and so on .*/
char letter ;
letter=65; A
B
cout<<letter<<endl;
letter=66;
cout<<letter<<endl;
}
Ex. What is the output of the following program?
# include <iostream.h>
int main()
{
char letter ; A
letter='A'; B
cout<<letter<<endl;
letter='B';
cout<<letter<<endl;
return 0;
}

Ex. What is the output of the following program?


# include <iostream.h>
int main()
{
// bool data type (Boolean) set to either true or false
bool boolvalue;
boolvalue=true;
cout<<boolvalue<<endl; true
boolvalue=false; false
cout<<boolvalue<<endl;
return 0;
}

Ex. Write a program that reads the radius of the circle (as double value) print the diameter the circumference
and the area , use the value 3.14 for π .
the radius=6
# include <iostream.h> diameter =12
int main () circle =37.68
{ area =113.04
const float pi=3.14 ;
float diameter,area,circle,r;
11
r=6.0;
cout<<"the radius = "<<r <<endl;

diameter = 2.0 * r;
cout<<"diameter = "<<diameter <<endl;
circle = 2.0 *pi* r;
cout<<"circle = "<< circle <<endl;
area = pi* r*r;
cout<<"area = "<< area <<endl;
return 0;
}
-------------------------------------------------------------------------------------------------------
2.5 Strings

Enclose string literals in " " ( two double-quote marks ) e.g."Ali Mohammad Al –Ghonmein"
-------------------------------------------------------------------------------------------------------
2.6 Reserved keywords

The C++ compiler uses words and they are therefore reserved. You cannot use them as variable names. like

auto const double float int short struct unsigned


break continue else for long signed switch void
case default enum goto register sizeof and or
char do not if return static union while
-------------------------------------------------------------------------------------------------------
2.7 Arithmetic Operators :

SYMBOL OPERATION EXAMPLE VALUE OF ans

+ addition ans = 7 + 3; 10

- subtraction ans = 7 - 3; 4

* multiplication ans = 7 * 3; 21

/ division ans = 7 / 3; 2

% modulus ans = 7 % 3; 1

-------------------------------------------------------------------------------------------------------
2.8 Logical Operators :

Used as conditions in loops, if statements


• && (logical AND)
true if both conditions are true. if ( (x == 2) && (y == 2) )
• || (logical OR)
true if either of condition is true. if ( (x == 2) || (y == 4)
• ! (logical NOT, logical negation)
Returns true when its condition is false, & vice versa. if ( !(x == 2) )
-------------------------------------------------------------------------------------------------------

12
2.9 Relational operators and Equality operators :

SYMBOL meaning EXAMPLE evaluates to

< Less than (5 < 5) false

<= Less than or (15 <= 5) false


equal to
> Greater than (5 > 4) true

>= Greater than or (6 >= 6) true


equal to
== Equal to (7 == 5) false

!= Not equal to (10 != 2) true

-------------------------------------------------------------------------------------------------------
2.10 Input statement (cin) :
cin >> : Read inputs from the standard input device (usually the keyboard).
cin is the name of the standard input stream. By default, this will be the keyboard.
The >> operator reads data from the input stream that precedes it and places it in the argument that follows
it. Here are some valid cin statements:

1. int x; cin >> x;


2. double d; cin >> d;
3. int i; double n; cin >> i >> n;

/* Here is an example of how >> behaves when asked to read input into an int, and
double */

-------------------------------------------------------------------------------------------------------
Ex. find the summation of two integer values ( read them from keyboard) .

# include <iostream.h>
main()
{
int a,b,c;
Enter the value of a
cout << "Enter the value of a " << endl; 20
cin >> a; Enter the value of b
cout << " Enter the value of b " <<endl; 15
cin >> b; The result of a+b= 35
c=a+b;
cout <<"The result of a+b= " << c;
}

Ex. Write a C ++ program to find the Average of three marks ?


# include <iostream.h>
main()
{
float m1,m2,m3,sum,avg;
cout<< "Enter mark 1 : " <<endl;
13
cin >> m1;
cout<< "Enter mark 2 : " <<endl; Enter mark 1 :
cin >> m2; 20
cout<< "Enter mark 3 : " <<endl; Enter mark 2 :
cin >> m3; 18
sum = m1+m2+m3; Enter mark 3 :
avg = sum / 3; 19
cout << "The average is : " << avg; The average is : 19
}

Ex. Write a C++ program to solve the equation : R = X3 + ( X + Y ) * 3


# include <iostream.h>
main()
{
int x,y,r;
cout << "Enter X :"; Enter X =1
cin >> x; Enter Y =2
cout << "Enter Y :"; R =10
cin >> y;
r = x*x*x+(x +y) *3;
cout<< " R = " <<r;
}
-------------------------------------------------------------------------------------------------------
2.11 Special characters :

Character Name Meaning


// Double slash Beginning of a comment

# Pound sign Beginning of preprocessor


directive
< > Open/close Enclose filename in
brackets #include
( ) Open/close Used when naming a
parentheses function
{ } Open/close brace Encloses a group of
statements
" " Open/close Encloses string of
quotation marks characters
; Semicolon End of a programming
statement

-------------------------------------------------------------------------------------------------------
2.12 Comma operator ( , )

The comma operator (,) is used to separate two or more expressions that are included where only one
expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost
expression is considered.
For example, the following code:

a=(b=3,b+2);

Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would
contain the value 5 while variable b would contain value 3.

-------------------------------------------------------------------------------------------------------
14
2.13 C++ Comments ( Notations )
A comment is text that the compiler ignores but that is useful for programmers.
A C++ comment is written in one of the following ways:
Notation Description
// Single line comment
/* */ Multi line comments
Ex. int s = 255; // Assigns the value 255 to the variables.

Ex.

/***************************\
* *
* This is the *
* Multi line comments *
* *
\***************************/

Ex. // cout<<"this is a single line comment ,ignored by compiler";


-------------------------------------------------------------------------------------------------------
2.14 Assignment operator

SYMBOL OPERATION Equivalent to VALUE OF


Ans = 7 Ans
= Ans = Ans + 3; Ans = 7 + 3; 10

+= Ans += 3 ; Ans = Ans +3; 10

-= Ans -= 3; Ans = Ans - 3; 4

*= Ans *= 3; Ans = Ans * 3; 21

/= Ans /= 3; Ans = Ans / 3; 2

%= Ans %= 3; Ans = Ans % 3; 1

-------------------------------------------------------------------------------------------------------
2.15 increment and decrement operators

Postfix/ Prefix increment and decrement

The postfix variety is written after the variable name (name++) or (name--).
C++;  use the value of C, then increment (C = C+1) it.
C-- ;  use the value of C, then decrement (C = C-1) it.
The prefix variety is written before the variable name (++name) or (--name);
++C;  increment the value of C (C = C+1), then use it .
- - C; Decrement the value of C (C = C-1), then use it .
X + = 1 equivalent to X + + equivalent to + + X equivalent to X = X + 1
X - = 1 equivalent to X - - equivalent to - - X equivalent to X = X – 1
-------------------------------------------------------------------------------------------------------

15
Ex. What is the output of the following program?
# include <iostream.h>
main() 21
{
int n =20; // assign 20 to n
cout << ++n; // ++n; cout<<n;
}
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h> 7 8
main()
{
int n = 7; // assign 7 to n
cout << n++ <<" "; // cout<<n; n++;
cout << n; // print 8
}
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h>
main()
{
int n = 5; // assign 5 to n 68
n++; // increment n
cout << n; // print 6
--n; // decrement n
n+=2;
n++; // increment n
++n; // increment n
cout << (n-=1); // calculate n=n-1; cout<<n;
}
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h> 6 8 5
main()
{
int n =5; // assign 5 to n
cout<<n<<" "<<n+2<<" "<<n++; // start from right to left
}
-------------------------------------------------------------------------------------------------------
Precedence of operators

When writing complex expressions with several operands, we may have some doubts about which operand
is evaluated first and which later. For example, in this expression:

a = 5 + 7 % 2

we may doubt if it really means:

1 a = 5 + (7 % 2) // with a result of 6, or
2
a = (5 + 7) % 2 // with a result of 0

The correct answer is the first of the two expressions, with a result of 6. There is an established order with
the priority of each operator, and not only the arithmetic ones (those whose preference come from
mathematics) but for all the operators which can appear in C++. From greatest to lowest priority, the priority
order is as follows:

16
Level Operator Description Grouping
1 ( ) ++ -- Grouping , postfix Left-to-right
2 ++ -- prefix Right-to-left
3 + - unary sign operator
4 * / % Multiplication, division, modulo Left-to-right
5 + - Addition and subtraction Left-to-right
6 < > <= >= Comparisons: less-than, ... Left-to-right
7 == != Comparisons: equal and not equal Left-to-right
8 & bitwise AND Left-to-right
9 ^ bitwise XOR Left-to-right
10 | bitwise OR Left-to-right
11 && logical AND Left-to-right
12 || logical OR Left-to-right
13 = *= /= %= += -= Assignment operators Right-to-left

Note :
Postfix increment/decrement have high precedence, but the actual increment or decrement of the
operand is delayed (to be accomplished sometime before the statement completes execution). So in
the statement y = x * z++; the current value of z is used to evaluate the expression (i.e., z++
evaluates to z) and z only incremented after all else is done.

-------------------------------------------------------------------------------------------------------
Important Notes

 All C++ programs must include a function main().


 All statements in C++ are terminated by a semi-colon ( ; ).
 Comments are ignored by the compiler. All characters between // and the end of the line are ignored by the
compiler.
 All variables and constants that are used in a C++ program must be declared before use. Declaration associates
a type and a name with a variable.
 The type int is used for integer numbers.
 The type float is used for real (decimal) numbers.
 The type char is used to represent single characters. A char constant is enclosed in single quotation marks ‘ ‘ .
 strings can be used in output statements and are represented by enclosing the characters of the string in
double quotation marks “ “.
 Variables names can only include letters of the alphabet, digits and the underscore character.
 Variables take values from input when included in input statements using cin >> variable-name.
 The value of a variable or constant can be output by including the name in the output list cout << output-list.
Items in the output list are separated by <<.
 To create new line in output we use '\n' ,"\n" or endl.
 any string comes after the "\0" is ignored.

-------------------------------------------------------------------------------------------------------

17
Ex. What is the output of the following program?

# include <iostream.h>
main()
{ output 20
int x=2,y=3; // assign 2 to x and 3 to y
cout<< x+ y * x + ( x+ ( y % x +y) *x % y % x ) * y + x*y;
}
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?

# include <iostream.h>
main()
{
int x=2,y=3; // assign 2 to x and 3 to y
cout<< x+ y * x + x+ ( y % x +y) *x % y % x * y + x*y;
} output 16
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?

# include <iostream.h>
main()
{
int x=2,y=3; // assign 2 to x and 3 to y
cout<< x+ y * x + x+ y % x +y *x % y % x * y + x*y;
} output 17
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?

#include <iostream.h>
main()
{
cout<<(3 + 2 * 3- 5 * 2 + 1 + (( 5 - 3 ) * 5) + -7 ) / 2.0;
} output 1.5
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?

#include <iostream.h>
main()
{
cout<<(3 + 2 * 3 – 5 * 2 + 1 + (( 5 - 3 ) * 5) + -7 ) / 2;
} output 1
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?

#include <iostream.h>
main()
{
cout<<(3 + 2 * 3 – 5 * 2 + 1 + (( 5 - 3 ) * 5) + -7 ) / 2*2+3;
} output 5
-------------------------------------------------------------------------------------------------------

18
Ex. What is the output of the following program?
# include <iostream.h>
main()
{
int X=5,Y=4,Z;
Z=X++ + Y; // Z=X+Y; X=X+1;
cout<<Z;
} output 9
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h>
main()
{
int X=5,Y=4,Z;
Z=++X +Y; // X=X+1; Z=X+Y;
cout<<Z;
} output 10
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h>
main()
{
int n=5,m=4,x;
x=n+ --m*m++ + --n*n; // --n; --m; x=n+m*m+n*n; m++;
cout<< x;
} output 29
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h>
main()
{
int n=5,m=4,x;
x=n+ --m * m++ + --n + --n + --m*m; // --m; --n; --n; --m; x=n+m*m+n+n+m*m; m++;
cout<< x;
} output 17
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?
# include <iostream.h>
main()
{
int X=5,Y=4,Z;
Z=X++ + Y++; // Z=X+Y; X++;Y++;
cout<<Z<<endl;
} output 9
-------------------------------------------------------------------------------------------------------
Ex. What is the output of the following program?

# include <iostream.h>
main()
{
int n=5,m=4,x;
x=(n+=3)*++(m-=2); // n+=3; m-=2; ++m; x=n*m;
cout<< x+x;
} output 48
-------------------------------------------------------------------------------------------------------
19
Another Example s about Postfix , prefix, and Precedence
Ex1: What is the output of the following program? 6 6
#include<iostream.h>
main ()
{
int x;
x=5; // assign 5 to x
cout<<x<<" "<<++x; The priority is for ++x before x , so it will execute first.
}
This statement is equivalent to  cout << ++x;
cout << x;
-------------------------------------------------------------------------------------------------------
Ex2: What is the output of the following program?
6 5
#include<iostream.h>
main ()
{
int x;
x=5; // assign 5 to x
cout<<++x<<" "<<x ;
}
Print 6 without change the value of x , changes performs after execute the cout statement , if there are
another cout it will take the new value .
Note: if we divide the statement as :
cout << ++x;
cout << x;
this will print 6 6
-------------------------------------------------------------------------------------------------------
Ex3: What is the output of the following program?
#include<iostream.h>
main () 6 6 5
{
int x;
x=5; // assign 5 to x
cout <<x<<" "<<++x<<" "<<x; //from right to left
}
-------------------------------------------------------------------------------------------------------
Ex4: What is the output of the following program?
#include<iostream.h> 7 7 6 6
main ()
{
int x;
x=5; // assign 5 to x
cout << x <<" "<< ++x <<" "<< x <<" "<< ++x ; //from right to left
}
-------------------------------------------------------------------------------------------------------
Ex5: What is the output of the following program?

#include<iostream.h> 8 7 6
main ()
{
int x;
x=5; // assign 5 to x
cout << ++x <<" " << ++x <<" " << ++x; //from right to left
}
-------------------------------------------------------------------------------------------------------
20
Ex6: What is the output of the following program?

#include<iostream.h> 8 7 6 5
main ()
{
int x;
x=5;
cout << ++x <<" " << ++x <<" " << ++x <<" "<< x; //from right to left
}
-------------------------------------------------------------------------------------------------------
Ex7: What is the output of the following program?

#include<iostream.h> 55
main ()
{
int x;
x=5;
cout << x++ << x ; if we divide the statement as: cout << x++;
} cout << x;
this will print 5 6
-------------------------------------------------------------------------------------------------------
Ex8: What is the output of the following program?

#include<iostream.h> 65
main ()
{
int x;
x=5;
cout << x++ << x++ ; //from right to left
}

Note : NO changes during cout statement execution but if we divide the statement as:
cout << x++;
cout << x++;
this will print : 5 6
and if we write this : cout << x++;
cout << x++;
cout << x;
this will print : 5 6 7
-------------------------------------------------------------------------------------------------------
Ex9: What is the output of the following program?

#include<iostream.h> 7 7 5
main ()
{
int x;
x=5;
cout << x++ <<" " << ++x<<" " << x++; //from right to left
}
-------------------------------------------------------------------------------------------------------

21
Ex10: What is the output of the following program?
#include<iostream.h>
main () 6 5 5
{
int x;
x=5;
cout << x <<" "<< x++ <<" "<< x ; //from right to left
}
-------------------------------------------------------------------------------------------------------
Ex11: What is the output of the following program?
#include<iostream.h>
main () 6 6 5 5
{
int x;
x=5;
cout << x++<<" "<< x<<" "<< x++<<" "<< x; //from right to left
}
-------------------------------------------------------------------------------------------------------
Ex12: What is the output of the following program?
#include<iostream.h>
main () 7 6 6 5
{
int x;
x=5;
cout << x<<" "<< x++<<" "<< x<<" "<<x++; //from right to left
}
-------------------------------------------------------------------------------------------------------
Ex13: What is the output of the following program?
#include<iostream.h> 8 6 6
main ()
{
int x=5;
cout <<++x<<" "<<x++<<" "<<++x ; //from right to left
}
-------------------------------------------------------------------------------------------------------
Ex14: What is the output of the following program?
#include<iostream.h>
7 6 16
main ()
{ int X,Y,Z;
X=5;
Y=6;
Z=X++ + Y + X++; // Z=X+Y+X; X=X+1; X=X+1;
cout<<X<<" "<<Y<<" "<<Z<<endl;
}
-------------------------------------------------------------------------------------------------------
Ex15: What is the output of the following program?
#include<iostream.h>
15
main ()
4 5
{
int x,y,z;
x=2;
y=3;
z= x++ * x++ * y++ + y++; // z= x *x +y +y; x=x+1; x=x+1; y=y+1; y=y+1;
cout<<z <<'\n';
cout << x <<'\t'<< y;
}
-------------------------------------------------------------------------------------------------------
22
Ex16: What is the output of the following program?

#include<iostream.h>
main () 4
{ 2 3
int x,y,z;
x=2;
y=3;
z= x++ * --x * y++ + --y; // y=y-1; x=x-1; z=x*x*y+y; x=x+1; y=y+1;
cout<<z <<'\n';
cout << x <<'\t'<<y;
}
-------------------------------------------------------------------------------------------------------
Ex17: What is the output of the following program?

#include<iostream.h>
main () 3
{ 3 4
int x,y,z;
x=2;
y=3;
z= x++ * x++ * y++ - y++ + --y + --x;
cout<<z <<'\n';
cout << x <<'\t'<< y;
}
-------------------------------------------------------------------------------------------------------
Ex18: What is the output of the following program?

#include<iostream.h>
main () 5
{ 3 -1
int x,y,z;
x=2;
y=3;
z= x * --y + y-- * x++ + y--*--y;
cout<<z <<'\n';
cout << x <<'\t'<< y;
}
-------------------------------------------------------------------------------------------------------
Find the value of X :
Ex: X= 5 – 3 + 6*2  X = 14
Ex: X= 3 + 5*(10 – 6)  X = 23
Ex : X= 3 – 5*(4 – 6 * 2 – 5 + 7) + 8 * 3
Ex: X= 7 + 2 * (9 / 3) – 1
-------------------------------------------------------------------------------------------------------
Ex: What is the output of the following program?

#include <iostream.h>
void main()
{ Hello
Welcome
cout<<"Hello\nWelcome\0 to jordan";
}

Note : any string comes after the "\0" is ignored.


-------------------------------------------------------------------------------------------------------

23
Ex: What is the output of the following program?

-------------------------------------------------------------------------------------------------------
Ex: What is the output of the following program?

-------------------------------------------------------------------------------------------------------
Ex: What is the output of the following program?

#include <iostream.h>
main()
{
cout<<"abcd\nxyz\\xxx//xxxx\t\'xx\"\n\nabcd\b\0xxxx";
}
-------------------------------------------------------------------------------------------------------
Ex: What is the output of the following program?

#include<iostream.h>
main ()
{
cout<<"//\?xx\?\\xx%6^&*!;";
}
-------------------------------------------------------------------------------------------------------

24
Chapter 3 : Selection statements ( if , if / else ,if / else if ,switch )

3.1 The if Statement :

Syntax if ( condition ) statement ; || Block of Statement;

The if statement is used to execute an instruction or block of instructions only if a


condition is fulfilled.The condition can be any equality or relational comparison statement and must
be enclosed in parentheses. The block of instructions is enclosed in curly brackets and are indented for
readability.The braces are not required if only one statement follows the "if", but it is a good idea to get in
the habit of including them.

Ex: Write a single if statement that examines the student mark if "Passed" ?

# include <iostream.h> Enter your mark 75


main() Passed
{
int mark ;
cout << "Enter your mark : "; Enter your mark 45
cin >> mark ;
if ( mark >=50 ) cout<< "Passed";
}
-------------------------------------------------------------------------------------------------------
If we want more than a single statement to be executed in case that the condition is
true we can specify a block of instructions using curly brackets { }:

# include <iostream.h>
main()
{ 45
degree is 45 Positive
int degree;
cin>>degree;
if (degree >= 0) // The block executes only if the condition is TRUE.
{
cout << "degree is "<<degree;
cout << “Positive”;
}
}
-------------------------------------------------------------------------------------------------------
Ex: Enter two integer numbers and check the relationships that satisfy?
hint: use relational and equality operators
Enter two integer numbers :
10
# include <iostream.h> 5
main() 10 is greater than 5
{ 10 is greater than or equal
int x,y ; to 5
cout << "Enter two integer numbers : "<<endl; 10 is not equal to 5
cin >> x>>y ;
if ( x >y ) cout<< x<<” is greater than “<<y<<endl;
if ( x <y ) cout<< x<<” is less than “<<y<<endl;
if ( x >=y ) cout<< x<<” is greater than or equal to “<<y<<endl;
if ( x <=y ) cout<< x<<” is less than or equal to “<<y<<endl;
if ( x ==y ) cout<< x<<” is equal to “<<y<<endl;
if ( x !=y ) cout<< x<<” is not equal to “<<y<<endl;
}
-------------------------------------------------------------------------------------------------------
Note: If you put a semicolon after the test condition, the "if" statement will STOP. The block will not be executed.

25
3.2 The if / else Statement :
Syntax if ( condition )
Statement; || Block of Statement;
else
Statement; || Block of Statement;

Let's look at situations where your program requires two situations as the result of a decision, we need to
use the if/else statement.If the condition is TRUE, the block of statements following the
"if" executes. If the condition is FALSE, however, the block of statements following
the "else" executes instead.

Ex: write a C++ program to enter your mark then check the student mark if "Pass" or "Fail" :
# include <iostream.h>
main()
{ Enter your mark : 55
int m; Pass
cout << "Enter your mark : ";
cin >> m;
if ( m >=50 )
cout<< "Pass"; Enter your mark : 45
else Fail
cout << "Fail";
}
-------------------------------------------------------------------------------------------------------
Ex: Read integer number then check if it's Even or Odd number ?

#include <iostream.h>
main() Enter value : 11
{ Odd
int x , m;
cout << "Enter value : ";
cin >> x;
m = x % 2;
if ( m == 0 ) Enter value : 920
cout << "Even "; Even
else
cout << "Odd";
}
-------------------------------------------------------------------------------------------------------
Ex: Examine the following program , and write what output?

# include <iostream.h>
main()
{
int n = 3,m = 5 , x=10;
++n; Welcome
m = --m * n++; 21
x = m-- + n; 5
if ( (n+m) < x ) 15
cout << "Welcome";
else
cout << "Hello";
cout << endl;
cout << x <<endl;
cout << n <<endl;
cout << m << endl;
}
-------------------------------------------------------------------------------------------------------

26
Nesting of if…else statement

When a series of decision are involved, we may have to use more than one if…else statement in nested form as

If the condition1 is false, the statement3 will be executed; otherwise it continues to perform the second test.
If the condition2 is true, the statement1 will be executed; otherwise the statement2 will be evaluated and
then the control is transferred to the statement x.
Ex.

#include<iostream.h>
main()
{

int a=5,b=5,c=6; 6 is greater than 5 and 5


if (a == b)
if (b > c)
cout<<a<<" and "<<b <<" are greater than "<<c;
else
cout<<c <<" is greater than "<< a<<" and "<<b;
}

Conditional Expressions

The statement:

if (a < b)
max = b;
else
max = a;

can also be expressed using a conditional expression, which would look like:

max = (a < c) ? b : a;

 While a bit more obscure than the if/else version, a conditional expression can be used in the same
way as any other expression, and is thus a bit more versatile

27
3.3 The if /else if /else statement

Syntax if ( condition )
Statement; || Block of Statement;
else if (condition)
Statement; || Block of Statement;
else Statement; || Block of Statement;

Ex: write a C++ program to enter your test result, then print the equivalent char:

#include<iostream.h> enter the test result 66


int main() D
{
int result;
cout << "enter the test result "; enter the test result 75
cin >> result; C
if (result >=84 ) cout << 'A';
else if (result >=76 ) cout << 'B';
else if (result >=68) cout << 'C'; enter the test result 41
else if (result >=60) cout << 'D'; F
else cout << 'F';
}
-------------------------------------------------------------------------------------------------------
Ex: write a C++ program to enter your test result, then print the equivalent char:

#include<iostream.h>
main () 90-100 A
{ 80-89 B
int mark; 70-79 C
cout << "Enter your mark: "; 60-69 D
cin >> mark; 0-59 F
if (mark >= 90 )
cout << "Your grade is an A" << endl;
else if (mark >= 80 )
cout << "Your grade is a B" << endl;
else if (mark >= 70 )
cout << "Your grade is a C" << endl;
else if (mark >= 60 )
cout << "Your grade is a D" << endl;
else
cout << "Your grade is an F" << endl;
}
-------------------------------------------------------------------------------------------------------
Ex: write a C++ program to read integer number (x) and check if x is positive, negative or zero
#include<iostream.h>
int main() Enter the value of x: 0
{ x is 0
int x;
cout <<”Enter the value of x: “;
Enter the value of x: -50
cin>>x; x is negative
if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative"; Enter the value of x: 3
else x is positive
cout << "x is 0";
}
-------------------------------------------------------------------------------------------------------
Note: If we want more than a single statement to be executed in any case that the condition is true we can
specify a block using braces { }.

28
Ex: write a program to read integer value and shows if the value stored is positive, negative or zero?

#include<iostream.h>
int main() Enter the value of X : -50
{ X= -50
int x; X is negative
cout <<”Enter the value of X : “;
cin>>x;
if (x > 0)
{ Enter the value of X : 3
cout<<”X =”<<x <<endl; X=3
cout << "X is positive"; X is positive
}
else if (x < 0)
{
cout<<”x =”<<x<<endl; Enter the value of X : 0
cout << "X is negative"; X is 0
}
else
cout << "X is 0";
}
-------------------------------------------------------------------------------------------------------
Ex: What is the wrong with the following program?

#include<iostream.h>
int main()
{
int x;
cout <<"Enter the value of X : ";
cin>>x;
if (x > 0)
{
cout<<"X ="<<x <<endl;
cout << "X is positive";
}
cout<<"Goodbye";//There are errors
else if (x < 0)
{
cout<<"x ="<<x<<endl;
cout << "X is negative";
}
cout<<"Hello";//There are errors
else
cout << "X is 0";
}
-------------------------------------------------------------------------------------------------------
Ex: What is the wrong with the following program?

#include<iostream.h>
int main()
{
int x;
cout <<"Enter the value of X : ";
cin>>x;
if (x > 0)
cout<<"X ="<<x <<endl;
cout << "X is positive";
cout<<"Goodbye"; //There are errors
else if (x < 0)
cout<<"x ="<<x<<endl;
cout << "X is negative";
29
cout<<"Hello"; //There are errors
else
cout << "X is 0";
}
-------------------------------------------------------------------------------------------------------
Ex: What is the wrong with the following program?
# include <iostream.h>
main()
{
int m;
cout << "Enter your mark : ";
cin >> m;
if ( m >=50 )
cout<< "Pass"<<endl;
cout<<"Greater than 50"<<endl;
else
cout << "Fail";
}
-------------------------------------------------------------------------------------------------------
Ex: What is the output of the following program if m=50?

# include <iostream.h>
main()
{
int m;
cout << "Enter your mark : ";
cin >> m;
if ( m >=50 )
cout<< "Pass"<<endl;
else
cout << "Fail";
cout<<"less than 50"<<endl;
}
-------------------------------------------------------------------------------------------------------
Note: in C++, zero is false, and any other value is true.
A statement such as:
if (x) // if x is nonzero (true)
x = 0;
can be read as "If x has a nonzero value, set it to 0."
if (x != 0) // if x is nonzero
x = 0;
These two statements also are equivalent:
if (!x) // if x is false (zero)
if (x == 0) // if x is zero
-------------------------------------------------------------------------------------------------------
Write a C++ program to do the following :
1) read three marks .
2) compute the average .
3) find the ranking according to the following cases :
avg < 35 or avg > 100  Error
35<= avg <= 49  Fail
50<= avg <= 67  Accepted
68<= avg <= 75  Good
76<= avg <= 84  Very Good
85<= avg <= 100  Excellent
-------------------------------------------------------------------------------------------------------

30
3.4 The switch statement:
If your program must select from one of many different choices, the "switch" statement will be
more efficient than an "if ..else..." statement .
Syntax
Switch ( expression )
{
case 1 : statement ; || Block of Statement; break;
case 2 : statement ; || Block of Statement; break;
:
default : statement ; \\ it is optional
}
Note: You must use a break statement after each "case" block to keep execution from "falling through" to
the remaining case statements.
-------------------------------------------------------------------------------------------------------
Ex: Write a C++ program to read integer value then examine
If the value = 10 , print "Welcome"
If the value = 20 , print "Ok" 100
Otherwise print "Goodbye" Goodbye
# include <iostream.h>
main() 10
{ Hello
int val ;
cin >> val ;
switch (val) 20
{ Ok
case 10 : cout << "Hello"; break;
case 20 : cout << "Ok"; break;
default : cout << "Goodbye"; //Print Goodbye for other values
}
}
-------------------------------------------------------------------------------------------------------
Ex: Write a C++ program that reads two integer numbers and one arithmetic operators ( +, -, *, /) then
compute and print the result?
#include<iostream.h>
main()
{
int x,y ;
char op; enter the first number 10
cout<<"enter the first number "; enter the second number 6
cin >> x; enter the operation +
cout<<"enter the second number "; 16
cin >> y;
cout<<"enter the operation ";
cin >> op; enter the first number 10
switch (op) enter the second number 20
{ enter the operation *
case '+' : cout<<x+y; break; 200
case '*' : cout<<x*y; break;
case '-' : cout<<x-y; break;
case '/' : cout<<x/y; break;
default : cout<<"Error, please try again " ;
}
}
-------------------------------------------------------------------------------------------------------

31
Ex: Trace the following C++ program and show the results :

# include <iostream.h> 10
int main() Good bye
{
int val ; 5
cin >> val ; Welcome
switch (val) Ok
{ Good bye
case 5 : cout << "Welcome"<<endl;
case 7 : cout << "Ok"<<endl;
default : cout << "Good bye"; 7
} Ok
return 0; Good bye
}
-------------------------------------------------------------------------------------------------------
Ex: Trace the following C++ program and show the results :
#include<iostream.h>
main() Try again
{
int j=1,k=1;
switch (j+k)
{
case 0 : cout << "Welcome"<<endl; break;
case 1 : cout << "Ok"<<endl; break ;
case 2 : // cout << "Good bye"; break;
default: cout<<”Try again “; //Print Try again for other values
}
}
Hint : the statement // cout << "Good bye"; break; is a comment
-------------------------------------------------------------------------------------------------------
Ex: write a program to check if the entered letter is a vowel letter or not :
Hint: the vowel letters are : a,e,o,u,i .

#include<iostream.h>
main()
{ h
char letter; Not Vowels
cin>> letter ;
switch (letter)
{ o
case 'a': Vowels
case 'e':
case 'o':
case 'u':
case 'i': cout<<"Vowels"; break; //The case code for a,e,o,u,i
default :cout<<"Not Vowels \n"; //Print Not Vowels for other values
}
}
-------------------------------------------------------------------------------------------------------
Hint: the last program is for small letters only !!!!

To use this program for small letters and capital letters there are two ways :
- write a new program contain all of them (small and capital letters ) .
- add the statement letter = tolower(letter) before switch statement and add the header file #include
<ctype.h> .
-------------------------------------------------------------------------------------------------------
32
Ex: Trace the following C++ program and show the results :

#include<iostream.h>
main()
{ 5 is less than 8
int a=5,b=8;
switch (a<b)
{
case 0 : cout << a<<" is greater than"<<b<<endl; break;
case 1 : cout << a<<" is less than "<<b<<endl; break ;
}
}

Hint : This example about logical expression ( true 1 and false  0)


Ex: Trace the following C++ program and show the results :

#include<iostream.h>
main() 10 is greater than 8
{
int a=10,b=8;
switch (a==b)
{
case 0 : cout << a<<" is greater than"<<b<<endl; break;
case 1 : cout << a<<" is less than "<<b<<endl; break ;
}
}
-------------------------------------------------------------------------------------------------------
Ex: Trace the following C++ program and show the output :

# include <iostream.h> 10
main() Hello
{ C++
int val ;
cin >> val ;
switch (val) 20
Ok
{
case 10 : cout << "Hello"<<endl;
cout<<"C++"<<endl; break;
cout<<"Ali"; //This instruction is ignored because it occurred after break
case 20 : cout << "Ok"; break;
default : cout << "Goodbye";
}
}
-------------------------------------------------------------------------------------------------------
Ex: Trace the following C++ program and show the results then find the error:

#include<iostream.h> 8
8 is odd
main()
{
int num; 10
cin>>num; 10 is even and is dividable by 5
if (num%2==0)
if (num %5==0)
cout<<num <<” is even and is dividable by 5 “;
else
cout<<num<<” is odd”;
}

Hint: else follow the first if matched up from the bottom ( without using { } ).
-------------------------------------------------------------------------------------------------------
33
Ex: Trace the following C++ program and show the results :
#include<iostream.h> 8
main()
{
int num;
cin>>num; 10
10 is even and is dividable by 5
if (num%2==0)
{
if (num %5==0)
cout<<num <<” is even and is dividable by 5 “;
}
else
cout<<num<<” is odd”;
}
-------------------------------------------------------------------------------------------------------
Ex: Write a C++ program to find the Absolute value of number ?

# include <iostream.h>
void main ()
{
int a,y;
cout<<"enter number ";
cin>>a; enter number -3
if (a>=0) |-3|=3
cout<<a;
if (a<0)
y=-1*a;
cout<<"|"<<a<<"|="<<y;
}
-------------------------------------------------------------------------------------------------------
Ex: Trace the following C++ program and show the results :

#include <iostream.h>
void main()
{
int x=10, y=20,z=30;
if (x<y) 21
if (z>y)
cout <<++y;
else
cout << x++;
else
cout<<y-x;
}
-------------------------------------------------------------------------------------------------------
Ex: Trace the following C++ program and show the results :

#include <iostream.h>
void main()
{
int x=10, y=20,z=30;
if (x<y) x=10 y-x=10
if (z<y)
cout <<"y="<<y<<" ";
else
cout <<"x="<< x<<" ";

cout<<"y-x="<<y-x;
}
-------------------------------------------------------------------------------------------------------
34
Ex: Write a program to display “free” when your age is <7 or >=75 otherwise "you have to pay".
#include <iostream.h>
main() Age<7 free
{ Age>=75 free
int age; 7<=Age<75 You have to pay
cout << "Please,enter your age: ";
cin >> age; Please,enter your age:80
if (age > 7) free
if (age >= 75)
cout << "free"; Please,enter your age:22
else You have to pay
cout << "You have to pay";
else Please,enter your age:4
cout << "free"; free
}
-------------------------------------------------------------------------------------------------------
Ex: What is the output of following program if mark='C'?

#include <iostream.h>

main()
{
char mark;
cout << "Please,enter your mark: ";
cin >> mark;
switch (mark)
{
case 'A':
cout << "Your mark must be between 90 - 100"<< endl;
break;
case 'B':
cout << "Your mark must be between 80 - 89" << endl;
break;
case 'C':
cout << "Your mark must be between 70 - 79" << endl;
break;
case 'D':
cout << "Your mark must be between 60 - 69" << endl;
break;
default:
cout << "Your mark must be below 60" << endl;
}

}
-------------------------------------------------------------------------------------------------------
Ex: Trace the following C++ program and show the results :

example example equivalent


#include<iostream.h> #include<iostream.h>
int main() int main()
{ {
4 4
int num; 4 !=0 int num;
4 !=0
cin>>num cin>>num
if (num) if (num!=0)
cout<<num<<” !=0 ”; cout<<num<<” !=0 ”;
else else
cout<<num<<” = 0 ”; cout<<num<<” = 0 ”;
} }
-------------------------------------------------------------------------------------------------------

35
Ex: Convert from switch to if else equivalent

switch statement example if-else equivalent


switch (x) {
if (x == 10) {
case 10:
cout << "x is 10";
cout << "x is 10";
}
break;
else if (x == 20) {
case 20:
cout << "x is 20";
cout << "x is 20";
}
break;
else {
default:
cout << "value of x unknown";
cout << "value of x unknown";
}
}

Ex: Trace the following C++ programs and show the results

example Example
#include <iostream.h>
#include <iostream.h>
main()
main()
{
{
int x=4;
int input;
if (4==x) {
cout << "Enter an integer: ";
cout << "The number is 4." <<
cin >> input;
endl;}
if (input > 0) {
else {
cout << "You have entered a positive number."<<endl; }
cout << "The number is not 4."
else if (input < 0 ) {
<< endl; }
cout << "You have entered a negative number."<<endl; }
else {cout < "This else
else { cout << "You have entered 0." << endl; }
statement causes an error." <<
}
endl; } }

HW: Convert from switch to if else equivalent


switch statement example if-else equivalent
switch (x) {
case 1:
case 3:
if(x==1||x==3||x==5)
case 5:
cout << "x is 1, 3 or 5";
cout << "x is 1, 3 or 5";
else
break;
cout << "x is not 1, 3 nor 5";
default:
cout << "x is not 1, 3 nor 5";
}

HW: Convert from switch to if else equivalent


switch statement example if-else equivalent
# include <iostream.h>
main()
{
int val ;
cin >> val ;
switch (val)
{
case 5 : cout << "Welcome";
case 7 : cout << "Ok"; break;
default : cout << "Good bye";
}
}

36
Chapter 4 : Iteration statements ( Loops ) ( while , do / while , for )

4.1 The while statement

Syntax

while (condition)
{
Statement; || block of statements
}
-------------------------------------------------------------------------------------------------------
Ex : To print the numbers from ( 1 - 10 )
1
# include <iostream.h> 2
main() 3
{ 4
int i =1 ; 5
while ( i <=10) 6
{ 7
cout<<i<<endl; 8
i++; 9
} 10
}

Hint: The last value of i is i=11


-------------------------------------------------------------------------------------------------------
Ex : To print the numbers (2 , 4 , 8 , 16 , 32 , 64 )

# include <iostream.h>
main()
{
int x =2 ;
2 4 8 16 32 64
while ( x <=100)
{
cout<<x<<” ”;
x = x * 2 ;
}
}
-------------------------------------------------------------------------------------------------------
Ex :Write a program to print number from 10 – 1
10
# include <iostream.h> 9
main() 8
{ 7
int i =10 ; 6
while ( i >=1) 5
{ 4
cout<<i<<endl; 3
--i; 2
} 1
}
-------------------------------------------------------------------------------------------------------

37
Ex :Write a program to print the even number from 10 – 0

# include <iostream.h>
main()
{
int i=10;
while(i>=0)
10 8 6 4 2 0
{
cout<<i<<” “;
i=i-2;
}
}
-------------------------------------------------------------------------------------------------------
4.2 The do / while statement

Syntax

Do
{
Statements;
}
while (condition) ;
-------------------------------------------------------------------------------------------------------
Ex : Write a program to print numbers from ( 1 – 10 )
1
# include <iostream.h> 2
int main() 3
{ 4
int i =1; 5
do 6
{ 7
cout << i <<endl; 8
i++; 9
} 10
while ( i <=10 );
}
-------------------------------------------------------------------------------------------------------
Ex :Write a program to print number from 10 – 1
10
# include <iostream.h> 9
int main() 8
{ 7
int i =10 ; 6
do 5
{ 4
cout<<i<<endl; 3
--i; 2
} 1
while ( i >=1);
}
-------------------------------------------------------------------------------------------------------

38
What is the difference between

int x=0; int x=0;

while(x!=0) do
{ {
cout <<"hello"; cout <<"hello";
} }
while (x!=0);

-------------------------------------------------------------------------------------------------------
Ex: Find the summation of the entered values until read zero :

#include<iostream.h>
main()
{ Enter value :10
int x,sum=0; Enter value :12
do Enter value :44
{ Enter value :-12
cout <<"Enter value :"; Enter value :-1
cin >> x; Enter value :1
sum+=x; Enter value :0
} The total is :54
while (x !=0);
cout<<"The total is :"<<sum;
}
-------------------------------------------------------------------------------------------------------
4.3 The for statement

Syntax

for ( initialization ; loop Continuation Condition ; increment )


statement;

Ex : write a C++ program to print the following


Hello
#include<iostream.h> Hello
main() Hello
{ Hello
for (int i = 1 ; i <= 5 ; i+=1) Hello
cout<<"Hello\n";
}
-------------------------------------------------------------------------------------------------------
Ex : write a C++ program to print the following
1 2 3 4 5 6 7 8 9 10
#include<iostream.h>
main()
{
for( int x=1; x<=10;++x)
cout << x<<” “ ;
}

-------------------------------------------------------------------------------------------------------
Ex : write a C++ program to print the even numbers from ( 3 to 13 ) :

39
#include<iostream.h>
main()
{
for (int i =4 ; i <=13 ; i +=2 )
cout << i<<endl ;
}
-------------------------------------------------------------------------------------------------------
Ex : write a C++ program to print odd numbers from ( 21 to 5 ) :

#include<iostream.h>
main()
{
for (int i =21; i >=5 ; i -=2)
cout << i <<endl;
}
-------------------------------------------------------------------------------------------------------
HW : Write a C++ programs to print the following :

7 , 14 , 21 , 28 , 35 , 42 , 49 50 , 45 , 40 , 35 , 30 , 25 , 20

-7 -5 -3 -1 1 3 5 7 9 11 13 15 A
B
C
D
E
0 ,1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 F

2*1=2 "X"Y"Z"
2*2=4 ===========
2*3=6 " 1 " 5 " -8 "
2*4=8 " 2 " 4 " -6 "
2 * 5 = 10 " 3 " 3 " -4 "
2 * 6 = 12 " 4 " 2 " -2 "
2 * 7 = 14 "5 "1 " 0"
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

-------------------------------------------------------------------------------------------------------
Ex: What is the output
m=1 n=8
for(m=1, n=8 ; m < n ; m++ , n--) m=2 n=7
cout<< "m=" << m << "n=" << n << endl ; m=3 n=6
m=4 n=5

-------------------------------------------------------------------------------------------------------

40
5 5
Ex: write a C++ program to compute 2 to power 5 ( 2 ) where 2 =2*2*2*2*2

#include<iostream.h>
main()
{
int pow,i;
pow=1; 2 power 5 = 32
for( i=1;i<=5;i++)
{
pow=pow*2;
}
cout<<2<<" power "<<5<<" = "<<pow;
}
-------------------------------------------------------------------------------------------------------
Ex: write a C++ program to compute X to power Y ( X^y)  eg. 2^2=4 ; 3^3=27

#include<iostream.h>
main()
{
int pow,i,x,y;
Enter two numbers
cout<<"Enter two numbers\n";
pow=1; 2
5
cin>>x>>y;
2 power 5 = 32
for( i=1;i<=y;i++)
{
pow=pow*x;
}
cout<<x<<" power "<<y<<" = "<<pow;
}
-------------------------------------------------------------------------------------------------------
Ex: write a C++ program to calculate factorial of 5 ( 5!) where 5!=5*4*3*2*1

#include<iostream.h>
main()
{ 5 ! = 120
int i,fac=1;
for(i=1;i<=5;i++)
fac=fac*i;
cout<<5<<" ! = "<<fac;
}
-------------------------------------------------------------------------------------------------------
Ex: write a C++ program to calculate factorial of n ( n!)  eg. 4!=24 ; 3!=6

#include<iostream.h>
main()
{ 4
int i,n,fac=1; 4 ! = 24
cin>>n;
for(i=1;i<=n;i++)
fac=fac*i;
cout<<n<<" ! = "<<fac;
}
-------------------------------------------------------------------------------------------------------

41
Ex: write a C++ program to find the average of class consist of 5 students

#include<iostream.h>
main()
{
int counter , grade ;
float sum,average ; Enter grade : 50
sum =0.0; Enter grade : 60
counter=1; Enter grade : 70
while (counter<=5) Enter grade : 80
{ Enter grade : 90
cout<<”Enter grade : “; average =70
cin>>grade ;
sum = sum +grade;
counter++;
}
average= sum /5;
cout<<” average = “<<average ;
}
-------------------------------------------------------------------------------------------------------
Set width : Sets the number of characters to be used as the field width for the next insertion operation.
Setw( int )  #include < iomanip.h >

Ex: Welcome1234567to Jordan


Welcome to Jordan
cout <<"Welcome1234567toJordan"<<endl ;
cout <<"Welcome"<<setw(5)<<"to"<<"Jordan";

Note: The number of spaces between Welcome and to is 3 (not 5) why?


-------------------------------------------------------------------------------------------------------
Ex : Trace the following C++ programs and show the results

#include<iostream.h>
#include <iomanip.h>
main()
{
int x;
for(x=4;x<=10;x+=1)
cout <<"Hello"<<setw(x)<<"C++\n";
}

-------------------------------------------------------------------------------------------------------
Ex: Trace the following C++ programs and show the results

#include<iostream.h>
#include <iomanip.h>
main()
{
int x;
for(x=15;x>=4;x-=1)
cout <<setw(x)<<"C++\n";

for(x=4;x<=15;x+=1)
cout <<setw(x)<<"C++\n";
}
-------------------------------------------------------------------------------------------------------

42
Power function : Pow(x,y)  #include<math.h>
Ex :
#include<iostream.h>
#include<math.h>
main()
{
int a,b;
cout <<"Enter the number :";
cin >> a;
cout <<"Enter the Power :";
cin >> b;
cout <<"The value of a^b is :"<<pow(a,b);
}
-------------------------------------------------------------------------------------------------------
Square root function : Sqrt(x)  <math.h>

Ex :
int x = 16 ;
cout << sqrt ( x ) ; print   4
cout << sqrt ( sqrt (81)) ; 3
-------------------------------------------------------------------------------------------------------
Ex : Trace the following code :
#include<iostream.h>
#include<math.h>
main()
{
int i=2,j=8,k;
k= i-- + ++j;
while(k >7)
{ I = 5 j = 24 k = 7
j= k + pow(2,i);
i+=1;
k-=1;
}
cout <<" I = " << I << " j = " << j << " k = " << k;
}
-------------------------------------------------------------------------------------------------------
Ex : Trace the following code :

# include <iostream.h>
int main ()
{ 3
int i,x,y; 7
for(i=1;i<=10;i++) 11
if(i%2 != 0) 15
{ 19
y=i+1 ;
x=y+i;
cout<<x<<endl;
}
}
-------------------------------------------------------------------------------------------------------

43
4.4 The Nested Loop (for):

Ex :
Print this : 1 2 3 4 5
1 2 3 4 5
# include < iostream.h > 1 2 3 4 5
# include < iomanip.h >
main()
{
int i,j;
for(i=1;i<=3;i+=1)
{
for(j=1;j<=5;j+=1)
{
cout<< setw(5)<<j;
}
cout << endl;
}
}
-------------------------------------------------------------------------------------------------------
Ex : Print this :
1 2 3 4
2 3 4
# include <iostream.h> 3 4
int main() 4
{
for(int x=1 ; x<=4; x+=1)
{
for(int j=x ; j<=4 ; j++)
{
cout<< j<<” “;
}
cout << endl;
}
}
-------------------------------------------------------------------------------------------------------
Ex : Print this :
1
1 2
# include <iostream.h> 1 2 3
int main() 1 2 3 4
{
for(int x=1;x<=4;x+=1)
{
for(int j=1 ; j<=x ; j++)
{
cout<< j<<” “;
}
cout << endl;
}
}
-------------------------------------------------------------------------------------------------------

44
Special Cases

1- for( ; ; ) cout<<” hi “;  infinite loop

2- for( int c=0; c<100 ; ) cout<<c;  infinite loop

3- for (int i=0 ; i<5 ; i++) ;  Null statement

-------------------------------------------------------------------------------------------------------
Ex : Print this :
* * * * *
# include < iostream.h > * * * * *
# include < iomanip.h > * * * * *
main() * * * * *
{
int i , j;
for(i=1;i<=4;i+=1)
{
for(j=1;j<=5;j+=1)
{
cout<< setw(5)<< '*' ;
}
cout << endl;
}
}
Ex : write a C++ program to print the following :

5 4 3 2 1 2 4 6 8 1 2 3 4 1
5 4 3 2 1 2 4 6 8 1 2 3 4 2
5 4 3 2 1 2 4 6 8 1 2 3 4 3
2 4 6 8 1 2 3 4 4

1 * * * * * * 1 2 3 4 5
2 * * * * * * 6 7 8 9 10
3 * * * * * * 11 12 13 14 15
4 * * * * * * 16 17 18 19 20
5 * * * * * * 21 22 23 24 25

5 5 5 5 5
1 *
4 4 4 4
2 2 *
3 3 3
3 3 3 *
2 2
4 4 4 4 1 *
5 5 5 5 5 *
*
* *
* * *
5 *
4 4 * * *
3 3 3 * * * *
2 2 2 2 * * * * *
1 1 1 1 1

45
4.5 Jump statements ( the break and the continue )

The break Statement

The break statement can be used in a switch statement and in any of the loops. It
causes program execution to pass to the next statement following the switch or the
loop.

syntax of break statement

Note : The break statement skips rest of the loop and goes out of the loop.

The continue statement

The continue statement is used in loops and causes a program to skip the rest of
the body of the loop.

syntax of continue statement

Note : The continue statement skips rest of the loop body and starts a new iteration.

46
break and continue

Ex :
#include<iostream.h>
main()
{
for (int i=1; i <=20 ; i++ )
{
if(i==6)
break; 1 2 3 4 5
cout<<i;
}
}
-------------------------------------------------------------------------------------------------------
Ex :
#include<iostream.h>
main()
{
for (int i=10;i>=1;i--)
{
if(i==4) 10 9 8 7 6 5 3 2 1
continue;
cout<<i;
}
}
-------------------------------------------------------------------------------------------------------
Ex :
for (int i=1;i<=100;i++)
{
if (i== 8)
break;
if (i== 3 || i==5) 12467
continue;
cout<<i;
}
-------------------------------------------------------------------------------------------------------
Ex :
for (int i=1;i<=10;i++)
{
if (i> 3)
break; 123
if (i== 7)
continue;
cout<<i;
}
-------------------------------------------------------------------------------------------------------
Ex :
int value =0;
for (int i=0 ; i< 10;i++ )
{
if (i==4 || i==6)
continue;
value +=2; 16
}
cout<<value;
-------------------------------------------------------------------------------------------------------

47
Ex :
main()
{
int value =0;
for (int i=0 ; i< 10;i++ ) 6
{
if (i==2 || i==5)
break;
value +=3;
}
cout<<value;
}
-------------------------------------------------------------------------------------------------------
Ex :
int n; Enter the number :5
do The number is: 5
{ Enter the number :20
cout<<" Enter the number :"; Skip the value
cin>>n; Enter the number :-3
if (n < 0)
{ break; }
if (n >10)
{ Enter the number :4
cout<<"Skip the value\n"; The number is: 4
continue; Enter the number :30
} Skip the value
cout<<"The number is: "<< n<<endl Enter the number :0
}
while (n!= 0);
-------------------------------------------------------------------------------------------------------
Sequence , Selection and Repetition Structures

48
Scoping :

#include<iostream.h>
int x = 4;
main()
{ 65
int x = 5;
{
int x = 6;
cout << x;
}
cout <<x;
}
-------------------------------------------------------------------------------------------------------
#include<iostream.h>
int x = 14; 14
main() 5
{ 5
cout <<x<<endl;
int x = 5;
{
cout << x<<endl;
int x=6;
}
cout <<x;
}
-------------------------------------------------------------------------------------------------------
Extra questions

- Find the value of sum


2 3 n
sum= (x/1!) + (x /2!) +(x /3!) +…+(x /n!)

#include<iostream.h>
#include<math.h>
main()
{
int i,j,fact,sum=0,x,n;
cin>>n;
cin>>x;

fact=1;
for(j=1;j<=i;j++)
{
fact=fact*j;
sum=sum+(pow(x,i)/fact);
}
cout<<sum;
}
-------------------------------------------------------------------------------------------------------

49
Find the value of Sum:
Sum=1!+2!+3!+4!+…+n!

#include<iostream.h>
#include<math.h>
main()
{
int i,j,fact,sum=0,n;
cin>>n;
fact=1;
for(j=1;j<=n;j++)
{
fact=fact*j;
sum=sum+fact;
}
cout<<sum;
}
-------------------------------------------------------------------------------------------------------

H.W

- Write a C++ program to read 5 integer marks, if pass in all marks (>=50) print “pass” otherwise print “fail”.

- Write a C++ program to display the first 20 even numbers.

- Write a C++ program to find the average of the odd numbers,between 200 and 100.

- Enter number and check if the number is Prime or not ?

50
Chapter 5 : Arrays ( One Dimensional arrays , multidimensional arrays)

5.1 One Dimensional arrays

An array is a collection of memory locations for a specific type of data and have the same name . Think of
an array as a "box" drawn in memory with a series of subdivisions, called elements, to store data. The box
below could represent an array of 5 integers.
1 0 5 23 7
While this array contains only 5 elements, arrays are traditionally used to handle large amounts of data. It is
important to remember that all of the elements in an array must contain the same name and type of data.

Declaring arrays
Syntax :
Data _type Array_Name [Array_size] ;

declares an array named X that contains 5 integers. When the compiler encounters this declaration, it
immediately sets aside enough memory to hold all 5 elements.  int X[5];

X
1 100 15 23 7
X[0] X[1] X[2] X[3] X[4]

- A program can access each of the array elements (the individual cells) by referring to the name of
the array followed by the subscript which denotes the cell.

Format : Array_Name [index] ;

For example, the third cell is denoted X[2] .

- Declaring multiple arrays of same type use comma separated list


Ex: int x[20] , A[10] , Z[5];

- The first element at position 0 (not 1)


C[0] , C[1] , C[2] , … , C[n-1]
- The N th element at position n-1

- We can perform operations inside subscript :


C[2+1] same as C[3]
- Array size can be specified with constant variable (const)
const int size =20;
int Array[size]; // the size of array is 20
Note:
- constants can't be changed
- constants must be initialized when declared

Note:
array size can not be specified with variable int size =20; int Array[size];  Error
-------------------------------------------------------------------------------------------------------
51
5.2 Initializing arrays

Arrays can be initialized by placing a list of values, separated by commas, within braces.
1) int C[5] = {10,20,30,40,50}; this mean C[0]=10, C[1]=20, C[2]=30, C[3]=40, C[4]=50

Individual elements of an array are accessed using subscripts (or indices) such as C [0], C [1], C [2], C[3], and
C [4]. (Note the subscripts from 0 to 4.)  Array subscripts start with the number 0 (not 1).

2) if array size omitted ,initializers determine size


int C[]={10,20,30,40,50};  the array size =5

3) read elements of array from keyboard

int C[6];
cin>>C[0]>>C[1]>>C[2]>>C[3]>>C[4]>>C[5];
Using a for loop and cin to initialize an array

int C[6],i;
for (i=0;i<6;i++)
cin>>C[i]; // looping process fills elements
-------------------------------------------------------------------------------------------------------

Addresses of Arrays

int mark[100];

The elements of this array can be referred to in a program as mark[0] . . . mark[99].


When the program is compiled, the compiler does not save the addresses of all of the elements, but only
saves the address of the first element, mark [0]. When the program needs to access any element, such as
mark [5], it calculates the address by adding units to the address of mark [0].The address of mark [0] can
be obtained by using the & ("address of") operator. In C++, the name of the array, mark, without a
subscript, is the same as & mark [0].  cout<< mark; This will print the address of first element of mark.

-------------------------------------------------------------------------------------------------------

52
Find the Summation of two arrays

#include <iostream.h>
main ()
{
const int size =3;
int r1[size]={1,2,3};
int r2[size]={4,5,6};
int r3[size],i; 5 7 9
for (i=0;i<size;i++)
r3[i]=r1[i]+r2[i];
for (i=0;i< size;i++)
cout<<r3[i]<<" ";
}
-------------------------------------------------------------------------------------------------------
find the maximum value in an array of integers ?

#include <iostream.h>
main () The maximum number is 20
{
const int size =8;
int max,i;
int a[size] = {13,7,6,15,20,14,2,17};
max=a[0]; // start with max = first
for (i=0;i<size;i++)
if (a[i]>max)
max=a[i];
cout<<"The maximum number is "<<max ; // Print the highest value in array
}
-------------------------------------------------------------------------------------------------------
find the position of the minimum value in an array of integers

#include <iostream.h>
main ()
{
const int size =8;
int i,pos,min;
int a[size] = {13,7,6,15,20,14,2,17};
min=a[0]; min=2 the position =7

for (i=0;i<size;i++)
{
if (a[i]<min)
{
min=a[i];
pos =i;
} //if
} // for
cout<<"min=" << min<<" the position = " << pos+1;
}
-------------------------------------------------------------------------------------------------------

53
Swapping elements between two arrays

In order to swap two values, you must use a third variable, (a "temporary holding variable"), to temporarily
hold the value you do not want to lose:

#include<iostream.h>
main()
{
const int size =4;
int a[size]={1,2,3,4};
int b[size]={5,6,7,8};
5 6 7 8
int i;
1 2 3 4
int temp;
for (i=0;i<size;i++)
{ // swap elements
temp=a[i]; // holding variable
a[i]=b[i];
b[i]=temp;
} /*This process successfully exchanges, "swaps", the values of the two
variables(without the loss of any values).*/
for (i=0;i<size;i++)
{ cout<<a[i]<<" "; }

cout<<endl;
for (i=0;i<size;i++)
{ cout<<b[i]<<" "; }
}
-------------------------------------------------------------------------------------------------------
Sorting array (Ascending)

arrange the elements in an array in numerical order from lowest to highest values (ascending order)

// Sorting Ascending
#include<iostream.h>
main()
{

int a[8]={13,7,5,14,12,17,22,4};
int i,j,temp;

for (i=0;i<8;i++) 4 5 7 12 13 14 17 22
{
for (j=0;j<8;j++)
{

if (a[j]>a[i]) // descending order simply changes to <


{
temp=a[i]; // swap elements
a[i]=a[j];
a[j]=temp;
}
}
}

for (i=0;i<8;i++)
cout<<a[i]<<" " ;
}
-------------------------------------------------------------------------------------------------------

54
Searching array

#include <iostream.h>
main( )
{
int mark[10] = { 100,90,65,45,87,52,99,97,87,98} ,f=0, index ;
int search;
cout << "Please enter the mark you want it\t" << endl;
cin >> search;
for ( index=0;index<10;index++) Please enter the mark you want it
{ 50
if (mark[index] == search) No Body has this mark
{
cout << "The number of student is:" << index+1<<endl;
f=1;
}
Please enter the mark you want it
}
87
if (f==0)
The number of student is: 5
cout << "No Body has this mark" ;
The number of student is: 9
return 0;
}

Enter 3 marks for 5 students then compute the average and grade for each student and print them .

#include<iostream.h>
main()
{
int mark1,mark2,mark3;
int sum;
float avg;
char grade;
for(int i=0;i<5;i++)
{
cout<<"Enter 3 marks for student number "<<i+1<<endl;
cin>>mark1>>mark2>>mark3;
sum=mark1+mark2+mark3;
avg=sum/3.0;
if (avg>=90) grade='A';
else if(avg>=80) grade='B';
else if(avg>=70) grade='C';
else if(avg>=60) grade='D';
else grade='F';
cout<<"Average = "<< avg<<endl<<"grade = "<< " " << grade<<endl;
}
}
-------------------------------------------------------------------------------------------------------
Note
To set every element to same value when array declared enter the value between { } Ex. int x[10]={0};

H.W

Find the highest (maximum) and lowest (minimum) grades in an array of 30 integer grades.
Print the array and print the highest and lowest grades

55
5.3 Multi-Dimensional Arrays (Matrices)

Up until now, all of our arrays have been one-dimensional arrays. These arrays have had "length", but the
"width" (or height) remained as only one cell.
Two-dimensional arrays, called matrix. A matrix resembles a table with rows and columns.
The array which is used to represent and store data in a tabular form is called as ‘two dimensional array.
Such type of array specially used to represent data in a matrix form.
The elements of a matrix must be of the same name and data type.

Declaring two dimensional array

Syntax :

Data _type Array_Name [row] [col] ;


Ex: int A[3][4]; 4 Columns
0 1 2 3
0 A00 A01 A02 A03
Aij = 3 Rows 1 A10 A11 A12 A13
2 A20 A21 A22 A23

- declare a matrix of floats with 3 rows and 4 columns  float X[3][4];


- Declaring multiple arrays of same type use comma separated list
Ex: int x[20][5] , A[10][3] , Z[5][5];

Accessing two dimensional array elements

- To refer to element : Specify array name and position number (row and column)
Format : Array_Name [row][col] ;
Ex: C[3][2];
- The first element at row 0 and column 0.
C[0][0] , C[0][1] , C[0][2] , … , C[n-1][m-1].
- the last element at position n-1,m-1

- You can perform operations inside subscript :


C[2+1][0] same as C[3][0]
- Array size can be specified with constant variable (const)
const int size =20;
C[size][size];  C[20][20];

- Assignment :
int X[5][4];
X[0][1] = 5;
cout<<X[0][1] ;
-------------------------------------------------------------------------------------------------------

56
5.4 Initializing Two Dimensional Array

1) int C[3][4] = { { 10,20,30,40},{50,60,70,80},{90,100,110,120 } };

 this mean C[0][0]=10, C[0][1]=20, C[0][2]=30, C[0][3]=40, C[1][0]=50, C[1][1]=60,


C[1][2]=70, C[1][3]=80, C[2][0]=90, C[2][1]=100, C[2][2]=110, C[2][3]=120. Put each row in group
{ }

2) int C[3][4] = { 10,20,30,40,50,60,70,80,90,100,110,120 } ;

 this mean C[0][0]=10, C[0][1]=20, C[0][2]=30, C[0][3]=40, C[1][0]=50, C[1][1]=60,


C[1][2]=70, C[1][3]=80, C[2][0]=90, C[2][1]=100, C[2][2]=110, C[2][3]=120. All elements in the
same groub { } and end with ;

0 1 2 3
Cij = 0 10 20 30 40
1 50 60 70 80
2 90 100 110 120

3) read the elements of two dimensional array from keyboard

As with one-dimensional arrays, matrices can be filled one element at a time after declaration, by
assignment or by user input. Here is an example with user input. (Notice the nested loops.)

int C[3][4]; // declaring the 2-D array


for ( row=0; row<3; row++) // loop for establishing the rows
for (col=0 ; col<4 ; col++) // loop for the columns
cin >> C[row][col] ; // user input elements of 2-D array

Printing Two dimensional Arrays ,Nested loops are also used to print a matrix:
for ( row=0; row<3; row++) // loop for establishing the rows
for (col=0 ; col<4 ; col++) // loop for the columns
cout<< C[row][col] ; //Printing elements of 2-D array

-------------------------------------------------------------------------------------------------------

Aij =
0 1 2 3
- To print 70 : 0 10 20 30 40
cout<<a[1][2]; 1 50 60 70 80
2 90 100 110 120
- To insert new value :
cin>>a[2][0];
-------------------------------------------------------------------------------------------------------

57
- read the elements of two dimensional array from keyboard.
0 1 2 3
0 5 7 2 13
1 17 63 15 77
2 11 22 33 45
int A[3][4]; // declaring the 2-D array
for ( int row=0; row<3; row++) // loop for establishing the rows
for (int col=0 ; col<4 ; col++) // loop for the columns
cin >> A[row][col] ; // user input elements of 2-D array
-------------------------------------------------------------------------------------------------------
- Print the elements of two dimensional array.

for ( int row=0; row<3; row++) // loop for establishing the rows
{
for (int col=0 ; col<4 ; col++) // loop for the columns
cout << A[row][col] ; //Printing elements of 2-D array
cout<<endl;
}

- To insert elements of two dimensional array

int a[3][4]={{5,7,2, 13},{17,63,15,77},{11,22,33,45}};

-------------------------------------------------------------------------------------------------------

Find the sum of the elements in the matrix "table"

58
Find the sum of the elements of each row in 2 dimensional array (3X4)

#include<iostream.h>
main()
{
int a[3][4]={{5,7,2, 13},{17,63,15,77},{11,22,33,45}}; // Fill the array
int sumr=0;
for (int i=0;i<3;i++)
{
for (int j=0;j<4;j++)
sumr=sumr+a[i][j]; // Find the sum of the elements of row
cout<<"sum["<<i<<"]="<<sumr; // Print the sum of each row
cout<<endl;
sumr=0;
}
}
-------------------------------------------------------------------------------------------------------
Find The sum of elements for each column in 2 dimensional array (3X4)

#include<iostream.h>
main()
{

int a[3][4]={{5,7,2, 13},{17,63,15,77},{11,22,33,45}};


int sumc=0;
for (int i=0;i<4;i++)
{
for (int j=0;j<3;j++)
{
sumc=sumc+a[j][i];
}
cout<<"sum["<<i<<"]="<<sumc;
cout<<endl;
sumc=0;
}
}
-------------------------------------------------------------------------------------------------------
Find The sum of Diagonal elements in 2 dimensional array (4X4)

0 1 2 3
0 5 7 2 13
1 17 63 15 77
2 11 22 33 45
3 10 20 30 40

#include<iostream.h>
main()
{
int a[4][4]={{5,7,2, 13},{17,63,15,77},{11,22,33,45}, { 10,20,30,40} };
int sum=0,i,j;
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if (i== j)
sum=sum+a[i][j];
}
cout<<"sum of diagonal elements ="<<sum;
}
59
-------------------------------------------------------------------------------------------------------
Find the Sum of the elements below the diagonal (4X4)

0 1 2 3
0 5 7 2 13
1 17 63 15 77
2 11 22 33 45
3 10 20 30 40

#include<iostream.h>
main()
{
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{ 10,20,30,40} };
int sum=0,i,j;
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if (i> j)
sum=sum+a[i][j];
}
cout<<"sum of the elements below the diagonal ="<<sum;
}
-------------------------------------------------------------------------------------------------------
Find the Sum of the elements above the diagonal (4X4)

0 1 2 3
0 5 7 2 13
1 17 63 15 77
2 11 22 33 45
3 10 20 30 40
#include<iostream.h>
main()
{
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{ 10,20,30,40} };
int sum=0,i,j;
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if (i< j)
sum=sum+a[i][j];
}
cout<<"sum of the elements above the diagonal ="<<sum;
}
-------------------------------------------------------------------------------------------------------

60
Find the The maximum number of two dimensional array (4X4)

#include<iostream.h>
main()
{
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{ 10,20,30,40} };
int max,i,j;
max=a[0][0];
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if (max< a[i][j])
max=a[i][j];
}
cout<<"Max ="<<max;
}
-------------------------------------------------------------------------------------------------------
Change the row to column and column to row ( Transport )

0 1 2 3
0 5 7 2 13
Aij = 1 17 63 15 77
2 11 22 33 45
3 10 20 30 40
Bij =
0 1 2 3
0 5 17 11 10
1 7 63 22 20
2 2 15 33 30
3 13 77 45 40
#include<iostream.h>
main()
{
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{ 10,20,30,40} };
int b[4][4];
int max,i,j;
for (i=0;i<4;i++)
for (j=0;j<4;j++)
b[i][j] = a[j][i];

for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
cout<< b[i][j]<<" " ;
cout<<endl;
}
}
-------------------------------------------------------------------------------------------------------
H.W

- Find the Maximum number in two dimensional array

61
Summation of two arrays

#include<iostream.h>
main()
{
int i,j;
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{10,20,30,40} };
int b[4][4]={{5,17,11,10},{7,63,22,20},{2,15,33,30},{13,77,45,40} };
int c[4][4];
for (i=0;i<4;i++)
for (j=0;j<4;j++)
c[i][j] = a[i][j]+b[i][j] ;
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
cout<< c[i][j]<<" " ;
cout<<endl;
}
}
--------------------------------------------------------------------------------------------------------
Print the elements of inverse diagonal 0 1 2 3
0 5 7 2 13
#include<iostream.h> 1 15 7717 63
main() 2
22 33 45 11
{ 3
int i,j; 10 20 30 40
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{10,20,30,40} };
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if((i+j)==3)
cout<< a[i][j]<<" " ;
cout<<endl;
}
}
-------------------------------------------------------------------------------------------------------
Find the summation of inverse diagonal elements

#include<iostream.h>
main()
{
int i,j,sum=0;
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{10,20,30,40} };
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if((i+j)==3)
sum=sum+a[i][j];
}
cout<<"sum="<<sum; }
-------------------------------------------------------------------------------------------------------

62
Find the summation of the elements above the inverse diagonal

0 1 2 3
0 5 7 2 13
1 17 63 15 77
#include<iostream.h> 2 11 22 33 45
main() 3
10 20 30 40
{
int i,j,sum=0;
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{10,20,30,40} };

for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if((i+j)<3)
sum=sum+a[i][j];
}
cout<<"sum="<<sum;
}
-------------------------------------------------------------------------------------------------------
Find the summation of the elements above the inverse diagonal

0 1 2 3
0 5 7 2 13
#include<iostream.h> 1 17 63 77 15
main()
{ 2 11 22 33 45
int i,j,sum=0; 3 10 20 30 40
int a[4][4]={{5,7,2,13},{17,63,15,77},{11,22,33,45},{10,20,30,40} };
for (i=0;i<4;i++)
{
for (j=0;j<4;j++)
if((i+j)>3)
sum=sum+a[i][j];
}
cout<<"sum="<<sum;
}
-------------------------------------------------------------------------------------------------------
H.W
- Find the position of Minimum number in two dimensional array .
- Sorting two dimensional array (Ascending) .
- Product of two array A(4X3) , B(3X2) ?
-------------------------------------------------------------------------------------------------------
Note

 Array size should be positive number only.

 String array always terminates with null character ('/0’).

 Array elements are countered from 0 to n-1.

 Array are useful for multiple reading of elements (numbers).

63
To initialize two dimensional array
- default of 0
- initializers grouped by row in braces
Ex.
int m[2][2] = {{1}, {3,4}};

0 1
0 1 0
1 3 4

int array1[2][3] = { {1,2,3} ,{4,5,6} };

0 1 2
0 1 2 3
1 4 5 6

int array2 [2][3] = {1,2,3,4,5};

0 2 3
0 1 2 3
1 4 5 0

int array3[2][3] = { {1,2} ,{4} };

0 1 2
0 1 2 0
1 4 0 0

64
Hw.1) Multiplication of two dimensional array ( Multiply matrix )

# include <iostream.h>
#include<string.h>
#include<conio.h>

main ()
{
int i,j,k;
int c[2][2]={0},a[2][2],b[2][2];

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
cin>>a[i][j]; //input the elements of first array
}

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
cin>>b[i][j]; //input the elements of second array
}
clrscr();
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
cout<<a[i][j]<<" ";//print the elements of first array
cout<<endl;
}
cout<<"*******"<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
cout<<b[i][j]<<" "; //print the elements of second array
cout<<endl;
}
cout<<"******"<<endl;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
for(k=0;k<2;k++)
c[i][j] = c[i][j] + a[i][k] * b[k][j] ; // Multiplication of two dimintional
array

cout<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
cout<<c[i][j]<<" ";
cout<<endl;
}

65
Hw.2) another method to Multiply matrix

# include<iostream.h>
#include<conio.h>
main ()
{
const int m=2 , n=3 , k=2 ;
int a[n][m] , b[m][k] , c[n][k]={0};
int i,j,h;
for (i=0 ; i<n ; i++)
for (j=0 ; j<m ; j++)
{
cout<<"a["<<i<<"]["<<j<<"]";
cin>> a[i][j];
}

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


for (j=0 ; j<k ; j++)
{
cout<<"b["<<i<<"]["<<j<<"]";
cin>> b[i][j];
}

clrscr();
for (i=0 ; i<n ; i++)
{
for (j=0 ; j<m ; j++)
cout<< a[i][j]<<" ";
cout<<endl;
}

cout<<"******"<<endl;
for (i=0 ; i<m ; i++)
{
for (j=0 ; j<k ; j++)
cout<< b[i][j]<<" ";
cout<<endl;
}
cout<<"******"<<endl;
for (i=0 ; i<n ; i++)
for (j=0 ; j<k ; j++)
for (h=0 ; h<m ; h++)
c[i][j] += a[i][h] * b[h][j] ;

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


{
for (j=0 ; j<k ; j++)
cout<<"c["<<i<<"]["<<j<<"]"<<c[i][j]<<" ";
cout<<endl;
}
}

66
1 1 1 1
1 0 0 1
Hw.3) Program to print 1 0 0 1
1 1 1 1
# include <iostream.h>
main ()
{
int i,j,y,x;
int a[4][4];
for (i=0 ; i<4 ; i++)
{
for (j=0 ; j<4 ; j++)
if (i== 1 && j== 2 ||i== 1 && j== 1 || j== 2 && i== 1 || i== 2 && j== 1 || i== 2
&& j== 2)
{
x=0;
cout<<x;
}
else
{
y=1;
cout<<y;
}
cout<<endl;
}
}

Hw.4) Find the maximum value and its position in multidimensional arrays .

# include<iostream.h>
#include<conio.h>
main ()
{
int m=0,max;
int row ,col;
int i,j,a[3][3];

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


for (j=0 ; j<3 ; j++)
{
cout<<"a["<<i<<"]["<<j<<"]";
cin>> a[i][j];
} //for
clrscr();
for (i=0 ; i<3 ; i++) {
for (j=0 ; j<3 ; j++)
cout<< a[i][j]<<" ";
cout<<endl; }
cout<<"******"<<endl;
max=a[0][0];
for(i=0;i<3;i++)
for(j=0;j<3;j++)
if (max<a[i][j]){
max=a[i][j];
row=i;
col=j; }
cout<<"the maximum number is "<<a[row][col]<<" in positon [
"<<row<<"]"<<"["<<col<<"]";
}

67
Hw.5) Sorting two dimensional array ascending

# include<iostream.h>
#include<conio.h>
main ()
{
int m=2 , n=2 , k=2 ;
int a[2][2] , b[2][2] ;
int i,j,h,l;
for (i=0 ; i<n ; i++)
for (j=0 ; j<m ; j++)
{
cout<<"a["<<i<<"]["<<j<<"]";
cin>> a[i][j];
}

clrscr();
for (i=0 ; i<n ; i++)
{
for (j=0 ; j<m ; j++)
cout<< a[i][j]<<" ";
cout<<endl;
}

cout<<"******"<<endl;
//sort ascending
for(i=0;i<2;i++)
for(j=0;j<2;j++)
for(k=0;k<2;k++)
for(l=0;l<2;l++)
if (a[i][j] < a[k][l])
{
int temp = a[i][j];
a[i][j] = a[k][l];
a[k][l] = temp;
}

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


{
for (j=0 ; j<k ; j++)
cout<<"a["<<i<<"]["<<j<<"]"<<a[i][j]<<" ";
cout<<endl;
}

references

 H. Deitel and P. Deitel, “C++ How to Program,” 6th ed., Pearson/Prentice Hall, 2008.
 Schaum’s Outline of programming With C++, by John Hubbard, McGraw-Hill.
Websites

 The C++ resource network: http://www.cplusplus.com


 Textbook hompage: http://www.deitel.com/books/cpphtp5
 Free C and C++ resources: http://www.freeprogrammingresources.com/freetutr.html.
 Basics of C++ - Objective Questions Multiple Choice Questions (MCQs), http://www.psexam.com.
 C++ lessons and topics , http://www.functionx.com/cpp.

68

You might also like