0% found this document useful (0 votes)
60 views47 pages

Computer Is A Device Capable of Performing Computations and Making

Computers are devices capable of performing computations and logical decisions at extremely high speeds through the execution of programs. Programming involves writing instructions, known as source code, for computers to execute in order to solve problems. The C++ programming language has evolved over time, with early languages including Fortran, Cobol, and Algol leading to the development of C++ in the 1980s. C++ programs make use of variables, constants, input/output operations, and arithmetic operators to perform tasks.

Uploaded by

kophyozawhk
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)
60 views47 pages

Computer Is A Device Capable of Performing Computations and Making

Computers are devices capable of performing computations and logical decisions at extremely high speeds through the execution of programs. Programming involves writing instructions, known as source code, for computers to execute in order to solve problems. The C++ programming language has evolved over time, with early languages including Fortran, Cobol, and Algol leading to the development of C++ in the 1980s. C++ programs make use of variables, constants, input/output operations, and arithmetic operators to perform tasks.

Uploaded by

kophyozawhk
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/ 47

Introduction

Computer is a device capable of performing computations and making


logical decisions at speeds millions and even billions of times faster than
human beings.

Computers process data under the control of sets of instructions called


computer programs.

Programming is the process of writing instructions for a computer in a


certain order to solve a problem.
The computer programs that run on a computer are referred to as software.

Developing new software requires written lists of instructions for a computer


to execute. Programmers rarely write in the language directly understood
by a computer.

1
Short History
The following is a short history, just for given a general view of how
languages are arrived:
• 1954: Fortran.
• 1957: Cobol.
• 1958: Algol (Base for Simula).
• 1958: Lisp.
• 1961: B1000.
• 1962: Sketchpad.
• 1964: Basic.
• 1967: Simula67.
• 1968: FLEX.
• 1970: Pascal (From Algol).
• 1971: C (From a language called B).
• 1972: Smalltalk72 (Based on Simula67 and Lisp).
• 1976: Smalltalk76.
• 1979: ADA (From Pascal).
• 1980: C with classes (experimental version).
• 1983: C++ (by Bjarne Stroustrup).
• 1986: Objective-C (from C and Smalltalk).
• 1986: Eiffel (from Simula).
• 1991: Sather (From Eiffel) .
• 1991: Java. Bjarne Stroustrup
• 2000: C#.

2
Character set:
C++ has the letters and digits, as show below:
1) Uppercase: A, B, C, . . ., Z
2) Lowercase: a, b, c, . . ., z
3) Digits: 0, 1, 2, . . .,9
4) Special Characters:

+ - * / . ( ) : $ # ; , = < > % } { ! " '

Identifiers:
An identifier is a name given to some program entity, such as a
variable, a constant, an array, or a function.

An identifier is a sequence of alphanumeric (alphabetic and numeric)


characters, the first of which must be a letter, and can‟t contain
spaces.

Upper and lower letters can be used.


CS1 Computer computer first
Note: C++ is case-sensitive. That means the
uppercase and lowercase letters are consider
named age is different from Age, which is different
from AGE.
The length of an identifier is machine dependent. C++ allows identifiers
of up to 127 characters.
Some words are reserved by C++ (are parts of the C++ language) such
as main, for, while, if…

3
Reserved words
Reserved words can‟t be used as variable names or constant.

Reserved Words in C++ Language:


near static asm double long sizeof protected
do int while new auto else far
for this void delete goto if catch
const entry char class public case char
continue extern struct inline float private return
virtual volatile frinde enum near static break
cdecl default overload unsigned typedef signed register
pascal operator switch template union

Getting Started with C++:


To begin learning C++ lets examine our first C++ Program:
Example 2.1
Example:
#include<iostream.h> Output:
void main( )
Technical
{
// A program to print Technical
cout << “Technical”;
}

 #include<iostream.h> this line is for pre-processor directive. Any


begins with # is processed before the program is compiled. C++
programs must be start with #include.

Every group of related functions is stored in a separate library called


(header file). To use the cin and cout, must include the header file
iostream.

 main( ),the actual program begins with a function named main().


Every C++ program must have a function called main(). In general, a
function is a block of code that performs one or more action. Usually
functions are called by the other functions, but main() is special, when
your program stared it is called automatically .
s

4
 void, is the return type of the main function. When the return type of a
