SlideShare a Scribd company logo
DUHOK PLOYTECHNIC
UNIVERSITY
C++
(lectures)
2015-2016
Prepared By:
Zhiyan A.younis
Computer is a device capable of performing
computations and making logical decisions at speeds
faster than human beings. it is designed to follow
instructions (program). All computer systems consist
of similar hardware devices and software components.
The computer programs that run on a computer are
referred to as software(SW). While the hard
component of it is called hardware (HW).
Programming is the process of writing instructions
for a computer in a certain order to solve a
problem using computer languages..
What is a computer???
2
INTRODUCTION
3
The CPU:
The CPUs job is to fetch instructions, follow the instructions, and produce some
result. The CPU unit consists of: the control unit and the arithmetic and logic
unit (ALU). The CU is responsible for determining where to get the next
instruction and regulating the other major components of the computer with
control signals. The ALU is designed to perform mathematical operations.
Main memory:
Commonly known as random-access memory, or RAM, the computer´s main
memory is a device that holds information. Specifically, RAM holds the
sequences of instructions in the programs that are running and the data
those programs are using.
Secondary storage:
Secondary storage is a type of memory that can hold data for long periods of
time-even when there is no power to the computer. Frequently used
programs are stored in secondary memory and loaded in to main , memory
as needed. Important information, such as word processing documents,
payroll data, and inventory figures, is saved to secondary storage as well.4
Inputs Devices:
Input is any information the computer collects from the world. The
device that collects the information and sends it to the computer
is called an input device.
Output Devices:
Output is any information the computer sends to the outside
world. Common output devices are monitors, printers and
speakers. Output sent to a monitor is called “softcopy”, while
output sent to a printer is called “hard copy”.
5
Software:
Software refers to the programs that run on a computer. There are
two general categories of software: operating system and
application software.
1-Programming Languages:
There are two categories of programming languages: low-level and high-level. A low
level language is close to the level of the computer, which means it resembles the
numeric machine language of the computer more than the natural language of
humans. The easiest languages for people to learn are high level languages. They
are called “high level” because they are closer to the level of human-readability than
computer readability.
C++ is popular not only because of its mixture of low and high-level features, but also
because of its portability. This means that a C++ program can be written on one type
of computer and then run on many other types of systems.
2- Operating system:
An operating system is a set of programs that
manages the computer´s hardware devices and
controls their processes.
6
C++ Program Development Process
(PDP):
C++ programs typically go through six phases before they can be
executed. These phases are:
1. Edit: The programmer types a C++ source program, and makes
correction, if necessary. Then file is stored in disk with extension
(.cpp).
2. Pre-Processor: Pre-processing is accomplished by the pre-
proceccor before compilation, which includes some substitution
of files and other directories to be include with the source file.
3. Compilation: Converting the source program into object-code.
4. Linking: A linker combines the original code with library
functions to produce an executable code.
5. Loading: The loader loads the program from the disk into
7
Short History about programming langueges:
1954: Fortran.
1957: Cobol.
1958: Lisp.
1964: Basic.
1970: Pascal (From Algol).
1971: C (From a language called B).
1980: C with classes (experimental version).
1983: C++ (by Bjarne Stroustrup).
1986: Objective-C (from C and Smalltalk).
1991: Java.
2000: C#.
8
9
Algorithm :
algorithm can be defined as a finite sequence of
effect statements to solve a problem.
Example 1: Develop an algorithm that inputs a
series of number and output their average
"Read a number".
"Add a number to anther number".
"Output a number".
10
Flowcharts
A flowchart is a graphical representation of an
algorithm
11
Draw the flowchart required to find the sum of negative numbers
among 50 numbers entered by the user.
12
Character set: In C++ language, upper case and lower
case letters are distinct and hence there are 52 letters
in all. For example bag is different from Bag which is
different from BAG.
Special Characters:
13
Identifiers: An identifier is a name given to
some program entity such as variable ,
constant, array, function, structure, or class.
A variable works as a store for values (letters,
numbers and Boolean). When we choose the name of
an identifier there are some conditions:-
1- Starting with letters or underscore symbol.
2- The length of identifiers should be less than (256)
letters.
3- The C++ language is sensitive for the case of letters
(small and capital).
14
Keywords:The keywords are also
identifiers but cannot be user defined, since they
are reserved words. All the keywords should be in
lower case letters. Reserved words cannot be
used as variable names or constant. The following
words are reserved for use as keywords:
15
Constants are identifiers that can hold values but
; their values can not be changed after they
initialized.
Constants types:
1. String Constants :“This is test program”
3.Character Constants: ‘A’, ‘a’, ‘:’, ‘?’, etc…
2. Numeric Constants:integer, floating point,
hexadecimal, and octal.
16
17
C++ operators:
18
Example:
X+y*X-Z,
where
X=5,
Y=6,
and Z=8.
19
Assignment Operators
Ex:
x=x+5;
y=y*10;
x+=5;
y*=10;
20
Comparision and logical operators
(a) Relational operators: <, >, <= , >=
(b) Equality operators: ==, !=
(c) Logical operators: not(!), and(&&), or(||).
21
Type Conversion
int x;
float y;
x=y;
Statements:
22
STARTING WITH C++
Every C++ program has an anatomy.
Unlike human anatomy, the parts of
C++programs are not always in the
same place. Nevertheless, the parts
are there and your first step in
learning C++ is to learn what they
are.
THE PARTS OF A C++ PROGRAM
There are three main parts in c++
programs:
• Comments
• Header
• body
24
WHAT ARE COMMENTS?
Comments are used to document and explain your
codes and program logic. Comments are not
programming statements and are ignored by the
compiler, but they VERY IMPORTANT for providing
documentation and explanation for others to understand
your program(and also for yourself some days later).
There are two kinds of comments in c/c++:
1. Multi-line Comment: begins with a /* and ends with a
*/, and can span several lines .
2. End-of-line comment :begins with // and lasts till the
end of the current line.
25
HEADER
Any line started with a #, it is called a pre-processor directive. Pre-
processor reads your program before it is compiled and only
executes those lines beginning with a # symbol.
The # include directive causes the pre-processor to include the
contents of another file in the program. The word inside the
brackets, iostream.h is the name of the file that is to be included
.The iostream.h file contains code that allows a C++ program to
display output on the screen and read input from the keyboard .
The iostream file is called a header file, so it should be included at
the top of the program.
C++ provides several libraries of pre-written functions for you that
perform frequently needed operations. You access these libraries
by placing #include statements at the top of your source code file.
The most commonly used libraries are listed below. 26
HEADERS
iostream provides cin and cout
cmath provides math functions like: sin(), aqrt(),
log10()
cstdlib provides miscellaneous routines like rand()
ctime provides function for manipulating time
string allows use of the string type
vector allows use of the vector type
list allows use of the list type
27
Getting Started with C++:
The keyboard and screen I/O
instructions in C++ are:
(a): COUT/ display an object onto the
video screen:
Cout<<var.1<<var2<<…<<var.n;
(b): Cin/ It is used to read an object
from a standard input device
(keyboard):
Cin>>var.1>>var.2>>…>>var.n;
28
Getting Started with C++:
29
30
31
32
33
Constants
Write a program that reads the radius of a circle, then computes
and outputs its area.
#include<iostream.h>
void main( )
{
const float pi = 3.14;
int r; float c;
cout << “enter the radius of circle:”;
cin>>r;
cout<<endl;
c = r * r * pi;
cout << “the area of circle:” << c;
}
34
The following program computes the arethmatic
operators.
#include<iostream.h>
void main( )
{
int a,b,sum,sub,mul,div;
cout << “enter any two numbers<<endl;
cin>> a>>b;
sum=a+b;
sub=a-b;
mul=a*b;
div=a/b;
cout<<”a=”<<a<<”b=”<<b<<”sum=”<<sum<<endl;
cout<<”sub=”<<sub<<endl;
cout<<”mul=”<<mul<<endl;
cout<<”div=”<<div<<endl;
}
35
The following program computes different division
operators.
#include<iostream.h>
void main( )
{
int x, y, z, r ;
x= 7 / 2;
cout << "x=" << x <<endl;
y=17/(-3);
cout << "y="<< y <<endl;
z=-17/3;
cout << "z="<< z <<endl;
r=-17/(-3);
cout << "r="<< r <<endl;
}
36
The modulus operator “%” is used with integer
operands (int, short, long,unsigned). It can’t be used
with float or double operands.
#include<iostream.h>
void main( )
{
int y1, y2;
y1 = 8 % 3;
y2 = -17 % 3;
cout << "y1="<< y1 <<endl;
cout << "y2="<< y2 <<endl;
}
37
Example 2:
State the order of evaluation for the following expression:
Z = P * R % Q + W / X – Y;
38
Write C++ program to perform the above equation:
#include<iostream.h>
void main( )
{
int Z, P, R, Q, W, X, Y;
cout << "enter P:"; cin >> P;
cout << "enter R:"; cin >> R;
cout << "enter Q:"; cin >> Q;
cout << "enter W:"; cin >> W;
cout << "enter X:"; cin >> X;
cout << "enter Y:"; cin >> Y;
Z= P * R % Q + W / X - Y;
cout << "the result="<< Z;
}
39
The “math.h” Library:
40
Example:
Write the following equation as a C++ expression and
state the order of
evaluation of the binary operators:
Solution:
f = sqrt ((sin(x) – pow(x,5)) / (log(x) + x/4))
Order of evaluation:
41
42
Manipulator Functions:
Write C++ program to convert a base of a number:
#include<iostream.h>
void main( )
{
int value;
cout << "enter number:"; cin >> value;
cout << "Decimal base=”<<dec<<value<<endl;
cout << "Hexadecimal base=”<<hex<<value<<endl;
cout << "Octa base=”<<oct<<value<<endl;
}
43
Manipulator Functions:
Setw: It is used to specify the minimum number of
character positions on the O/P field a variable will
consume: setw(int w)
Write C++ program to use tab:
#include<iostream.h>
#include<iomanip.h>
void main( void)
{
int a,b;
a=200;
b=300;
cout<<a<<’t’<<b<<endl;
}
44
SELECTION STATEMENTS
• The Single If Statement
• The if-else Statement
• The nested if statement
• The case-switch Statement
45
SELECTION STATEMENTS
The Single If Statement Structure
46
47
The Single Block If Statement Structure :
48
The Single Block If Statement Structure :
49
The Single Block If Statement Structure :
50
The If/else Statement Structure:
51
The If/else Statement Structure:
Example 1:
cin >> value;
if ( value >= 0 )
cout << “positive”;
else
cout << “negative”;
52
The If/else Statement Structure:
Example 2:
cin >> num1 >> num2;
if ( num1 > num2 )
cout << num1;
else
cout << num2;
53
54
55
Else if Statements:
56
Else if Statements:
57
Nested If Statements:
58
Nested If Statements:
59
1. THE SWITCH SELECTION STATEMENT (SELECTOR):
General Form of Switch Selection statement:
switch ( selector )
{
case label1 : statement1 ; break;
case label2 : statement2 ; break;
case label3 : statement3 ; break;
:
case label-n : statement-n ; break;
default : statement-e ; break;
}
60
Example 1:
switch (value)
{
case 0: cout << “grade is A”;
break;
case 1: cout<< “grade is B”;
break;
case 2: coucout << “grade is C”;
break;
default: cout << “grade is X”;
break;
}
61
Notice that the break statement tells where to stop
execution.
Example:
#include<iostream.h>
void main()
{int mark; cout<<”enter mark :”; cin>>mark;
switch (mark/10)
{
case 5:cout<<”passn”;break;
case 6:cout<<”mediumn”;break;
--
--
case 10:cout<<”excellentn”;break;
default:cout<<”fail!n”;break;
}
62
Write C++ program to read two integer numbers, and read the
operation to perform on these numbers:
#include<iostream.h>
void main( )
{
int a, b;
char x;
cout << “Enter two numbers n”;
cin >> a >> b;
cout << “+ for addition n”;
cout << “- for subtraction n”;
cout << “* for multiplication n”;
cout << “/ for division n”;
cout << “enter your choice n”;
cin >> x;
63
switch ( x )
{
case ‘+’: cout << a + b;
break;
case ‘-’: cout << a - b;
break;
case ‘*’: cout << a * b;
break;
case ‘/’: cout << a / b;
break;
default: break;
}
}
64
2. NESTED SWITCH SELECTION STATEMENT:
General Form of Nested Switch Selection statement:
switch ( selector1 )
{case label1 : statement1 ; break;
case label2 : statement2 ; break;
case label3 : switch ( selector2 )
{ case label1 : statement1 ; break;
case label2 : statement2 ; break;
: }
case label-n : statement-n ; break;
default : statement-e ; break;
}
65
Write C++ program to read integer number, and print the name of
the computerized department:
#include<iostream.h>
void main( )
{
int i,j;
cout << “Enter the number for the department name n”;
cin >> i>>j;
switch (i)
{
case 1: cout << “Software Engineering Department”; break;
case 2: cout << “Control and computers Department”; break;
case 3: cout << “Computer Sciences Department”;
cout<<”Enter the no. of branch”;
66
switch(j)
{
case 1: cout << “Software”; break;
case 2: cout << “Information system”; break;
case 3: cout << “Security”;
case 4: cout << “AI”;
}
default: cout << “Invalid day number”; break;
}
}
67
3. CONDITIONAL STATEMENT:
General Form of Conditional statement:
( condition ? True : False )
Example 1:
cin >> value;
cout << (value >= 0 ? “positive” : “negative” );
Example 2:
cin >> x >> y;
cout << ( x < y ? -1 : (x == y ? 0 : 1) );
68
Write C++ program to read integer number, and print if its
even or odd:
#include<iostream.h>
void main( )
{
int value;
cout << “Enter the number n”;
cin >> value;
cout<<(value%2==0?”even”:”odd”);
}
69
LOOP STATEMENTS:
General Form of For statement:
for ( initialization ; continuation condition ; update )
statement1 ;
for ( initialization ; continuation condition ; update )
{
statement1 ;
statement2 ;
}
70
LOOP STATEMENTS:
Example 1:
for ( i = 0; i < 10; i ++ )
cout << i;
Output:
0 1 2 3 4 5 6 7 8 9
Example 2:
for ( i = 0; i < 10; i += 2 )
cout << i;
Output:
even numbers only
0 2 4 6 8
71
LOOP STATEMENTS:
Example 3:
for ( i = 1; i < 10; i += 2 )
cout << i;
Output:
odd numbers only
1 3 5 7 9
72
LOOP STATEMENTS:
Example 1
Write C++ program to add the numbers between 1 and
100:
#include<iostream.h>
void main( )
{
int sum = 0;
for ( int i = 1; i <= 100; i ++ )
sum = sum + i;
cout << “sum is: “ << sum;
}
73
LOOP STATEMENTS:
Write C++ program to add the numbers between 1 and
100:
#include<iostream.h>
void main( )
{
int sum = 0;
for ( int i = 1; i <= 100; i ++ )
sum = sum + i;
cout << “sum is: “ << sum;
}
74
LOOP STATEMENTS:
Write C++ program to find the factorial of n (using for
statement ):
n! = n * n-1 * n-2 * n-3 * … * 2 * 1
#include<iostream.h>
void main( )
{
int n, f = 1;
cout << “enter positive number: “;
cin >> n;
for ( int i = 2; i <= n; i ++ )
f = f * i;
cout << “factorial is: “ << f;
}
75
LOOP STATEMENTS:
Write C++ program to the result of the following:
#include<iostream.h>
void main( )
{
int sum = 0;
for ( int i = 1; i <= 20; i ++ )
sum = sum + ( i * i );
cout << “The sum is: “ << sum;
}
76
LOOP STATEMENTS:
Example 4
Write C++ program to read 10 integer numbers, and find
the sum of positive number only:
#include<iostream.h>
void main( )
{
int num, sum = 0;
for ( int i = 1; i <= 10; i ++ )
{
cout << “enter your number: “;
cin >> num;
if ( num > 0 ) sum = sum + num;
}
cout << “The sum is: “ << sum;
}
77
LOOP STATEMENTS:
Example 5
Write C++ program to print the following series: 1, 2, 4, 8,
16, 32, 64
#include<iostream.h>
void main( )
{
int x;
for ( x = 1; x < 65; x *= 2 )
cout << x <<” “;
}
78
LOOP STATEMENTS:
Example 6
Write C++ program to print the following:
#include<iostream.h>
void main( )
{
int x;
for ( x = 1; x < 7; ++ x )
cout << x <<”t“ << 11 – x << endl;
}
1 10
2 9
3 8
4 7
5 6
6 5
79
LOOP STATEMENTS:
Example 9
Write C++ program to print the following figure:
+
+ +
+ + +
+ + + +
+ + + + +
+ + + + + +
+ + + + + + +
+ + + + + + + +
+ + + + + + + + +
+ + + + + + + + + +
80
LOOP STATEMENTS:
General Form of While statement:
• while (condition )
statement1 ;
• while (condition )
{ statement1 ;
statement2 ;
:
statement-n ; }
81
i = 0;
while ( i < 10 )
{
cout << i;
i ++;
}
Output:
0 1 2 3 4 5 6 7 8 9
i=10
LOOP STATEMENTS:
82
Example 2:
i = 0;
while ( i < 10 )
{
cout << i;
i += 2;
}
LOOP STATEMENTS:
Output: print even numbers only
that are between(0,10)
0 2 4 6 8
83
Example 3:
i = 1;
while ( i < 10 )
{
cout << i;
i += 2;
}
LOOP STATEMENTS:
Output: odd numbers only
1 3 5 7 9
i=11
84
#include<iostream.h>
void main( )
{int i = 1;
int sum = 0;
while ( i <= 99 )
{
sum = sum + i;
i = i + 2;
}
cout << “sum is: “ << sum << endl;
}
WRITE C++ PROGRAM TO FIND THE SUMMATION OF THE FOLLOWING
SERIES:
SUM = 1 + 3 + 5 + 7 + … + 99
IN OTHER WORDS: FIND THE SUMMATION OF THE ODD NUMBERS,
BETWEEN 0 AND 100)
85
#include<iostream.h>
void main( )
{
int num , cubenum ;
cout << “Enter positive number n”;
cin >> num;
while ( num > 0 )
{
cubenum = num * num * num;
cout << “cube number is :” << cubenum << endl;}
WRITE C++ PROGRAM TO FIND THE CUB OF A NUMBER, WHILE IT IS
POSITIVE:
86
#include<iostream.h>
void main( )
{int i = 1, n ,sum = 0;
cout << “enter positive number”;
cin >> n;
while ( i <= n )
{sum += i * i ;
i++;
}cout << “sum is: “ << sum << endl;
}
WRITE C++ PROGRAM TO FIND THE SUMMATION OF THE FOLLOWING
SERIES:
87
#include<iostream.h>
void main( )
{int mark, i, sum = 0;
float av = 0;
i = 1;
while ( i <= 8 )
{cout << “enter mark: “;
cin >> mark;
sum = sum + mark;
i++;
}cout << “sum is: “ << sum << endl;
av = sum / 8;
cout << “average is: “ << av;
}
WRITE C++ PROGRAM TO FIND THE SUMMATION OF
STUDENT’S MARKS, AND IT’S AVERAGE, ASSUME THE
STUDENT HAVE 8 MARKS:
88
do
statement1 ;
while (condition );
do
{
statement1 ;
statement2 ;
:
statement-n ;
}
while (condition );
DO / WHILE STATEMENT:
89
Example 1:
i = 0;
do
{
cout << i;
i ++;
}
while ( i < 10 )
DO / WHILE STATEMENT:
Output:
0 1 2 3 4 5 6 7 8 9
i=10
90
Example 2:
i = 0;
do
{
cout << i;
i += 2;
}
while ( i < 10 )
DO / WHILE STATEMENT:
Output:
even numbers only
0 2 4 6 8
i=10
91
#include<iostream.h>
void main( )
{int accept = 1;
int x, low = 50, high = 70;
do
{cout << “enter number: “;
cin >> x;
if ( x >= low && x <= high )
accept =1;
else
accept = 0;}
while ( ! accept );}
WRITE C++ PROGRAM TO VALID INPUT CHECKING, THAT
ACCEPT THE NUMBERS BETWEEN 50 ... 70 ONLY:
92
#include<iostream.h>
void main( )
{ int mark, i, sum = 0;
float av = 0;
i = 1;
do { cout << “enter mark: “;
cin >> mark;
sum = sum + mark;
i++;}
while ( i <= 8 )
cout << “sum is: “ << sum << endl;
av = sum / 8;
cout << “average is: “ << av; }
Write C++ program to find the summation of students
marks, and its average , assume the student have 8
marks:
93
#include<iostream.h>
void main( )
{int n, f = 1;
cout << “enter positive number: “;
cin >> n;
do
{f = f * n;
n - -;}
while ( n > 1 );
cout << “factorial is: “ << f;}
N! = N * N-1 * N-2 * N-3 * … * 2 * 1
Write c++ program to find the factorial of N:
94
BREAK CONTROL STATEMENT
Example 1:
for ( i = 1; i < 100; i ++ )
{
cout << i;
if ( i == 10 ) break;
}
Output:
1 2 3 4 5 6 7 8 9 10
the break statement causes a loop to terminate early. Sometimes
it’s necessary to stop a loop before it goes through all its
iterations. When it is encountered, the loop stops and the
program jumps to the statement immediately following the loop.
95
BREAK CONTROL STATEMENTS
Example 2:
for ( i = 1; i < 10; ++ i )
for ( j = 1; j < 20; ++ j )
{
cout << i * j << endl;
if ( j == 10 ) break;
}
In a nested loop, the break statement only
interrupts the loop it is placed in.
96
BREAK CONTROL STATEMENTS
Write C++ program to check if zero or negative value
found:
#include<iostream.h>
void main( )
{ int value , I ; i=0;
while (i<=10) {
cout<<”enter a number n”;
cin>>value; if (value<=0) {
cout<<”Zero or negative value found
n”;
The continue statement causes a loop to stop its current
iteration and begin the next one!
97
CONTINUE CONTROL STATEMENTS:
Example 1:
do
{
cin >> x;
cin >> n;
if ( n < 1 ) continue;
cout << x;
-- n;
}
while ( n < 1 ); 98
ARRAYS:
An array is a consecutive group of homogeneous memory
locations.
Each element (location) can be referred to using the array name
along with an integer that denotes the relative position of that
element within the array. The data items grouped in an array
can be simple types like int or float, or can be user-defined
types like structures and objects. There are array of one or two
dimensions…
Array of One Dimension:
It is a single variable specifies each array element. The
declaration of
one dimensional arrays is:
data-type Array-name [ size ];99
Examples: int age [10]; int num [30];
float degree[5]; char a [15];
The item in an array are called elements (in contrast to the items
in a structure which are called members). The elements in an
array are of the same type only the values vary.
100
ARRAY OF ONE DIMENSION:
Initializing Array Elements
The first element of array age:
age [0] = 18;
- The last element of array age:
age [9] = 19;
- All elements of array age:
age [9] = { 18, 17, 18 ,18 ,19, 20 ,17, 18 ,19,19 };
- int x [ ] = { 12, 3, 5, 0, 11, 7, 30, 100, 22 };
- int y [10] = { 8, 10, 13, 15, 0, 1, 17, 22};
101
ARRAY OF ONE DIMENSION:
Write C++ program to display 2nd and 5th
elements of array distance:
#include<iostream.h>
void main( )
{ double distance[ ] = { 23.14, 70.52, 104.08,
468.78, 6.28};
cout << “2nd element is: “ << distance[1] << endl;
cout << “5th element is: “ << distance[4];
}
102
ARRAY OF ONE DIMENSION:
Write C++ program to read 5 numbers and print it in
reverse order:
#include<iostream.h>
void main( )
{ int a [5]; cout << "Enter 5 numbers n";
for ( int i =0; i <5; i++ )
{ cout << i << “: “;
cin >> a [ i ];
cout << “n”;
} cout << “The reverse order is: n”;
for ( i =4; i >=0; i - - )
cout << i << “: “ << a [ i ] << endl; } 103
ARRAY OF ONE DIMENSION:
Write C++ program, to find the summation of array
elements:
#include<iostream.h>
void main ( )
{ int const L = 10; int a [L]; int sum = 0;
cout << "enter 10 numbers n";
for ( int i =0; i <L; i++ )
{cout << “enter value “ << i << “: “;
cin >> a [ i ];
sum += a [ i ];
}
cout << "sum is: " << sum << endl;
104
Write C++ program, to find the minimum value in
array of 8 numbers:
#include<iostream.h>
void main ( )
{ int n = 8;
int a [ ] = { 18, 25, 36, 44, 12, 60, 75, 89 };
int min = a [ 0 ];
for ( int i = 0; i < n; i++ )
if ( a [ i ] < min ) min = a [ i ];
cout << "The minimum number in array is: "
<<min; }
105
ARRAY OF TWO DIMENSION:
Examples:
int a [10] [10];
int num [3] [4];
Arrays can have higher dimension. There can be arrays of two
dimension which is array of arrays. It is accessed with two index.
Also there can be arrays of dimension higher than two.
General Form of 2D-Array:
data-type Array-name [ Row-size ] [ Col-size ];
106
ARRAY OF TWO DIMENSION:
Initializing 2D-Array Elements:
- The first element of array age:
a [2] [3] = { {1, 2, 3} , {4, 5, 6} };
107
Write C++ program, to read 15 numbers, 5 numbers per row, the
print them:
#include<iostream.h>
void main ( )
{int a [ 3 ] [ 5 ]; int i , j;
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 5; j++ )
cin >> a [ i ] [ j ];
for ( i = 0 ; i < 3; i++ )
{for ( j = 0 ; j < 5; j++ )
cout << a [ i ] [ j ];
cout << endl;
} } 108
C++
(structures)
Structures are typically used to group several data items
together to form a single entity. It is a collection of
variables used to group variables into a single record.
Thus a structure (the keyword struct is used in C++) is
used. Keyword struct is a data-type, like the following
C++ data-types ( int, float, char, etc... ). This is unlike
the array, which all the variables must be the same
type. The data items in a structure are called the
members of the structure.
General Form of Structure:
struct struct-name
{
variables …
}; 110
For example:
Struct time
{ int hour;
Int minute;
Int second;
};
Its important to note that the structure declaration not
define a variable. It simply tells the compiler what a
time structure is made of. In essence, it creates a new
data type named time. You can define variables of this
type with simple definition statements, for example:
Time x; int a;
111
Accessing structure members
The dot operator (.) allows you to access structure members in a
program.
Examples: x.hour= 4; // assingment
cin>> y.minute; //reading
cout<<z.hour<<z.minute<<z.second; //printing
comparing structure variables
you cannot perform comparison operation directly on structure
variables. For example, assume that circle1 and circle2 are circle
structure variables. The following statement will cause an error.
If (circle1 == circle2)// error!
In order to compare two structures, you must compare the
individual members, as shown in the following code.
If ( circle1.radius == circle2.radius && circle1.diameter ==
circle2.diameter && circle1.area == circle2.area) then 112
Initializing a structure
The members of a structure variable may be initialized with starting values when the
structure variable is defined. For example:
Struct GeoInfo
{ char cityName[30];
Char state[3];
Long population;
Int distance;
};
GeoInfo location= {“ Asheville”,”nc”,50000,28};
You do not have to provide initializers for all the members of a structure variable.
For example:
GeoInfo location = {“tampa”};
GeoInfo location = {“tampa”,”GA”};
If you leave a structure member uninitialized, you must leave all the members that
follow it uninitialized as well:
GeoInfo location = {“tampa”,”GA”, ,90};//illegal!!!
113
Example: write a program to find the radius and the area of a
circle if you have the diameter (use struture).
#include <iostream.h>
#include <math.h>
Struct circle
{ double radius; double diameter; double area; };
const double pi= 3.14159;
Void main()
{ circle c;
Cout<<”enter diameter: “;cin >> c.diameter; c.radius= c.
diameter/2;
c.area = pi * pow (c. radius, 2.0)
cout<<” the radius @ the area of the circle are :n”;
cout << “radius : “<<c.radius<<endl;
cout <<” area : “ << c.area << endl; }
114
write a program to read and print the following information (student-name, mark [5], group) for (5) student and find
the average for each student.
#include <iostream.h>
Struct student
{ char name[20]; int mark[5]; char group; float average };
Void main()
{ student s[5]; int s1,i,j; For (i =0; i<5 ; i++)
{ s1=0; Cout<< “enter student name : “;
Cin >>s[i].name;
For (j =0; j<5 ; j++)
{ Cout<< “n enter student mark : “;
Cin >>s[i].mark[j];
s1=s1+ s[i].mark[j]; }
s[i].average = s1/5;
Cout<< “n enter student group“ ;
cin>>s[i].group; }
//printing information
For (i =0; i<5 ; i++)
{ Cout<< “n student name : “<<s [i].name; Cout<< “n student marks : “;
For (int j =0; j<5 ; j++)
{ cout << s[i].mark[j]<<”tt”;}
Cout<< “n student group“ ;<< s[i].group;
Cout<< “n student average“ ;<< s[i].average; } }
115
C++
(pointers)
A pointer is a variable which holds the memory address of another
variable. The pointer has the following advantages:
1. It allows passing variables, arrays, functions, strings and structures as
function arguments.
2. A pointer allows returning structured variables from functions.
3. It provides functions which can modify their calling arguments.
4. It supports dynamic allocation and deallocation of memory segments.
5. With the help of a pointer, variables can be swapped without physically
moving them.
6. It allow to establish links between data elements or objects for
somecomplex data structures such as linked lists, stacks, queues, binary
trees,tries and graphs.
7. A pointer improves the efficiency of certain routines.
In C++ pointers are distinct such as integer, float, character, etc. A
pointer
variable consists of two parts, namely, (i) the pointer operator and (ii)
the 117
Pointer Operator:
A pointer operator can be represented by a combination of (*) with
a
variable, for example int *ptr; where ptr is a pointer variable which
holds theaddress of an integer data type.
General Form of Pointer:
Data_type *pointer_variable;
Example: int x, y; int *ptr1, *ptr2;
Address Operator:
An address operator can be represented by a combination of &
with a
pointer variable. For example, if a pointer variable is an integer
type and also declared (&) with the pointer variable, then it
means that the variable is of type “address of”. For example
m=&ptr;. Note that the pointer operator & is an operator that
returns the address of the variable following it. 118
Note:
Notice the difference between the reference and
dereference operators:
& is the reference operator and can be read as
"address of"
* is the dereference operator and can be read
as "value pointed by"
Thus, they have complementary (or opposite)
meanings. A variable referenced with & can be
dereferences with *.
119
Examples:
(1) Ptr1 = &x; The memory address of variable x is assigned to
the pointer variable ptr1.
(2) Y=*prt1; The contents of the pointer variable ptr1 is assigned
to the variable y, not the memory address.
(3) Ptr1=&x; The address of the ptr1 is assigned to the pointer
variable ptr2. The contents Ptr2=ptr1; of both ptr1 and ptr2 will
be the same as these two pointer variables hold the same
address.
120
Example: write a program to store the address of a
variable in a pointer.
#include <iostream.h>
Void main()
{ int x= 25; int* ptr;
ptr = &x; //store the address of x in ptr
Cout<<”the value in x is : “<< x <<endl;
cout<<” the address of x is “ << ptr <<endl; }
121
Example: write a program to read the radius of a circle
from keyboard then calculate its area and print it (use
pointer)
# include <iostream.h>
Void main()
{ double r; double *p;
P=&r;
Cout<<”enter the radius:”;
Cin>>*p;
*p= *p * *p *3.14;
Cout<<”the area =”<<*p;
}
122
write a program to read a number from keyboard then
calculate its factorial and store it in the same location
in the memory , finally print it (use pointer)
#include<iostream.h>
Void main()
{ int i,a,no;
No=1; int* p;
P=&a;
Cin>>*p;
For(i=1;i<= *p ; i++)
{ no=no*i; }
*p=no;
cout<<”the factorial = “<<*p; } 123
A PROGRAM TO DISPLAY THE CONTENT OF POINTERS
USING AN ARRAY OF POINTERS
#include <iostream.h>
void main(void)
{
Char *ptr[3];
Ptr[0]=”Ahmed”;
Ptr[1]=”Reem”;
Ptr[2]=”Ali”;
Cout<<”contents of pointer 1 =”<<ptr[0]<<endl;
Cout<<”contents of pointer 2 =”<<ptr[1]<<endl;
Cout<<”contents of pointer 3 =”<<ptr[2]<<endl;
}
contents of pointer 1 = Ahmed
contents of pointer 2 = Reem
contents of pointer 3 = Ali
124
Functions:
A function is a set of statements designed to accomplish
a particular task . Experience has shown that the best
way to develop and maintain a large program is to
construct it from smaller pieces or (modules). Modules
in C++ are called functions . Functions are very useful
to read, write, debug and modify complex programs.
They can also be easily incorporated in the main
program. In C++,the main() itself is a function that
means the main function is invoking the other
functions to perform various tasks.
125
Defining a Function
A function definition has a name, parentheses pair containing zero ormore parameters
and a body. For each parameter, there should be a corresponding declaration that
occurs before the body. Any parameter not declared is taken to be an integer by
default. The general format of the function definition is :
General Form of Function:
return-type function-name ( parameters-list )
{
(body of function)
statement1 ;
statement2 ;
:
statement-n ;
(return something)
}
126
The type of the function may be int, float, char, etc. It may be
declared as type (void), which informs the compiler not to the
calling program. For example:
Void function_name (---)
Int function_name (---)
Any variable declared in the body of a function is said to be local
to that function. Other variables which are not declared either
as arguments or in the function body are considered “global” to
the function and must be definedexternally. For example
Void square (int a, int b) → a,b are the formal arguments.
Float output (void) → function without formal arguments
127
Example 1:
void printmessage ( )
{
cout << “University of Technology”;
}
void main ( )
{ printmessage( ); }
Example 2:
int max (int a, int b)
{ int c;
if (a > b) c = a;
else c = b;
return (c);
}
void main ( )
{ cout << max (5, 6);} 128
Return Statement:
The keyword return is used to terminate function and return a
value to its caller. The return statement may also be used to
exit a function without returning a value. The return
statement may or may not include an expression. Its
general syntax is:
Return;
Return (expression);
The return statements terminate the execution of the function
and pass the control back to the calling environment.
129
Example 1
Write C++ program to calculate the squared value of a number passed from
main function. Use this function in a program to calculate the squares of
numbers from 1 to 10:
#include<iostream.h>
int square ( int y )
{ int z;
z = y * y;
return ( z );
}
void main( )
{
int x;
for ( x=1; x <= 10; x++ )
cout << square ( x ) << endl;
}
130
Example 2
Write C++ program using function to calculate the average of two numbers entered by the user in the
main program:
#include<iostream.h>
float aver (int x1, int x2)
{ float z;
z = ( x1 + x2) / 2.0;
return ( z);
}
void main( )
{ float x; int num1,num2;
cout << "Enter 2 positive number n";
cin >> num1 >> num2;
x = aver (num1, num2);
cout << x;
}
131
Example 4
Write a function to find the largest integer among three integers entered by the user in the main
function.
#include <iostream.h>
int max(int y1, int y2, int y3)
{ int big; big=y1;
if (y2>big) big=y2;
if (y3>big) big=y3;
return (big);
}
void main( )
{ int largest,x1,x2,x3;
cout<<"Enter 3 integer numbers:";
cin>>x1>>x2>>x3;
largest=max(x1,x2,x3);
cout<<largest;
}
132
133

More Related Content

PDF
Web design EJ3
Aram Mohammed
 
PDF
net work iTM3
Aram Mohammed
 
PDF
Unit-4 networking basics in java
Amol Gaikwad
 
DOCX
Simple chat room using python
VISHAL VERMA
 
PDF
Lecture25
Debasish Pratihari
 
PDF
Socket programming-in-python
Yuvaraja Ravi
 
PDF
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
PDF
maXbox Arduino Tutorial
Max Kleiner
 
Web design EJ3
Aram Mohammed
 
net work iTM3
Aram Mohammed
 
Unit-4 networking basics in java
Amol Gaikwad
 
Simple chat room using python
VISHAL VERMA
 
Socket programming-in-python
Yuvaraja Ravi
 
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
maXbox Arduino Tutorial
Max Kleiner
 

What's hot (20)

PPT
Network Programming in Java
Tushar B Kute
 
PPT
Networking in java
shravan kumar upadhayay
 
PPT
java networking
Waheed Warraich
 
PDF
Chapter 2.1 : Data Stream
Ministry of Higher Education
 
PDF
Arduino LED maXbox starter18_3
Max Kleiner
 
PPTX
Networking in Java
Tushar B Kute
 
PDF
Java networking programs - theory
Mukesh Tekwani
 
PPT
Networking Java Socket Programming
Mousmi Pawar
 
PPTX
CCNA 1 Routing and Switching v5.0 Chapter 10
Nil Menon
 
DOC
socket programming
prashantzagade
 
PPTX
Addressing in networking (IP,MAC,Port addressing)
Geethu Jose
 
PDF
Lec 6(Application Layer)
maamir farooq
 
PDF
Chapter 2 : Inet Address & Data Stream
Ministry of Higher Education
 
PPTX
Internet Protocols
Anil Neupane
 
PPTX
Python Sockets
pythontic
 
PPTX
Socket programming or network programming
Mmanan91
 
PPT
Md13 networking
Rakesh Madugula
 
PPT
Ports & sockets
myrajendra
 
PPTX
SET UP INTERNET CONNECTION USING MODEM
EILLEN IVY PORTUGUEZ
 
Network Programming in Java
Tushar B Kute
 
Networking in java
shravan kumar upadhayay
 
java networking
Waheed Warraich
 
Chapter 2.1 : Data Stream
Ministry of Higher Education
 
Arduino LED maXbox starter18_3
Max Kleiner
 
Networking in Java
Tushar B Kute
 
Java networking programs - theory
Mukesh Tekwani
 
Networking Java Socket Programming
Mousmi Pawar
 
CCNA 1 Routing and Switching v5.0 Chapter 10
Nil Menon
 
socket programming
prashantzagade
 
Addressing in networking (IP,MAC,Port addressing)
Geethu Jose
 
Lec 6(Application Layer)
maamir farooq
 
Chapter 2 : Inet Address & Data Stream
Ministry of Higher Education
 
Internet Protocols
Anil Neupane
 
Python Sockets
pythontic
 
Socket programming or network programming
Mmanan91
 
Md13 networking
Rakesh Madugula
 
Ports & sockets
myrajendra
 
SET UP INTERNET CONNECTION USING MODEM
EILLEN IVY PORTUGUEZ
 
Ad

Similar to Whole c++ lectures ITM1 Th (20)

PPTX
Paksitan Zindabad in ITDevelopment of IT
ssuser6aa405
 
PDF
C++ advanced PPT.pdf
DinashMaliya3
 
PDF
Cp week _2.
shahidullah57
 
PPTX
Begin with c++ Fekra Course #1
Amr Alaa El Deen
 
PPT
2621008 - C++ 1
S.Ali Sadegh Zadeh
 
PPT
Basic structure of C++ program
matiur rahman
 
PPT
01 introduction to cpp
Manzoor ALam
 
PPT
Lecture01
Xafran
 
PPT
C PLUS PLUS FOR BS ELECTRICAL 2ND SEMSTERLecture01.ppt
abdurrahimk182
 
PPT
Overview of c++
geeeeeet
 
PPTX
Lec01-02 (Topic 1 C++ Fundamentals).pptx
NabilHarith2
 
PDF
Chap 2 c++
Widad Jamaluddin
 
PDF
An introduction to programming
rprajat007
 
PPT
Basics of c++ Programming Language
Ahmad Idrees
 
PPT
Programming of c++
Ateeq Sindhu
 
PPTX
introductiontothecomputerprogramming.pptx
beenish75
 
PPT
chapter-2.ppt
XanGwaps
 
PDF
Basic Elements of C++
Jason J Pulikkottil
 
PPTX
Chap_________________1_Introduction.pptx
Ronaldo Aditya
 
PPTX
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
 
Paksitan Zindabad in ITDevelopment of IT
ssuser6aa405
 
C++ advanced PPT.pdf
DinashMaliya3
 
Cp week _2.
shahidullah57
 
Begin with c++ Fekra Course #1
Amr Alaa El Deen
 
2621008 - C++ 1
S.Ali Sadegh Zadeh
 
Basic structure of C++ program
matiur rahman
 
01 introduction to cpp
Manzoor ALam
 
Lecture01
Xafran
 
C PLUS PLUS FOR BS ELECTRICAL 2ND SEMSTERLecture01.ppt
abdurrahimk182
 
Overview of c++
geeeeeet
 
Lec01-02 (Topic 1 C++ Fundamentals).pptx
NabilHarith2
 
Chap 2 c++
Widad Jamaluddin
 
An introduction to programming
rprajat007
 
Basics of c++ Programming Language
Ahmad Idrees
 
Programming of c++
Ateeq Sindhu
 
introductiontothecomputerprogramming.pptx
beenish75
 
chapter-2.ppt
XanGwaps
 
Basic Elements of C++
Jason J Pulikkottil
 
Chap_________________1_Introduction.pptx
Ronaldo Aditya
 
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
 
Ad

More from Aram Mohammed (17)

PDF
Web Design EJ3
Aram Mohammed
 
PPT
Financial markets and institutions ITM3
Aram Mohammed
 
PDF
Java doc Pr ITM2
Aram Mohammed
 
PPTX
Information Technology Fundamentals ITM!
Aram Mohammed
 
PPTX
Information Technology ITM1
Aram Mohammed
 
PPTX
Information Technology ITM1
Aram Mohammed
 
PPTX
Information Technology ITM1
Aram Mohammed
 
PPTX
Information Technology ITM1
Aram Mohammed
 
PPTX
Information Technology IT1
Aram Mohammed
 
PPTX
Information Technology ITM1
Aram Mohammed
 
PDF
Network th ITM3
Aram Mohammed
 
PPT
Introduction to financial management ITM3
Aram Mohammed
 
PPTX
System analysis ITM3.pptx
Aram Mohammed
 
PPTX
E-management ITM3
Aram Mohammed
 
PPTX
E-management ITM3
Aram Mohammed
 
PPTX
System analysis ITM3(1).pptx
Aram Mohammed
 
PDF
Network(pr)kurdish
Aram Mohammed
 
Web Design EJ3
Aram Mohammed
 
Financial markets and institutions ITM3
Aram Mohammed
 
Java doc Pr ITM2
Aram Mohammed
 
Information Technology Fundamentals ITM!
Aram Mohammed
 
Information Technology ITM1
Aram Mohammed
 
Information Technology ITM1
Aram Mohammed
 
Information Technology ITM1
Aram Mohammed
 
Information Technology ITM1
Aram Mohammed
 
Information Technology IT1
Aram Mohammed
 
Information Technology ITM1
Aram Mohammed
 
Network th ITM3
Aram Mohammed
 
Introduction to financial management ITM3
Aram Mohammed
 
System analysis ITM3.pptx
Aram Mohammed
 
E-management ITM3
Aram Mohammed
 
E-management ITM3
Aram Mohammed
 
System analysis ITM3(1).pptx
Aram Mohammed
 
Network(pr)kurdish
Aram Mohammed
 

Recently uploaded (20)

PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PDF
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPTX
Virus sequence retrieval from NCBI database
yamunaK13
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PDF
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Basics and rules of probability with real-life uses
ravatkaran694
 
PPTX
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
BÀI TẬP TEST BỔ TRỢ THEO TỪNG CHỦ ĐỀ CỦA TỪNG UNIT KÈM BÀI TẬP NGHE - TIẾNG A...
Nguyen Thanh Tu Collection
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
Artificial Intelligence in Gastroentrology: Advancements and Future Presprec...
AyanHossain
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Virus sequence retrieval from NCBI database
yamunaK13
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
Biological Classification Class 11th NCERT CBSE NEET.pdf
NehaRohtagi1
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
How to Close Subscription in Odoo 18 - Odoo Slides
Celine George
 
Basics and rules of probability with real-life uses
ravatkaran694
 
Kanban Cards _ Mass Action in Odoo 18.2 - Odoo Slides
Celine George
 

Whole c++ lectures ITM1 Th

  • 2. Computer is a device capable of performing computations and making logical decisions at speeds faster than human beings. it is designed to follow instructions (program). All computer systems consist of similar hardware devices and software components. The computer programs that run on a computer are referred to as software(SW). While the hard component of it is called hardware (HW). Programming is the process of writing instructions for a computer in a certain order to solve a problem using computer languages.. What is a computer??? 2
  • 4. The CPU: The CPUs job is to fetch instructions, follow the instructions, and produce some result. The CPU unit consists of: the control unit and the arithmetic and logic unit (ALU). The CU is responsible for determining where to get the next instruction and regulating the other major components of the computer with control signals. The ALU is designed to perform mathematical operations. Main memory: Commonly known as random-access memory, or RAM, the computer´s main memory is a device that holds information. Specifically, RAM holds the sequences of instructions in the programs that are running and the data those programs are using. Secondary storage: Secondary storage is a type of memory that can hold data for long periods of time-even when there is no power to the computer. Frequently used programs are stored in secondary memory and loaded in to main , memory as needed. Important information, such as word processing documents, payroll data, and inventory figures, is saved to secondary storage as well.4
  • 5. Inputs Devices: Input is any information the computer collects from the world. The device that collects the information and sends it to the computer is called an input device. Output Devices: Output is any information the computer sends to the outside world. Common output devices are monitors, printers and speakers. Output sent to a monitor is called “softcopy”, while output sent to a printer is called “hard copy”. 5
  • 6. Software: Software refers to the programs that run on a computer. There are two general categories of software: operating system and application software. 1-Programming Languages: There are two categories of programming languages: low-level and high-level. A low level language is close to the level of the computer, which means it resembles the numeric machine language of the computer more than the natural language of humans. The easiest languages for people to learn are high level languages. They are called “high level” because they are closer to the level of human-readability than computer readability. C++ is popular not only because of its mixture of low and high-level features, but also because of its portability. This means that a C++ program can be written on one type of computer and then run on many other types of systems. 2- Operating system: An operating system is a set of programs that manages the computer´s hardware devices and controls their processes. 6
  • 7. C++ Program Development Process (PDP): C++ programs typically go through six phases before they can be executed. These phases are: 1. Edit: The programmer types a C++ source program, and makes correction, if necessary. Then file is stored in disk with extension (.cpp). 2. Pre-Processor: Pre-processing is accomplished by the pre- proceccor before compilation, which includes some substitution of files and other directories to be include with the source file. 3. Compilation: Converting the source program into object-code. 4. Linking: A linker combines the original code with library functions to produce an executable code. 5. Loading: The loader loads the program from the disk into 7
  • 8. Short History about programming langueges: 1954: Fortran. 1957: Cobol. 1958: Lisp. 1964: Basic. 1970: Pascal (From Algol). 1971: C (From a language called B). 1980: C with classes (experimental version). 1983: C++ (by Bjarne Stroustrup). 1986: Objective-C (from C and Smalltalk). 1991: Java. 2000: C#. 8
  • 9. 9
  • 10. Algorithm : algorithm can be defined as a finite sequence of effect statements to solve a problem. Example 1: Develop an algorithm that inputs a series of number and output their average "Read a number". "Add a number to anther number". "Output a number". 10
  • 11. Flowcharts A flowchart is a graphical representation of an algorithm 11
  • 12. Draw the flowchart required to find the sum of negative numbers among 50 numbers entered by the user. 12
  • 13. Character set: In C++ language, upper case and lower case letters are distinct and hence there are 52 letters in all. For example bag is different from Bag which is different from BAG. Special Characters: 13
  • 14. Identifiers: An identifier is a name given to some program entity such as variable , constant, array, function, structure, or class. A variable works as a store for values (letters, numbers and Boolean). When we choose the name of an identifier there are some conditions:- 1- Starting with letters or underscore symbol. 2- The length of identifiers should be less than (256) letters. 3- The C++ language is sensitive for the case of letters (small and capital). 14
  • 15. Keywords:The keywords are also identifiers but cannot be user defined, since they are reserved words. All the keywords should be in lower case letters. Reserved words cannot be used as variable names or constant. The following words are reserved for use as keywords: 15
  • 16. Constants are identifiers that can hold values but ; their values can not be changed after they initialized. Constants types: 1. String Constants :“This is test program” 3.Character Constants: ‘A’, ‘a’, ‘:’, ‘?’, etc… 2. Numeric Constants:integer, floating point, hexadecimal, and octal. 16
  • 17. 17
  • 21. Comparision and logical operators (a) Relational operators: <, >, <= , >= (b) Equality operators: ==, != (c) Logical operators: not(!), and(&&), or(||). 21
  • 22. Type Conversion int x; float y; x=y; Statements: 22
  • 23. STARTING WITH C++ Every C++ program has an anatomy. Unlike human anatomy, the parts of C++programs are not always in the same place. Nevertheless, the parts are there and your first step in learning C++ is to learn what they are.
  • 24. THE PARTS OF A C++ PROGRAM There are three main parts in c++ programs: • Comments • Header • body 24
  • 25. WHAT ARE COMMENTS? Comments are used to document and explain your codes and program logic. Comments are not programming statements and are ignored by the compiler, but they VERY IMPORTANT for providing documentation and explanation for others to understand your program(and also for yourself some days later). There are two kinds of comments in c/c++: 1. Multi-line Comment: begins with a /* and ends with a */, and can span several lines . 2. End-of-line comment :begins with // and lasts till the end of the current line. 25
  • 26. HEADER Any line started with a #, it is called a pre-processor directive. Pre- processor reads your program before it is compiled and only executes those lines beginning with a # symbol. The # include directive causes the pre-processor to include the contents of another file in the program. The word inside the brackets, iostream.h is the name of the file that is to be included .The iostream.h file contains code that allows a C++ program to display output on the screen and read input from the keyboard . The iostream file is called a header file, so it should be included at the top of the program. C++ provides several libraries of pre-written functions for you that perform frequently needed operations. You access these libraries by placing #include statements at the top of your source code file. The most commonly used libraries are listed below. 26
  • 27. HEADERS iostream provides cin and cout cmath provides math functions like: sin(), aqrt(), log10() cstdlib provides miscellaneous routines like rand() ctime provides function for manipulating time string allows use of the string type vector allows use of the vector type list allows use of the list type 27
  • 28. Getting Started with C++: The keyboard and screen I/O instructions in C++ are: (a): COUT/ display an object onto the video screen: Cout<<var.1<<var2<<…<<var.n; (b): Cin/ It is used to read an object from a standard input device (keyboard): Cin>>var.1>>var.2>>…>>var.n; 28
  • 30. 30
  • 31. 31
  • 32. 32
  • 33. 33
  • 34. Constants Write a program that reads the radius of a circle, then computes and outputs its area. #include<iostream.h> void main( ) { const float pi = 3.14; int r; float c; cout << “enter the radius of circle:”; cin>>r; cout<<endl; c = r * r * pi; cout << “the area of circle:” << c; } 34
  • 35. The following program computes the arethmatic operators. #include<iostream.h> void main( ) { int a,b,sum,sub,mul,div; cout << “enter any two numbers<<endl; cin>> a>>b; sum=a+b; sub=a-b; mul=a*b; div=a/b; cout<<”a=”<<a<<”b=”<<b<<”sum=”<<sum<<endl; cout<<”sub=”<<sub<<endl; cout<<”mul=”<<mul<<endl; cout<<”div=”<<div<<endl; } 35
  • 36. The following program computes different division operators. #include<iostream.h> void main( ) { int x, y, z, r ; x= 7 / 2; cout << "x=" << x <<endl; y=17/(-3); cout << "y="<< y <<endl; z=-17/3; cout << "z="<< z <<endl; r=-17/(-3); cout << "r="<< r <<endl; } 36
  • 37. The modulus operator “%” is used with integer operands (int, short, long,unsigned). It can’t be used with float or double operands. #include<iostream.h> void main( ) { int y1, y2; y1 = 8 % 3; y2 = -17 % 3; cout << "y1="<< y1 <<endl; cout << "y2="<< y2 <<endl; } 37
  • 38. Example 2: State the order of evaluation for the following expression: Z = P * R % Q + W / X – Y; 38
  • 39. Write C++ program to perform the above equation: #include<iostream.h> void main( ) { int Z, P, R, Q, W, X, Y; cout << "enter P:"; cin >> P; cout << "enter R:"; cin >> R; cout << "enter Q:"; cin >> Q; cout << "enter W:"; cin >> W; cout << "enter X:"; cin >> X; cout << "enter Y:"; cin >> Y; Z= P * R % Q + W / X - Y; cout << "the result="<< Z; } 39
  • 41. Example: Write the following equation as a C++ expression and state the order of evaluation of the binary operators: Solution: f = sqrt ((sin(x) – pow(x,5)) / (log(x) + x/4)) Order of evaluation: 41
  • 42. 42
  • 43. Manipulator Functions: Write C++ program to convert a base of a number: #include<iostream.h> void main( ) { int value; cout << "enter number:"; cin >> value; cout << "Decimal base=”<<dec<<value<<endl; cout << "Hexadecimal base=”<<hex<<value<<endl; cout << "Octa base=”<<oct<<value<<endl; } 43
  • 44. Manipulator Functions: Setw: It is used to specify the minimum number of character positions on the O/P field a variable will consume: setw(int w) Write C++ program to use tab: #include<iostream.h> #include<iomanip.h> void main( void) { int a,b; a=200; b=300; cout<<a<<’t’<<b<<endl; } 44
  • 45. SELECTION STATEMENTS • The Single If Statement • The if-else Statement • The nested if statement • The case-switch Statement 45
  • 46. SELECTION STATEMENTS The Single If Statement Structure 46
  • 47. 47
  • 48. The Single Block If Statement Structure : 48
  • 49. The Single Block If Statement Structure : 49
  • 50. The Single Block If Statement Structure : 50
  • 51. The If/else Statement Structure: 51
  • 52. The If/else Statement Structure: Example 1: cin >> value; if ( value >= 0 ) cout << “positive”; else cout << “negative”; 52
  • 53. The If/else Statement Structure: Example 2: cin >> num1 >> num2; if ( num1 > num2 ) cout << num1; else cout << num2; 53
  • 54. 54
  • 55. 55
  • 60. 1. THE SWITCH SELECTION STATEMENT (SELECTOR): General Form of Switch Selection statement: switch ( selector ) { case label1 : statement1 ; break; case label2 : statement2 ; break; case label3 : statement3 ; break; : case label-n : statement-n ; break; default : statement-e ; break; } 60
  • 61. Example 1: switch (value) { case 0: cout << “grade is A”; break; case 1: cout<< “grade is B”; break; case 2: coucout << “grade is C”; break; default: cout << “grade is X”; break; } 61
  • 62. Notice that the break statement tells where to stop execution. Example: #include<iostream.h> void main() {int mark; cout<<”enter mark :”; cin>>mark; switch (mark/10) { case 5:cout<<”passn”;break; case 6:cout<<”mediumn”;break; -- -- case 10:cout<<”excellentn”;break; default:cout<<”fail!n”;break; } 62
  • 63. Write C++ program to read two integer numbers, and read the operation to perform on these numbers: #include<iostream.h> void main( ) { int a, b; char x; cout << “Enter two numbers n”; cin >> a >> b; cout << “+ for addition n”; cout << “- for subtraction n”; cout << “* for multiplication n”; cout << “/ for division n”; cout << “enter your choice n”; cin >> x; 63
  • 64. switch ( x ) { case ‘+’: cout << a + b; break; case ‘-’: cout << a - b; break; case ‘*’: cout << a * b; break; case ‘/’: cout << a / b; break; default: break; } } 64
  • 65. 2. NESTED SWITCH SELECTION STATEMENT: General Form of Nested Switch Selection statement: switch ( selector1 ) {case label1 : statement1 ; break; case label2 : statement2 ; break; case label3 : switch ( selector2 ) { case label1 : statement1 ; break; case label2 : statement2 ; break; : } case label-n : statement-n ; break; default : statement-e ; break; } 65
  • 66. Write C++ program to read integer number, and print the name of the computerized department: #include<iostream.h> void main( ) { int i,j; cout << “Enter the number for the department name n”; cin >> i>>j; switch (i) { case 1: cout << “Software Engineering Department”; break; case 2: cout << “Control and computers Department”; break; case 3: cout << “Computer Sciences Department”; cout<<”Enter the no. of branch”; 66
  • 67. switch(j) { case 1: cout << “Software”; break; case 2: cout << “Information system”; break; case 3: cout << “Security”; case 4: cout << “AI”; } default: cout << “Invalid day number”; break; } } 67
  • 68. 3. CONDITIONAL STATEMENT: General Form of Conditional statement: ( condition ? True : False ) Example 1: cin >> value; cout << (value >= 0 ? “positive” : “negative” ); Example 2: cin >> x >> y; cout << ( x < y ? -1 : (x == y ? 0 : 1) ); 68
  • 69. Write C++ program to read integer number, and print if its even or odd: #include<iostream.h> void main( ) { int value; cout << “Enter the number n”; cin >> value; cout<<(value%2==0?”even”:”odd”); } 69
  • 70. LOOP STATEMENTS: General Form of For statement: for ( initialization ; continuation condition ; update ) statement1 ; for ( initialization ; continuation condition ; update ) { statement1 ; statement2 ; } 70
  • 71. LOOP STATEMENTS: Example 1: for ( i = 0; i < 10; i ++ ) cout << i; Output: 0 1 2 3 4 5 6 7 8 9 Example 2: for ( i = 0; i < 10; i += 2 ) cout << i; Output: even numbers only 0 2 4 6 8 71
  • 72. LOOP STATEMENTS: Example 3: for ( i = 1; i < 10; i += 2 ) cout << i; Output: odd numbers only 1 3 5 7 9 72
  • 73. LOOP STATEMENTS: Example 1 Write C++ program to add the numbers between 1 and 100: #include<iostream.h> void main( ) { int sum = 0; for ( int i = 1; i <= 100; i ++ ) sum = sum + i; cout << “sum is: “ << sum; } 73
  • 74. LOOP STATEMENTS: Write C++ program to add the numbers between 1 and 100: #include<iostream.h> void main( ) { int sum = 0; for ( int i = 1; i <= 100; i ++ ) sum = sum + i; cout << “sum is: “ << sum; } 74
  • 75. LOOP STATEMENTS: Write C++ program to find the factorial of n (using for statement ): n! = n * n-1 * n-2 * n-3 * … * 2 * 1 #include<iostream.h> void main( ) { int n, f = 1; cout << “enter positive number: “; cin >> n; for ( int i = 2; i <= n; i ++ ) f = f * i; cout << “factorial is: “ << f; } 75
  • 76. LOOP STATEMENTS: Write C++ program to the result of the following: #include<iostream.h> void main( ) { int sum = 0; for ( int i = 1; i <= 20; i ++ ) sum = sum + ( i * i ); cout << “The sum is: “ << sum; } 76
  • 77. LOOP STATEMENTS: Example 4 Write C++ program to read 10 integer numbers, and find the sum of positive number only: #include<iostream.h> void main( ) { int num, sum = 0; for ( int i = 1; i <= 10; i ++ ) { cout << “enter your number: “; cin >> num; if ( num > 0 ) sum = sum + num; } cout << “The sum is: “ << sum; } 77
  • 78. LOOP STATEMENTS: Example 5 Write C++ program to print the following series: 1, 2, 4, 8, 16, 32, 64 #include<iostream.h> void main( ) { int x; for ( x = 1; x < 65; x *= 2 ) cout << x <<” “; } 78
  • 79. LOOP STATEMENTS: Example 6 Write C++ program to print the following: #include<iostream.h> void main( ) { int x; for ( x = 1; x < 7; ++ x ) cout << x <<”t“ << 11 – x << endl; } 1 10 2 9 3 8 4 7 5 6 6 5 79
  • 80. LOOP STATEMENTS: Example 9 Write C++ program to print the following figure: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 80
  • 81. LOOP STATEMENTS: General Form of While statement: • while (condition ) statement1 ; • while (condition ) { statement1 ; statement2 ; : statement-n ; } 81
  • 82. i = 0; while ( i < 10 ) { cout << i; i ++; } Output: 0 1 2 3 4 5 6 7 8 9 i=10 LOOP STATEMENTS: 82
  • 83. Example 2: i = 0; while ( i < 10 ) { cout << i; i += 2; } LOOP STATEMENTS: Output: print even numbers only that are between(0,10) 0 2 4 6 8 83
  • 84. Example 3: i = 1; while ( i < 10 ) { cout << i; i += 2; } LOOP STATEMENTS: Output: odd numbers only 1 3 5 7 9 i=11 84
  • 85. #include<iostream.h> void main( ) {int i = 1; int sum = 0; while ( i <= 99 ) { sum = sum + i; i = i + 2; } cout << “sum is: “ << sum << endl; } WRITE C++ PROGRAM TO FIND THE SUMMATION OF THE FOLLOWING SERIES: SUM = 1 + 3 + 5 + 7 + … + 99 IN OTHER WORDS: FIND THE SUMMATION OF THE ODD NUMBERS, BETWEEN 0 AND 100) 85
  • 86. #include<iostream.h> void main( ) { int num , cubenum ; cout << “Enter positive number n”; cin >> num; while ( num > 0 ) { cubenum = num * num * num; cout << “cube number is :” << cubenum << endl;} WRITE C++ PROGRAM TO FIND THE CUB OF A NUMBER, WHILE IT IS POSITIVE: 86
  • 87. #include<iostream.h> void main( ) {int i = 1, n ,sum = 0; cout << “enter positive number”; cin >> n; while ( i <= n ) {sum += i * i ; i++; }cout << “sum is: “ << sum << endl; } WRITE C++ PROGRAM TO FIND THE SUMMATION OF THE FOLLOWING SERIES: 87
  • 88. #include<iostream.h> void main( ) {int mark, i, sum = 0; float av = 0; i = 1; while ( i <= 8 ) {cout << “enter mark: “; cin >> mark; sum = sum + mark; i++; }cout << “sum is: “ << sum << endl; av = sum / 8; cout << “average is: “ << av; } WRITE C++ PROGRAM TO FIND THE SUMMATION OF STUDENT’S MARKS, AND IT’S AVERAGE, ASSUME THE STUDENT HAVE 8 MARKS: 88
  • 89. do statement1 ; while (condition ); do { statement1 ; statement2 ; : statement-n ; } while (condition ); DO / WHILE STATEMENT: 89
  • 90. Example 1: i = 0; do { cout << i; i ++; } while ( i < 10 ) DO / WHILE STATEMENT: Output: 0 1 2 3 4 5 6 7 8 9 i=10 90
  • 91. Example 2: i = 0; do { cout << i; i += 2; } while ( i < 10 ) DO / WHILE STATEMENT: Output: even numbers only 0 2 4 6 8 i=10 91
  • 92. #include<iostream.h> void main( ) {int accept = 1; int x, low = 50, high = 70; do {cout << “enter number: “; cin >> x; if ( x >= low && x <= high ) accept =1; else accept = 0;} while ( ! accept );} WRITE C++ PROGRAM TO VALID INPUT CHECKING, THAT ACCEPT THE NUMBERS BETWEEN 50 ... 70 ONLY: 92
  • 93. #include<iostream.h> void main( ) { int mark, i, sum = 0; float av = 0; i = 1; do { cout << “enter mark: “; cin >> mark; sum = sum + mark; i++;} while ( i <= 8 ) cout << “sum is: “ << sum << endl; av = sum / 8; cout << “average is: “ << av; } Write C++ program to find the summation of students marks, and its average , assume the student have 8 marks: 93
  • 94. #include<iostream.h> void main( ) {int n, f = 1; cout << “enter positive number: “; cin >> n; do {f = f * n; n - -;} while ( n > 1 ); cout << “factorial is: “ << f;} N! = N * N-1 * N-2 * N-3 * … * 2 * 1 Write c++ program to find the factorial of N: 94
  • 95. BREAK CONTROL STATEMENT Example 1: for ( i = 1; i < 100; i ++ ) { cout << i; if ( i == 10 ) break; } Output: 1 2 3 4 5 6 7 8 9 10 the break statement causes a loop to terminate early. Sometimes it’s necessary to stop a loop before it goes through all its iterations. When it is encountered, the loop stops and the program jumps to the statement immediately following the loop. 95
  • 96. BREAK CONTROL STATEMENTS Example 2: for ( i = 1; i < 10; ++ i ) for ( j = 1; j < 20; ++ j ) { cout << i * j << endl; if ( j == 10 ) break; } In a nested loop, the break statement only interrupts the loop it is placed in. 96
  • 97. BREAK CONTROL STATEMENTS Write C++ program to check if zero or negative value found: #include<iostream.h> void main( ) { int value , I ; i=0; while (i<=10) { cout<<”enter a number n”; cin>>value; if (value<=0) { cout<<”Zero or negative value found n”; The continue statement causes a loop to stop its current iteration and begin the next one! 97
  • 98. CONTINUE CONTROL STATEMENTS: Example 1: do { cin >> x; cin >> n; if ( n < 1 ) continue; cout << x; -- n; } while ( n < 1 ); 98
  • 99. ARRAYS: An array is a consecutive group of homogeneous memory locations. Each element (location) can be referred to using the array name along with an integer that denotes the relative position of that element within the array. The data items grouped in an array can be simple types like int or float, or can be user-defined types like structures and objects. There are array of one or two dimensions… Array of One Dimension: It is a single variable specifies each array element. The declaration of one dimensional arrays is: data-type Array-name [ size ];99
  • 100. Examples: int age [10]; int num [30]; float degree[5]; char a [15]; The item in an array are called elements (in contrast to the items in a structure which are called members). The elements in an array are of the same type only the values vary. 100
  • 101. ARRAY OF ONE DIMENSION: Initializing Array Elements The first element of array age: age [0] = 18; - The last element of array age: age [9] = 19; - All elements of array age: age [9] = { 18, 17, 18 ,18 ,19, 20 ,17, 18 ,19,19 }; - int x [ ] = { 12, 3, 5, 0, 11, 7, 30, 100, 22 }; - int y [10] = { 8, 10, 13, 15, 0, 1, 17, 22}; 101
  • 102. ARRAY OF ONE DIMENSION: Write C++ program to display 2nd and 5th elements of array distance: #include<iostream.h> void main( ) { double distance[ ] = { 23.14, 70.52, 104.08, 468.78, 6.28}; cout << “2nd element is: “ << distance[1] << endl; cout << “5th element is: “ << distance[4]; } 102
  • 103. ARRAY OF ONE DIMENSION: Write C++ program to read 5 numbers and print it in reverse order: #include<iostream.h> void main( ) { int a [5]; cout << "Enter 5 numbers n"; for ( int i =0; i <5; i++ ) { cout << i << “: “; cin >> a [ i ]; cout << “n”; } cout << “The reverse order is: n”; for ( i =4; i >=0; i - - ) cout << i << “: “ << a [ i ] << endl; } 103
  • 104. ARRAY OF ONE DIMENSION: Write C++ program, to find the summation of array elements: #include<iostream.h> void main ( ) { int const L = 10; int a [L]; int sum = 0; cout << "enter 10 numbers n"; for ( int i =0; i <L; i++ ) {cout << “enter value “ << i << “: “; cin >> a [ i ]; sum += a [ i ]; } cout << "sum is: " << sum << endl; 104
  • 105. Write C++ program, to find the minimum value in array of 8 numbers: #include<iostream.h> void main ( ) { int n = 8; int a [ ] = { 18, 25, 36, 44, 12, 60, 75, 89 }; int min = a [ 0 ]; for ( int i = 0; i < n; i++ ) if ( a [ i ] < min ) min = a [ i ]; cout << "The minimum number in array is: " <<min; } 105
  • 106. ARRAY OF TWO DIMENSION: Examples: int a [10] [10]; int num [3] [4]; Arrays can have higher dimension. There can be arrays of two dimension which is array of arrays. It is accessed with two index. Also there can be arrays of dimension higher than two. General Form of 2D-Array: data-type Array-name [ Row-size ] [ Col-size ]; 106
  • 107. ARRAY OF TWO DIMENSION: Initializing 2D-Array Elements: - The first element of array age: a [2] [3] = { {1, 2, 3} , {4, 5, 6} }; 107
  • 108. Write C++ program, to read 15 numbers, 5 numbers per row, the print them: #include<iostream.h> void main ( ) {int a [ 3 ] [ 5 ]; int i , j; for ( i = 0 ; i < 3; i++ ) for ( j = 0 ; j < 5; j++ ) cin >> a [ i ] [ j ]; for ( i = 0 ; i < 3; i++ ) {for ( j = 0 ; j < 5; j++ ) cout << a [ i ] [ j ]; cout << endl; } } 108
  • 110. Structures are typically used to group several data items together to form a single entity. It is a collection of variables used to group variables into a single record. Thus a structure (the keyword struct is used in C++) is used. Keyword struct is a data-type, like the following C++ data-types ( int, float, char, etc... ). This is unlike the array, which all the variables must be the same type. The data items in a structure are called the members of the structure. General Form of Structure: struct struct-name { variables … }; 110
  • 111. For example: Struct time { int hour; Int minute; Int second; }; Its important to note that the structure declaration not define a variable. It simply tells the compiler what a time structure is made of. In essence, it creates a new data type named time. You can define variables of this type with simple definition statements, for example: Time x; int a; 111
  • 112. Accessing structure members The dot operator (.) allows you to access structure members in a program. Examples: x.hour= 4; // assingment cin>> y.minute; //reading cout<<z.hour<<z.minute<<z.second; //printing comparing structure variables you cannot perform comparison operation directly on structure variables. For example, assume that circle1 and circle2 are circle structure variables. The following statement will cause an error. If (circle1 == circle2)// error! In order to compare two structures, you must compare the individual members, as shown in the following code. If ( circle1.radius == circle2.radius && circle1.diameter == circle2.diameter && circle1.area == circle2.area) then 112
  • 113. Initializing a structure The members of a structure variable may be initialized with starting values when the structure variable is defined. For example: Struct GeoInfo { char cityName[30]; Char state[3]; Long population; Int distance; }; GeoInfo location= {“ Asheville”,”nc”,50000,28}; You do not have to provide initializers for all the members of a structure variable. For example: GeoInfo location = {“tampa”}; GeoInfo location = {“tampa”,”GA”}; If you leave a structure member uninitialized, you must leave all the members that follow it uninitialized as well: GeoInfo location = {“tampa”,”GA”, ,90};//illegal!!! 113
  • 114. Example: write a program to find the radius and the area of a circle if you have the diameter (use struture). #include <iostream.h> #include <math.h> Struct circle { double radius; double diameter; double area; }; const double pi= 3.14159; Void main() { circle c; Cout<<”enter diameter: “;cin >> c.diameter; c.radius= c. diameter/2; c.area = pi * pow (c. radius, 2.0) cout<<” the radius @ the area of the circle are :n”; cout << “radius : “<<c.radius<<endl; cout <<” area : “ << c.area << endl; } 114
  • 115. write a program to read and print the following information (student-name, mark [5], group) for (5) student and find the average for each student. #include <iostream.h> Struct student { char name[20]; int mark[5]; char group; float average }; Void main() { student s[5]; int s1,i,j; For (i =0; i<5 ; i++) { s1=0; Cout<< “enter student name : “; Cin >>s[i].name; For (j =0; j<5 ; j++) { Cout<< “n enter student mark : “; Cin >>s[i].mark[j]; s1=s1+ s[i].mark[j]; } s[i].average = s1/5; Cout<< “n enter student group“ ; cin>>s[i].group; } //printing information For (i =0; i<5 ; i++) { Cout<< “n student name : “<<s [i].name; Cout<< “n student marks : “; For (int j =0; j<5 ; j++) { cout << s[i].mark[j]<<”tt”;} Cout<< “n student group“ ;<< s[i].group; Cout<< “n student average“ ;<< s[i].average; } } 115
  • 117. A pointer is a variable which holds the memory address of another variable. The pointer has the following advantages: 1. It allows passing variables, arrays, functions, strings and structures as function arguments. 2. A pointer allows returning structured variables from functions. 3. It provides functions which can modify their calling arguments. 4. It supports dynamic allocation and deallocation of memory segments. 5. With the help of a pointer, variables can be swapped without physically moving them. 6. It allow to establish links between data elements or objects for somecomplex data structures such as linked lists, stacks, queues, binary trees,tries and graphs. 7. A pointer improves the efficiency of certain routines. In C++ pointers are distinct such as integer, float, character, etc. A pointer variable consists of two parts, namely, (i) the pointer operator and (ii) the 117
  • 118. Pointer Operator: A pointer operator can be represented by a combination of (*) with a variable, for example int *ptr; where ptr is a pointer variable which holds theaddress of an integer data type. General Form of Pointer: Data_type *pointer_variable; Example: int x, y; int *ptr1, *ptr2; Address Operator: An address operator can be represented by a combination of & with a pointer variable. For example, if a pointer variable is an integer type and also declared (&) with the pointer variable, then it means that the variable is of type “address of”. For example m=&ptr;. Note that the pointer operator & is an operator that returns the address of the variable following it. 118
  • 119. Note: Notice the difference between the reference and dereference operators: & is the reference operator and can be read as "address of" * is the dereference operator and can be read as "value pointed by" Thus, they have complementary (or opposite) meanings. A variable referenced with & can be dereferences with *. 119
  • 120. Examples: (1) Ptr1 = &x; The memory address of variable x is assigned to the pointer variable ptr1. (2) Y=*prt1; The contents of the pointer variable ptr1 is assigned to the variable y, not the memory address. (3) Ptr1=&x; The address of the ptr1 is assigned to the pointer variable ptr2. The contents Ptr2=ptr1; of both ptr1 and ptr2 will be the same as these two pointer variables hold the same address. 120
  • 121. Example: write a program to store the address of a variable in a pointer. #include <iostream.h> Void main() { int x= 25; int* ptr; ptr = &x; //store the address of x in ptr Cout<<”the value in x is : “<< x <<endl; cout<<” the address of x is “ << ptr <<endl; } 121
  • 122. Example: write a program to read the radius of a circle from keyboard then calculate its area and print it (use pointer) # include <iostream.h> Void main() { double r; double *p; P=&r; Cout<<”enter the radius:”; Cin>>*p; *p= *p * *p *3.14; Cout<<”the area =”<<*p; } 122
  • 123. write a program to read a number from keyboard then calculate its factorial and store it in the same location in the memory , finally print it (use pointer) #include<iostream.h> Void main() { int i,a,no; No=1; int* p; P=&a; Cin>>*p; For(i=1;i<= *p ; i++) { no=no*i; } *p=no; cout<<”the factorial = “<<*p; } 123
  • 124. A PROGRAM TO DISPLAY THE CONTENT OF POINTERS USING AN ARRAY OF POINTERS #include <iostream.h> void main(void) { Char *ptr[3]; Ptr[0]=”Ahmed”; Ptr[1]=”Reem”; Ptr[2]=”Ali”; Cout<<”contents of pointer 1 =”<<ptr[0]<<endl; Cout<<”contents of pointer 2 =”<<ptr[1]<<endl; Cout<<”contents of pointer 3 =”<<ptr[2]<<endl; } contents of pointer 1 = Ahmed contents of pointer 2 = Reem contents of pointer 3 = Ali 124
  • 125. Functions: A function is a set of statements designed to accomplish a particular task . Experience has shown that the best way to develop and maintain a large program is to construct it from smaller pieces or (modules). Modules in C++ are called functions . Functions are very useful to read, write, debug and modify complex programs. They can also be easily incorporated in the main program. In C++,the main() itself is a function that means the main function is invoking the other functions to perform various tasks. 125
  • 126. Defining a Function A function definition has a name, parentheses pair containing zero ormore parameters and a body. For each parameter, there should be a corresponding declaration that occurs before the body. Any parameter not declared is taken to be an integer by default. The general format of the function definition is : General Form of Function: return-type function-name ( parameters-list ) { (body of function) statement1 ; statement2 ; : statement-n ; (return something) } 126
  • 127. The type of the function may be int, float, char, etc. It may be declared as type (void), which informs the compiler not to the calling program. For example: Void function_name (---) Int function_name (---) Any variable declared in the body of a function is said to be local to that function. Other variables which are not declared either as arguments or in the function body are considered “global” to the function and must be definedexternally. For example Void square (int a, int b) → a,b are the formal arguments. Float output (void) → function without formal arguments 127
  • 128. Example 1: void printmessage ( ) { cout << “University of Technology”; } void main ( ) { printmessage( ); } Example 2: int max (int a, int b) { int c; if (a > b) c = a; else c = b; return (c); } void main ( ) { cout << max (5, 6);} 128
  • 129. Return Statement: The keyword return is used to terminate function and return a value to its caller. The return statement may also be used to exit a function without returning a value. The return statement may or may not include an expression. Its general syntax is: Return; Return (expression); The return statements terminate the execution of the function and pass the control back to the calling environment. 129
  • 130. Example 1 Write C++ program to calculate the squared value of a number passed from main function. Use this function in a program to calculate the squares of numbers from 1 to 10: #include<iostream.h> int square ( int y ) { int z; z = y * y; return ( z ); } void main( ) { int x; for ( x=1; x <= 10; x++ ) cout << square ( x ) << endl; } 130
  • 131. Example 2 Write C++ program using function to calculate the average of two numbers entered by the user in the main program: #include<iostream.h> float aver (int x1, int x2) { float z; z = ( x1 + x2) / 2.0; return ( z); } void main( ) { float x; int num1,num2; cout << "Enter 2 positive number n"; cin >> num1 >> num2; x = aver (num1, num2); cout << x; } 131
  • 132. Example 4 Write a function to find the largest integer among three integers entered by the user in the main function. #include <iostream.h> int max(int y1, int y2, int y3) { int big; big=y1; if (y2>big) big=y2; if (y3>big) big=y3; return (big); } void main( ) { int largest,x1,x2,x3; cout<<"Enter 3 integer numbers:"; cin>>x1>>x2>>x3; largest=max(x1,x2,x3); cout<<largest; } 132
  • 133. 133