function is void, this function will not passes back any value to the
calling function.
Some programmers use int as a return type for the main function, in this
case a return(0) statement must be written as a last statement of the
main function-body.

 {, indicates the begin of the statements in the function.

 }, indicates the end of the statements in the function.

 //, text after these symbols is a comment. It does not affect the
program code, and compilers normally ignore it.
Also you can use the symbols /* */ to write comment between them

 cout, this statement used to print message to the screen.

 cin, It reads the input values from the keyboard.

 <<, the stream insertion operator (or send operator).


 >>, the stream extraction operator (or get from operator).
 ; , semicolon, the terminator of every C++ statement.

5
Special Escape Code
C++ provides escape sequences for several usages. These escape sequences
are listed bellow:

The endl is used in c++ to represent a new line, as shown in the following
example:
Example:
#include<iostream.h>
void main( ) Computer
Department
{
cout << “Computer” << endl;
cout << “Department”;
}

The \n is a special escape code, also used in C++ to represent a new line, as
shown in the following example:
Example:
#include<iostream.h>
void main( ) Computer
{ Department

cout << “Computer \n”;


cout << “Department”;
}

6
Variables Declaration:
A variable is a location in the computer‟s memory where a value can be
stored for later use by the program.

Variables are like buckets that hold data. These


data buckets are really locations in the computer‟s
memory.

All variable must be declared with a name (an identifier) and a


data-type. The types of variables used in C++ programs are described in the
following table.

Variable Type:
Type Description Size Range of values
unsigned short Short integer 2 Bytes 0 to 65,535
short Short integer 2 Bytes -32,768 to 32,767
unsigned long Long integer 4 Bytes 0 to 4,294,967,295
long Long integer 4 Bytes -2,141,483,647 to 2,141,483,648
int Integer 2 Bytes 0 to 65,535
Unsigned int Integer 2 Bytes -32,768 to 32,767
char Character 1 Byte 256 characters
float Floating point number 4 Bytes 1.2 e -38 to 3.4 e 38
Double Double precision floating point number 8 Bytes 2.2 e -308 to 1.8 e 308
bool Boolean value: true or false 1 Byte True or false

Numeric type

Integers Floating point

short int long float double

7
Variables
A variable defined by stating its type, followed by one or more
spaces, followed by the one or more variable names separated
by commas, then followed by semicolon. For example:
unsigned short X;
float Y;
char A, a, c;
Note: C++ does distinguish between above A and
a variables (C++ is case-sensitive).

Example
The following program reads three different data inputs and
outputs it.
#include<iostream.h>
input integer number: 2
input decimal number: 3.5
void main( ) input character: a
{
int n; float f; char c;
cout << “input integer number:”;
cin>>n;
cout<<endl;
cout << “input decimal number:”;
cin>>f;
cout<<endl;
cout << “input character:”;
cin>>c;
}

8
Constants
Like variables, constants are data storage locations. Unlike variables, and as
the name implies, constants don‟t change.
const int myage=19;
const double pi=3.14;
const float salary=20.5;
Example
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 a;
cout << “enter the radius of circle:”;
cin>>r;
cout<<endl;
a = r * r * pi;
cout << “the area of circle:” << a;
}

Example
Write a program that reads the width and high of a rectangle, then computes
and outputs its area.
#include<iostream.h>
void main()
{
int w,h,a;
cout << "input the width and height of the rectangle";
cin>>w>>h;
cout << endl;
a=w*h;
cout<<a;
}

9
Operations
1) Arithmetic operator
To perform arithmetic operations, C++ language provides the binary
operators:
- (subtraction operator), + (addition operator), *(multiplication operator),
/ (division operator) and % (modulus operator).
When a division operator “/” is used with integer‟s operands, an integer result
is provided; any fractional portion of the result is discarded.

Operator Description Example


+ Addition a+b
- Subtraction a-b
* Multiplication a*B
/ Division a/b
% Modulus – rest of division a%b

Example
#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;
}

10
The modulus operator % is used to find the reminder that would be obtained
when its left operand is divided by its right operand. It is used with integer
operands (int, short, long, unsigned). It can‟t be used with float or double
operands.
Example
#include<iostream.h>
void main( )
{
int y1, y2;
y1 = 8 % 3;
y2 = -17 % 3;
cout << "y1="<< y1 <<endl;
cout << "y2="<< y2 <<endl;
}

C++ evaluates arithmetic expressions by the following rules of operator


precedence, which are generally the same in algebra.
1. Parentheses evaluation, which can be used to force the order of
evaluation to occur in any desired sequence.
Y1 = 2 + (3*5) evaluates to 17.
Y2 = (2+3) * 5 evaluates to 25.
2. Multiplication (*), division (/), and modulus (%) operations are evaluated
next. For several operations in the same expression, the evaluation is
from left to right.
3. Addition (+), and subtraction (-) operations are evaluated last. For
several operations in the same expression, the evaluation is from left to
right.
Example 1:
Write the following equation as a C++ expression:

Solution:
f = (a + b + c + d + e) / 10;
Note: the parentheses here are required because division has higher
precedence than addition.

11
The “math.h” Library:
The “math.h” library contains the common mathematical function used in the
scientific equations.

Example:
Write the following equation as a C++ expression and state the order of
evaluation of the binary operators:

Then write the program?


Solution:
f = sqrt ((sin(x) + pow(x,5)) / (log(x) + x/4))

Order of evaluation:

#include <iostream.h>
#include <math.h>
void main ()
{
int x; float f;
cout<<"input x value"<<endl;
cin>>x;
f=sqrt((sin(x)+pow(x,5))/(log(x)+x/4));
cout<<"f="<<f<<endl;
}

12
Increment and decrement Operators:
The incremental operator (++) adds one to its operand. While the
decrement operator (- -) subtracts one from its operand.

For example:
i ++; is equivalent to: i = i+1;
size --; is equivalent to: size = size-1;
The ++ and - - operators can be written either before the variable (prefix
notation) or after the variable (postfix notation) as in the following:

X is incremented before its value is taken


Prefix notation: ++X
or returned to current statement.
X is incremented after its value is taken or
Postfix notation: X ++
returned to current statement.

The difference between the Prefix and Postfix notations:

Prefix notation Postfix notation


int y; int y;
int x = 7; int x = 7;
cout<< ++x <<endl; cout<< x++ <<endl;
y=x; y=x;
cout<<y; cout<<y;

Output: Output:
8 7
8 8

13
2) Operational Assignment Operators:
The operational assignment operator has the form:
Variable = variable operator expression;
For example: X = X + 5;
Y = Y * 10;
The operational assignment operator can be written in the following form:
Variable operator = expression;
For example: X += 5;
Y *= 10;
Exercise:
Rewrite the equivalent statements for the following examples, and find it
results. Assume: X=2 , Y=3 , Z=4 , V=12 , C=8.

Example Equivalent Statement Result

X+=5 X=X+5 X=7


Y-=8 Y=Y-8 Y=-5
Z*=5 Z=Z*5 Z=20
V/=4
C%=3

3) Relational Operators:
The relationships can be expressed in C++ by using the relational operators.
These operators are listed in the following table.

Operator Operator Usage Example Result


== Equal to 7= =5 False (0)
!= Not equal to 3 != 2 True (1)
< Less than 4<9 True (1)
<= Less than or equal to 7<=6 False (0)
> Greater than -2>4 False (0)
>= Greater than or equal to 12>=10 True (1)

14
4) Logical Operators:
The logical expression is constructed from relational expressions by the
use of the logical operators not(!), and(&&), or(||).

15
Exercise:
1. Given that A and B are real variables with values 1.5, and 2.5
respectively, and C is integer variable with value 3, evaluate the
following:
NOT (A < 0) AND (B/C <= 0).
2. Find the value of B (true or false) for the following:
i= 5;
j = 9;
B= ! (( i > 0 ) && ( i >= j ));

3. Find the value of D & E for the following:


#include <iostream.h>
int main ( )
{
short a,b,c ;
short d,e ;
d=e=30 ;
a=4 ;
b=--a+1 ;
c=++a + b++ ;
cout << "A="<<a<< "\t"<<"B=" <<b<< "\t"<< "C=" <<c<<"\n";
c+=--a + --b ;
a=b=c-(a*b) ;
d/=a+b ;
e=e/a +b ;
cout << "D="<<d<< "\t"<< "E=" <<e ;
return 0 ;
}

4. Write a program to read four marks of the students, then find & print the
average?

16
The Single If Statement Structure:

Example 1: if ( avrg >= 3.5 )


cout << “good”;
Example 2: if ( x > 0.0 )
sum += x;
Example 3: cin >> num;
if ( num == 0 )
zcount = zcount + 1;

The Single If Statement Structure (Blocks):

17
Example
Write C++ program to read a number and check if it’s positive, if it’s so print it, add it
to a total, and decrement it by 2 ?
#include<iostream.h>
void main( )
{
int num, total;
cin >> num;
if ( num >= 0 )
{
cout << num <<” is a positive”;
total += num;
num = num – 2;
}
}

The If/else Statement Structure:

Example 1: cin >> value;


if ( value >= 0 )
cout << “positive”;
else
cout << “negative”;
Example 2: cin >> num1 >> num2;
if ( num1 > num2 )
cout << num1;
else
cout << num2;

18
Example
Write C++ program to read a student degree, and check if it’s degree greater than or
equal to 50, then print pass, otherwise print fail?
#include<iostream.h>
void main( )
{
int degree;
cin >> degree;
if (degree >= 50 )
cout << "pass";
else
cout << "fail";
}

Example
Write C++ program to read a number, and check if it’s even or odd?
#include<iostream.h>
void main( )
{
int num;
cin >> num;
if ( num % 2 == 0 )
cout << "even";
else
cout << "odd";
}

19
Nested If and If/else Statements:
General Form of Nested If/else statement:
if ( expression or condition 1 ) statement1 ;
else if ( expression or condition 2 ) statement2 ;
else if ( expression or condition 3 ) statement3 ;
:
else if ( expression or condition n ) statement-n ;
else statement-e ;

Example 1: if ( value == 0 ) cout << “grade is A”;


else if ( value == 1 ) cout << “grade is B”;
else if ( value == 2 ) cout << “grade is C”;
else cout << “grade is X”;

Example 2: if ( day == 1 ) cout << “Sunday”;


else if (day == 2 ) cout << “Monday”;
else if (day == 3 ) cout << “Tuesday”;
else if (day == 4 ) cout << “Wednesday”;
else if (day == 5 ) cout << “Thursday”;
else if (day == 6 ) cout << “Friday”;
else if (day == 7 ) cout << “Saturday”;
else cout << “Invalid day number”;

20
Example
Write C++ program to compute the value of Z according to the following equations:
x+5 :x<0
Z= cos(x) + 4 :x=0
√x :x>0
#include<iostream.h>
void main( )
{
int Z, x;
cout << "Enter X value \n";
cin >> x;
if ( x < 0 ) Z= x + 5;
else if ( x == 0 ) Z= cos(x) + 4;
else Z= sqrt(x);
cout << "Z = " << Z;
}

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;
}
Example 1: switch (value)
{
case 0: cout << “grade is A”;
break;
case 1: cout << “grade is B”;
break;
case 2: cout << “grade is C”;
break;
default: cout << “grade is X”;
break;
}

21
Example :
switch (day)
{
case 1: cout << “Sunday”; break;
case 2: cout << “Monday”; break;
case 3: cout << “Tuesday”; break;
case 4: cout << “Wednesday”; break;
case 5: cout << “Thursday”; break;
case 6: cout << “Friday”; break;
case 7: cout << “Saturday”; break;
default: cout << “Invalid day number”; break;
}

Example
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;
switch ( x )
{
case „+‟: cout << a + b;

22
break;
case „-‟: cout << a - b;
break;
case „*‟: cout << a * b;
break;
case „/‟: cout << a / b;
break;
default: break;
}
}

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;
}

23
Exercise
Q1) Write C++ program to read x and compute sin, cos, and tan of x ?

Q2) Write C++ program to read integer number and print the equivalent string?
e.g:
0 Zero
1 One
2 Two
.
.

Q3) Write C++ program to read a score of student and print the estimation to refer it?
e.g:
100 – 90 Exultant
89 – 80 Very good
79 – 70 Good
69 – 60 Middle
59 – 50 Accept
49 – 0 Fail

24
While Repetition Structure:

Example
i = 0;
while ( i < 10 )
{
cout << i;
i ++;
}

Example
i = 0;
while ( i < 10 )
{
cout << i;
i += 2;
}

Example
i = 1;
while ( i < 10 )
{
cout << i;
i += 2;
}

25
Example
Write C++ program to find the summation of the following series:
sum = 1 + 3 + 5 + 7 + … + 99
#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;
}

Example
Write C++ program to find the cub of a number, while it is a positive
#include <iostream.h>
void main()
{
int num;
int cub;
cout <<"input positive number\n";
cin>>num;
while (num>0)
{
cub=num*num*num;
cout << "cube number is :" << cub << endl;
cin>>num;
}
}

26
Example
Write C++ program to find the summation of the following series:

#include <iostream.h>
void main()
{
int i=1, n, sum=0;
cin >>n;
while (i<=n)
{
sum=sum+i*i;
i++;
}
cout << "sum = " << sum << endl;
}

Example
Write C++ program to find the summation of student’s marks, and it’s average,
assume the student have 8 marks

#include <iostream.h>
void main()
{
int i=1,sum=0, mark;
float average;
while (i<=8)
{
cout<<"input the degree no."<<i;
cin>>mark;
sum=sum+mark;
i++;
}
cout<<"summation="<<sum<<endl;
cout<<"average="<<sum/8;
}

27
Exercise:
1. Find the factorial of n.
2. Represent the following series: 1, 2, 4, 8, 16, 32, 64.
3. Write C++ program to inverse an integer number (ex: 12345 to 54321)

28
Do / While Statement:

Example 1:
i = 0;
do
{
cout << i;
i ++;
}
while ( i < 10 );

Example 2:
i = 0;
do
{
cout << i;
i += 2;
}
while ( i < 10 );

29
Example
Write C++ program to find the summation of student’s marks, and it’s average,
assume the student have 8 marks
#include <iostream.h>
void main ()
{
int sum=0;
float av=0;
int degree,x=1;
do
{
cout <<"input the degree no."<<x<<"=";
cin>>degree;
sum=sum+degree;
x++;
}
while (x<=8);
cout<<"the summation="<<sum<<endl;
av=sum/8;
cout<<"the average="<<av;
}

30
Example
Write C++ program to valid input checking, that accept the numbers between
50 ... 70 only

#include<iostream.h>
void main( )
{
int accept = 1;
int x, low = 50, high = 70;
do
{
cout << “enter number: “;
cin >> x;
if ( x >= 50 && x <= 70 )
accept =1;
else
accept = 0;
}
while ( accept==1 );
}

Exercise:
Write C++ program to read 8 marks, if pass in all marks (>=50) print “pass”
otherwise print “fail”.

31
For Statement

Example
Write C++ program to sum 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;
}

32
Example
Write C++ program to find the factorial of n
#include <iostream.h>
void main ()
{
int n,f=1;
cout <<"input number=";
cin>>n;
for (int i=2; i<=n; i++)
f=f*i;
cout<<"the factorial of this number is ="<<f;
}

Example
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 summation = "<<sum;
}

33
Example
Write C++ program to read 10 integer numbers, and find the sum of positive
number only

#include <iostream.h>
void main ()
{
int sum=0;
int x;
for (int i=1; i<=10; i++)
{
cout<<"input number"<<i<<"=";
cin >> x;
if (x>0)
sum=sum+x;
}
cout<<"the summation="<<sum;
}

Example
Write C++ program to print the following series: 1, 2, 4, 8, 16, 32, 64

#include <iostream.h>
void main ()
{
for (int i=1;i<=64;i=i*2)
cout<<i<<"\t";
}

34
Exercise:
Q) Write C++ program to print the following:
1 20
2 19
3 18
4 17
5 16
6 15

Q) Write a program which reads an integer value (T) representing time in


seconds, and converts it to equivalent hours (hr), minutes (min), and seconds
(sec), in the following form:
hr : min : sec
i.e.:
Input: 5000
Output: 1 : 23 : 20

Q) Write a program represents the following series: 0, 1, 1, 2, 3, 5, 8, 13, 21

35
Nested Loops:
We can put loops one inside another to solve a certain programming problems.
Loops may be nested as follows:

Example

Write C++ program to print the following figure:


+
++
+++
++++
+++++
++++++
+++++++
++++++++
+++++++++
++++++++++

#include<iostream.h>
void main( )
{
int i, j;
for ( i = 1; i <= 10; i ++ )
{
for ( j = 1; j <= i; j ++ )
cout<<" + ";
cout<<"\n";
}
}

36
Exercise:
What is the output of the following C++ program?

#include<iostream.h>
void main( )
{
int i, j, k;
for ( i = 1; i <= 2; i ++ )
{
for ( j = 1; j <= 3; j ++ )
{
for ( k = 1; k <= 4; k ++ )
cout<<"+";
cout<<"\n";
}
cout<<"\n";

}
}

37
Arrays:
Declaration of 1 D-Array:

Initializing Array Elements:

38
Accessing Array Elements:
- Accessing the first element of array number to variable x:
x = number [0];
- Accessing the last element of array number to variable y:
y = number [9];
- cout << number [0] + number [9];
- number [0] = number [1] + number [2];
- number [7] = number [7] + 3;

Read / Write / Process Array Elements:

Example

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];
}

39
Example

Write C++ program to read 5 numbers and print it in reverse order:


#include<iostream.h>
void main( )
{
int a [4];
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;
}

Example
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;
}

40
Example

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 = 1; i < n; i++ )
if ( a [ i ] < min ) min = a [ i ];
cout << "The minimum number in array is: " << min;
}

41
Array of Two Dimensions:
Declaration of 2D-Arrays:

Initializing 2D-Array Elements:


- The first element of array age:
a [2] [3] = { {1, 2, 3} , {4, 5, 6} };
1 2 3
4 5 6

42
Read / Write / Process Array Elements
Example
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;
}
}

Example
Write C++ program, to read 4*4 2D-array, then find the summation of the array
elements, finally print these elements:
#include<iostream.h>
void main ( )
{
int a [ 4 ] [ 4 ];
int i , j, sum = 0;
for ( i = 0 ; i < 4; i++ )
for ( j = 0 ; j < 4; j++ )
cin >> a [ i ] [ j ];
for ( i = 0 ; i < 4; i++ )
for ( j = 0 ; j < 4; j++ )
sum += a [ i ] [ j ];
cout << “summation is: “ << sum << endl;
for ( i = 0 ; i < 4; i++ )
{
for ( j = 0 ; j < 4; j++ )
cout << a [ i ] [ j ];
cout << endl;
}
}

43
Example
Write C++ program, to read 3*4 2D-array, then find the summation of each row:
#include<iostream.h>
void main ( )
{
int a [ 3 ] [ 4 ];
int i , j, sum = 0;
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
cin >> a [ i ] [ j ];
for ( i = 0 ; i < 3; i++ )
{
sum = 0;
for ( j = 0 ; j < 4; j++ )
sum += a [ i ] [ j ];
cout << “summation of row “ << i << “ is: “ << sum << endl;
}
}

Example
Write C++ program, to read 3*4 2D-array, then replace each value equal 5
with0:
#include<iostream.h>
void main ( )
{
int a [ 3 ] [ 4 ];
int i , j;
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
cin >> a [ i ] [ j ];
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
if ( a [ i ] [ j ] == 5 ) a [ i ] [ j ] = 0;
for ( i = 0 ; i < 3; i++ )
{
for ( j = 0 ; j < 4; j++ )
cout << a [ i ] [ j ];
cout << endl;
}
}

44
Example
Write C++ program, to addition two 3*4 arrays:
#include<iostream.h>
void main ( )
{
int a [ 3 ] [ 4 ], b [ 3 ] [ 4 ], c [ 3 ] [ 4 ];
int i , j;
cout << "enter element of array A: \n";
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
cin >> a [ i ] [ j ];
cout << "enter element of array B: \n";
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
cin >> b [ i ] [ j ];
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
c [ i ] [ j ] = a [ i ] [ j ] + b [ i ] [ j ];
for ( i = 0 ; i < 3; i++ )
{
for ( j = 0 ; j < 4; j++ )
cout << c [ i ] [ j ];
cout << endl;
}
}

45
Example
Write C++ program, to replace each element in the main diameter (diagonal)
with zero:
#include<iostream.h>
void main ( )
{
int a [ 3 ] [ 3 ];
int i , j;
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 3; j++ )
cin >> a [ i ] [ j ];
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 3; j++ )
if ( i == j ) a [ i ] [ j ] = 0;
for ( i = 0 ; i < 3; i++ )
{
for ( j = 0 ; j < 3; j++ )
cout << a [ i ] [ j ];
cout << endl;
}
}

46
Example
Write C++ program, to convert 2D-array into 1D-array:
#include<iostream.h>
void main ( )
{
int a [ 3 ] [ 4 ];
int b [ 12 ];
int i , j, k = 0;
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
cin >> a [ i ] [ j ];
for ( i = 0 ; i < 3; i++ )
for ( j = 0 ; j < 4; j++ )
{
b [ k ] = a [ i ] [ j ];
k++;
}
for ( i = 0 ; i < k; i++ )
cout << b [ i ];
}

47

You might also like