SlideShare a Scribd company logo
Arrays
Chapter 5
1
Arrays
• In programming, one of the frequently problem is
to handle similar types of data. Consider this
situation: You have to store marks of more than
one student depending upon the input from user.
These types of problem can be handled in C++
programming using arrays.
• An array can be thought of as a collection of
numbered boxes each containing one data item.
The number associated with the box is the index
of the item. The index must be an integer and
indicates the position of the element in the array.
2
• Instead of declaring individual variables, such
as number0, number1, ..., and number99, you
declare one array variable such as numbers and
use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
A specific element in an array is accessed by
an index.
• Notice that the first element of an array called
foo is foo[0] not foo[1]. These elements are
numbered from 0. In C++, the first element in
an array is always numbered with a zero (not a
one), no matter its length.
3
Declaring Arrays
• Like a regular variable, an array must be declared
before being used. To declare an array in C++, the
programmer specifies the type of the elements
and the number of elements required by an array.
For examples:
• int myarray[10];
• The above statement declares an array called
myarray. This array contains 10 elements of type
integer. The first element will be myarray[0] and
the last element will be myarray[9].
4
• When declaring an array, we saw that you must
specify the number of items that the array is made
of. An alternative is to define a constant prior to
declaring the array and use that constant to hold
the dimension of the array. Here is an example:
• const int numberOfItems = 5;
• double distance[numberOfItems] ;
• Note that numberOfItems must be a const. So the
following code will give an error.
• int ItemsNumber = 5;
• double distance[ItemsNumber] ;
• // Wrong, ItemsNumber must be constant
5
Initializing arrays
• Here ia an examples of declaring and
initializing arrays:
• int arr[ 6 ] = { 7 , 2 , 4 , 9 , 10 , 3};
• int arr[ ] = { 7 , 2 , 4 , 9 , 10 , 3};
• int arr[ 10 ] = { 7 , 2 , 4 , 9 , 10 , 3};
• int arr[ 6 ] = { };
6
Accessing the values of an array
• The following statement stores the value 75 in the third
element of foo:
• foo[2] = 75;
• The following copies the value of the third element
of foo to a variable called x:
• x = foo[2];
• Notice that the third element of foo is specified foo[2],
since the first one is foo[0], the second one is foo[1],
and therefore, the third one is foo[2].
7
Important
• C++ does not check that the subscript that is
used to reference an array element actually lies
in the subscript range of the array.
• int arr[10];
• arr[17] = 22;
• This would lead to the program being
terminated by the operating system.
Alternatively it might assign a value to that
location, changing the value of the variable in
your program which is actually associated with
that memory location.
8
The size of an array
• Imagine you declare an array as follows:
• int arr[] = {18, 42, 25, 12, 34, 15, 63, 72, 92,
26, 26, 12, 127, 4762, 823, 236, 84, 5};
• Instead of counting the number of members of
this array, you can use the sizeof operator as
follows:
• int NumberOfItemsOfTheArray =
sizeof(arr)/sizeof(int);
9
Multidimensional arrays
• Multidimensional arrays can be described as
"arrays of arrays". For example, a two
dimensional array can be imagined as a two-
dimensional table made of elements, all of
them of a same uniform data type.
•
10
• The C++ syntax for this two dimensional array
is:
• int jimmy[3][5];
• the way to reference the second element
vertically and fourth horizontally in an
expression would be:
• jimmy[1][3] = 88;
• Multidimensional arrays are not limited to two
dimensions). They can contain as many
dimensions as needed.
11
Example 1
• One of the regular operations performed on an
array consists of adding the values of the
members to produce a sum.
12
int main()
{
int number[10] = {20,14,6,28,11,13,15,17,4,25};
int sum = 0;
for( int i = 0; i < 10; i++ )
{
sum += number[i];
}
cout << “Sum of numbers is " << sum << "n";
return 0;
}
13
Example 2
• Another type of operation regularly performed
on an array consists of looking for a value held
by one of its members. For example, you can
try to know if one of the members holds a
particular value you are looking for.
14
int main()
{
int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89};
int f, i, m = 8;
cout << "Enter a number to search: ";
cin >> f;
for (i = 0; (i < m) && (numbers[i] != f); i++)
continue;
if (i == m) cout << f << " is not in the list n";
else cout << f << " is the " << i + 1
<< "th element in the list n";
return 0;
}
15
Example 3
• One of the most regular operations performed
consists of comparing the values of different
members to get the lowest value of the
members
16
int main()
{
int numbers[] = {81, 25, 36, 44, 5, 60, 75, 89};
int min = numbers[0];
for (int i = 1; i < 8; ++i)
if (numbers[i] < min) min = numbers[i];
cout << “Minimum = " << min << endl;
return 0;
}
17
Problem 1
Write a program to read 30 numbers and to print
these numbers in a reverse order
18
int main(void)
{
int a[30] , k ;
for(k = 0 ; k <= 29 ; k++)
{
cout << "Enter an integer nuumber: ";
cin >> a[k] ;
}
cout << "n The numbers in reverse order: " ;
for(k = 29 ; k >= 0 ; k--) cout << a[k] << "t";
return 0;
}
19
Problem 2
Write a program to read 10 numbers, calculate
the average, then print the numbers which are
greater the average. Print also how many of these
numbers are greater than the average
20
void main(void)
{
int k , a[10] , sum , counter ;
float aver ;
sum = 0 ;
cout << "Please enter 10 integer numbers: " ;
for(k = 0 ; k <= 9 ; k++)
{
cin >> a[k] ;
sum = sum + a[k] ;
}
aver = sum / 10.0 ;
cout << "Average = " << aver << "n";
21
cout << "Numbers greater than average are: ";
counter = 0 ;
for(k = 0 ; k <= 9 ; k++)
if(a[k] > aver)
{
counter++ ;
cout << a[k] << "t" ;
}
cout << "n We have " << counter <<
"numbers greater than average n";
}
22
Problem 3
Write a program to add two matrices, each
matrix has dimensions 4*6
23
int main(void)
{
int a[4][6] , b[4][6] , sum[4][6] , r , c ;
cout << "Enter first matrix: n";
for(r = 0 ; r <= 3 ; r++)
for(c = 0 ; c <= 5 ; c++)
{
cout << "a["<<r<<"]["<<c<<"]=" ;
cin >> a[r][c] ;
}
24
cout << "Enter second matrix: n";
for(r = 0 ; r <= 3 ; r++)
for(c = 0 ; c <= 5 ; c++)
{
cout << "b["<<r<<"]["<<c<<"]=" ;
cin >> b[r][c] ;
}
25
cout << "The result n";
for(r = 0 ; r <= 3 ; r++)
{
for(c = 0 ; c <= 5 ; c++)
{
sum[r][c] = a[r][c] + b[r][c] ;
cout << sum[r][c] << "t";
}
cout << "n";
}
return 0;
}
26
Problem 4
Write a program to read 3*5 matrix and print its
transpose (5*3)
27
void main(void)
{
int m[3][5] , r , c ;
cout << "Please enter 3*5 matrix: n";
for(r = 0 ; r <= 2 ; r++)
for(c = 0 ; c <= 4 ; c++) cin >> m[r][c] ;
cout << "The transpose matrix is: ";
for(c = 0 ; c <= 4 ; c++)
{
for(r = 0 ; r <= 2 ; r++) cout << m[r][c] << "t";
cout << "n";
}
} 28
Problem 5
• Write a program to sort 10 numbers
29
• Arrays often need to be sorted in either ascending
or descending order. There are many well known
methods for doing this. This section briefly
describes one of the easiest sorting methods called
the selection sort.
• The basic idea of selection sort is:
• For each index position I in turn:
1. Find the smallest data value in the array from
positions I to (Length - 1), where "Length" is the
number of data values stored.
2. Exchange the smallest value with the value at
position I.
30
void main(void)
{
int y[10] , min , minloc , r , k , temp ;
cout << "Please enter 10 numbers: ";
for(r = 0 ; r <= 9 ; r++) cin >> y[r] ;
for(k = 0 ; k <= 8 ; k++) {
min = y[k] ; minloc = k ;
for(r = k+1 ; r <= 9 ; r++)
if(min > y[r] ) { min = y[r] ; minloc = r ; }
temp = y[k]; y[k] = y[minloc]; y[minloc] = temp;
}
for(r = 0 ; r <= 9 ; r++) cout << y[r] << "t" ;
}
31
Problem 6
• Write a program to add 2 arrays with
dimension 10 using 3 functions (read_array,
add_arrays, write_array). Do not use any
global variables
32
Problem 7
Write a program to read 10 numbers and test if
these numbers are sorted or not
33
int main()
{
int num[10] , res , k , count1 = 0 , count2 = 0 , length = 10;
for(k = 0 ; k < =length-1 ; k++)
{
cout << "Enter term number " << k << " : ";
cin >> num[k] ;
}
for(k = 0 ; k <= length-2 ; k++)
{
if(pt[k] > pt[k+1]) counter1++ ;
if(pt[k] < pt[k+1]) counter2++ ;
}
34
if((counter1 == 0) &&(counter2 == 0))
cout << "Equal numbers";
else if(counter1 == 0) cout << "Ascending";
else if(counter2 == 0) cout << "Descending" ;
else cout<< "Not sorted";
return 0 ;
}
35
Problem 8
• Write a method to search for a number in an
ordered list using Linear search. Assume that
the list contains numbers -10, -3, 7, 12, 13, 18,
20, 22, 24, and 25.
•
36
void main(void)
{
int key , res , j ;
int y[ ] = {-10, -3, 7, 12, 13, 18, 20, 22, 24, 25 };
cout << "Please enter the key number: ";
cin >> key ;
for(j = 0 ; j <= 9 ; j++)
if(y[j] == key) break ;
if(j == 10) cout << "Key does not exist n" ;
else cout << " Key exists at " << j <<"n";
}
37
Problem 9
• Write 2 programs to print the term number 10
from the series 0,1,1,2,3,5,8,........... using
1: loop without array, 2: loop with array.
38
void main(void) //First solution
{
int k , a , b , c ;
a = 0 ; b = 1 ;
for(k = 3 ; k <= 10 ; k++)
{
c = a + b ;
a = b ;
b = c ;
}
cout << c ;
}
39
void main(void) // Second solution
{
int a[10] , k ;
a[0] = 0 ;
a[1] = 1 ;
for(k = 2 ; k <= 9 ; k++)
a[k] = a[k-1] + a[k-2] ;
cout << a[9] ;
}
40
Problem 10
• Write 2 programs (one using array and the
other without using array) to read a date: year,
month, and day. Then calculate and print how
many days passed from the beginning of this
year to the specified date.
41
void main()
{
int mon[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int d , m , y , days ;
cout << "Enter day month year: ";
cin >> d >> m >> y ;
days = 0 ;
for(int k = 0 ; k < m-1 ; k++)
days = days + mon[k] ;
if((m > 2)&&(y%4 == 0)) days++;
days = days + d ;
cout << "n Number of days = %d n" << days;
}
42
void main(void)
{
int d , m , y , days ;
cout << "Enter day month year: ";
cin >> d >> m >> y ;
days = 0 ;
switch (m)
{
case 12 :days += 30 ;
case 11:days += 31 ;
case 10:days += 30 ;
case 9:days += 31 ;
case 8:days += 31 ;
43
case 7:days += 30 ;
case 6: days += 31 ;
case 5: days += 30 ;
case 4: days += 31 ;
case 3: if(y%4 == 0) days+= 29 ;
else days+= 28 ;
case 2: days += 31 ;
case 1: days += d ; break ;
default: printf("Wrong month numbern");
}
cout << "n Number of days = %d n" << days;
}
44
Problem 11
• Write a program to reverse elements of an
array of length 10. For example, if the data of
the array are already sorted in an ascending
order, it will be after executing the program in
descending order. Assume any data in the
array.
45
void main()
{
int x[ ] = { 1, 3, 7, 10, 12, 16, 19, 25, 29, 30 };
int y[10] , k ;
for(k = 0 ; k <= 9 ; k++) y[k] = x[9 - k] ;
for(k = 0 ; k <= 9 ; k++)
{
x[k] = y[k] ;
cout << x[k] << “t”;
}
}
46
Problem 12
Write a to calculate maximum, minimum,
average, variance, and deviation of these 10
numbers: 5.3, 7.2, 9.4, 8.3, 7.6, 10.2, 1.4, 2.3,
8.7, 9.1
47
Problem 13
• Write a program to print 10 random numbers
with value less than 100.
48
void main(void)
{
int k, num;
for (k = 1; k <= 10; k++)
{
num = rand() % 100;
cout << num << "t";
}
}
49
• If we run the program it will print these numbers
which are random numbers.
• 41 67 34 0 69 24 78 58
62 64
• The problem that if we rerun the program again it
will print the same numbers as follows
• 41 67 34 0 69 24 78 58
62 64
• To overcome this program we will use the
function srand(seed) before using the function
rand. Srand function will help us to get another
sequence of numbers depends on the value of
seed. For example, if we execute the following
program
50
#include < time.h >
void main(void)
{
srand(time(NULL));
int k, num;
for (k = 1; k <= 10; k++)
{
num = rand() % 100;
cout << num << "t";
}
}
51
Problem 14
• Write a program to generate 10 integer
numbers with values less than 20. The
numbers must be unrepeated. So, any number
must not be printed more than one time.
52
Problem 15
• Write a program to print 10 unrepeated sorted
(ascending) random integer numbers with
values less than 20.
53
Problem 16
• Write a program to multiply 2 matrices, the
first has dimensions 4*6, and the second has
dimensions 6*5
54
Problem 17
• Write a program to read scores of 20 students
in 5 subjects. Calculate the average score of
each student, and the succeeding ratio of each
subject.
55
Problem 18
• Write a program to read scores of 10 students
in mid term exam. Then, read scores of these
students in final exam. Calculate the total score
and the grade of each student.
56
Ad

More Related Content

Similar to 05_Arrays C plus Programming language22.pdf (20)

its arrays ppt for first year students .
its arrays ppt for first year students .its arrays ppt for first year students .
its arrays ppt for first year students .
anilkumaralaparthi6
 
C Arrays.ppt
C Arrays.pptC Arrays.ppt
C Arrays.ppt
ssuser0c1819
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
imtiazalijoono
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
Lec2
Lec2Lec2
Lec2
Ibrahim El-Torbany
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
Ibrahim El-Torbany
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
rohassanie
 
CS.3.Arrays.pdf
CS.3.Arrays.pdfCS.3.Arrays.pdf
CS.3.Arrays.pdf
YasirAli74993
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
Arrays and library functions
Arrays and library functionsArrays and library functions
Arrays and library functions
Swarup Boro
 
2DArrays.ppt
2DArrays.ppt2DArrays.ppt
2DArrays.ppt
Nooryaseen9
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
Education Front
 
Array-part1
Array-part1Array-part1
Array-part1
AbishaiAsir
 
Chapter 13.pptx
Chapter 13.pptxChapter 13.pptx
Chapter 13.pptx
AnisZahirahAzman
 
Arrays 06.ppt
Arrays 06.pptArrays 06.ppt
Arrays 06.ppt
ahtishamtariq511
 
C++ TUTORIAL 5
C++ TUTORIAL 5C++ TUTORIAL 5
C++ TUTORIAL 5
Farhan Ab Rahman
 
Array
ArrayArray
Array
PRN USM
 
R Programming Intro
R Programming IntroR Programming Intro
R Programming Intro
062MayankSinghal
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
adityavarte
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
arjurakibulhasanrrr7
 

Recently uploaded (20)

AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Introduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptxIntroduction to Zoomlion Earthmoving.pptx
Introduction to Zoomlion Earthmoving.pptx
AS1920
 
Ad

05_Arrays C plus Programming language22.pdf

  • 2. Arrays • In programming, one of the frequently problem is to handle similar types of data. Consider this situation: You have to store marks of more than one student depending upon the input from user. These types of problem can be handled in C++ programming using arrays. • An array can be thought of as a collection of numbered boxes each containing one data item. The number associated with the box is the index of the item. The index must be an integer and indicates the position of the element in the array. 2
  • 3. • Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. • Notice that the first element of an array called foo is foo[0] not foo[1]. These elements are numbered from 0. In C++, the first element in an array is always numbered with a zero (not a one), no matter its length. 3
  • 4. Declaring Arrays • Like a regular variable, an array must be declared before being used. To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array. For examples: • int myarray[10]; • The above statement declares an array called myarray. This array contains 10 elements of type integer. The first element will be myarray[0] and the last element will be myarray[9]. 4
  • 5. • When declaring an array, we saw that you must specify the number of items that the array is made of. An alternative is to define a constant prior to declaring the array and use that constant to hold the dimension of the array. Here is an example: • const int numberOfItems = 5; • double distance[numberOfItems] ; • Note that numberOfItems must be a const. So the following code will give an error. • int ItemsNumber = 5; • double distance[ItemsNumber] ; • // Wrong, ItemsNumber must be constant 5
  • 6. Initializing arrays • Here ia an examples of declaring and initializing arrays: • int arr[ 6 ] = { 7 , 2 , 4 , 9 , 10 , 3}; • int arr[ ] = { 7 , 2 , 4 , 9 , 10 , 3}; • int arr[ 10 ] = { 7 , 2 , 4 , 9 , 10 , 3}; • int arr[ 6 ] = { }; 6
  • 7. Accessing the values of an array • The following statement stores the value 75 in the third element of foo: • foo[2] = 75; • The following copies the value of the third element of foo to a variable called x: • x = foo[2]; • Notice that the third element of foo is specified foo[2], since the first one is foo[0], the second one is foo[1], and therefore, the third one is foo[2]. 7
  • 8. Important • C++ does not check that the subscript that is used to reference an array element actually lies in the subscript range of the array. • int arr[10]; • arr[17] = 22; • This would lead to the program being terminated by the operating system. Alternatively it might assign a value to that location, changing the value of the variable in your program which is actually associated with that memory location. 8
  • 9. The size of an array • Imagine you declare an array as follows: • int arr[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12, 127, 4762, 823, 236, 84, 5}; • Instead of counting the number of members of this array, you can use the sizeof operator as follows: • int NumberOfItemsOfTheArray = sizeof(arr)/sizeof(int); 9
  • 10. Multidimensional arrays • Multidimensional arrays can be described as "arrays of arrays". For example, a two dimensional array can be imagined as a two- dimensional table made of elements, all of them of a same uniform data type. • 10
  • 11. • The C++ syntax for this two dimensional array is: • int jimmy[3][5]; • the way to reference the second element vertically and fourth horizontally in an expression would be: • jimmy[1][3] = 88; • Multidimensional arrays are not limited to two dimensions). They can contain as many dimensions as needed. 11
  • 12. Example 1 • One of the regular operations performed on an array consists of adding the values of the members to produce a sum. 12
  • 13. int main() { int number[10] = {20,14,6,28,11,13,15,17,4,25}; int sum = 0; for( int i = 0; i < 10; i++ ) { sum += number[i]; } cout << “Sum of numbers is " << sum << "n"; return 0; } 13
  • 14. Example 2 • Another type of operation regularly performed on an array consists of looking for a value held by one of its members. For example, you can try to know if one of the members holds a particular value you are looking for. 14
  • 15. int main() { int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int f, i, m = 8; cout << "Enter a number to search: "; cin >> f; for (i = 0; (i < m) && (numbers[i] != f); i++) continue; if (i == m) cout << f << " is not in the list n"; else cout << f << " is the " << i + 1 << "th element in the list n"; return 0; } 15
  • 16. Example 3 • One of the most regular operations performed consists of comparing the values of different members to get the lowest value of the members 16
  • 17. int main() { int numbers[] = {81, 25, 36, 44, 5, 60, 75, 89}; int min = numbers[0]; for (int i = 1; i < 8; ++i) if (numbers[i] < min) min = numbers[i]; cout << “Minimum = " << min << endl; return 0; } 17
  • 18. Problem 1 Write a program to read 30 numbers and to print these numbers in a reverse order 18
  • 19. int main(void) { int a[30] , k ; for(k = 0 ; k <= 29 ; k++) { cout << "Enter an integer nuumber: "; cin >> a[k] ; } cout << "n The numbers in reverse order: " ; for(k = 29 ; k >= 0 ; k--) cout << a[k] << "t"; return 0; } 19
  • 20. Problem 2 Write a program to read 10 numbers, calculate the average, then print the numbers which are greater the average. Print also how many of these numbers are greater than the average 20
  • 21. void main(void) { int k , a[10] , sum , counter ; float aver ; sum = 0 ; cout << "Please enter 10 integer numbers: " ; for(k = 0 ; k <= 9 ; k++) { cin >> a[k] ; sum = sum + a[k] ; } aver = sum / 10.0 ; cout << "Average = " << aver << "n"; 21
  • 22. cout << "Numbers greater than average are: "; counter = 0 ; for(k = 0 ; k <= 9 ; k++) if(a[k] > aver) { counter++ ; cout << a[k] << "t" ; } cout << "n We have " << counter << "numbers greater than average n"; } 22
  • 23. Problem 3 Write a program to add two matrices, each matrix has dimensions 4*6 23
  • 24. int main(void) { int a[4][6] , b[4][6] , sum[4][6] , r , c ; cout << "Enter first matrix: n"; for(r = 0 ; r <= 3 ; r++) for(c = 0 ; c <= 5 ; c++) { cout << "a["<<r<<"]["<<c<<"]=" ; cin >> a[r][c] ; } 24
  • 25. cout << "Enter second matrix: n"; for(r = 0 ; r <= 3 ; r++) for(c = 0 ; c <= 5 ; c++) { cout << "b["<<r<<"]["<<c<<"]=" ; cin >> b[r][c] ; } 25
  • 26. cout << "The result n"; for(r = 0 ; r <= 3 ; r++) { for(c = 0 ; c <= 5 ; c++) { sum[r][c] = a[r][c] + b[r][c] ; cout << sum[r][c] << "t"; } cout << "n"; } return 0; } 26
  • 27. Problem 4 Write a program to read 3*5 matrix and print its transpose (5*3) 27
  • 28. void main(void) { int m[3][5] , r , c ; cout << "Please enter 3*5 matrix: n"; for(r = 0 ; r <= 2 ; r++) for(c = 0 ; c <= 4 ; c++) cin >> m[r][c] ; cout << "The transpose matrix is: "; for(c = 0 ; c <= 4 ; c++) { for(r = 0 ; r <= 2 ; r++) cout << m[r][c] << "t"; cout << "n"; } } 28
  • 29. Problem 5 • Write a program to sort 10 numbers 29
  • 30. • Arrays often need to be sorted in either ascending or descending order. There are many well known methods for doing this. This section briefly describes one of the easiest sorting methods called the selection sort. • The basic idea of selection sort is: • For each index position I in turn: 1. Find the smallest data value in the array from positions I to (Length - 1), where "Length" is the number of data values stored. 2. Exchange the smallest value with the value at position I. 30
  • 31. void main(void) { int y[10] , min , minloc , r , k , temp ; cout << "Please enter 10 numbers: "; for(r = 0 ; r <= 9 ; r++) cin >> y[r] ; for(k = 0 ; k <= 8 ; k++) { min = y[k] ; minloc = k ; for(r = k+1 ; r <= 9 ; r++) if(min > y[r] ) { min = y[r] ; minloc = r ; } temp = y[k]; y[k] = y[minloc]; y[minloc] = temp; } for(r = 0 ; r <= 9 ; r++) cout << y[r] << "t" ; } 31
  • 32. Problem 6 • Write a program to add 2 arrays with dimension 10 using 3 functions (read_array, add_arrays, write_array). Do not use any global variables 32
  • 33. Problem 7 Write a program to read 10 numbers and test if these numbers are sorted or not 33
  • 34. int main() { int num[10] , res , k , count1 = 0 , count2 = 0 , length = 10; for(k = 0 ; k < =length-1 ; k++) { cout << "Enter term number " << k << " : "; cin >> num[k] ; } for(k = 0 ; k <= length-2 ; k++) { if(pt[k] > pt[k+1]) counter1++ ; if(pt[k] < pt[k+1]) counter2++ ; } 34
  • 35. if((counter1 == 0) &&(counter2 == 0)) cout << "Equal numbers"; else if(counter1 == 0) cout << "Ascending"; else if(counter2 == 0) cout << "Descending" ; else cout<< "Not sorted"; return 0 ; } 35
  • 36. Problem 8 • Write a method to search for a number in an ordered list using Linear search. Assume that the list contains numbers -10, -3, 7, 12, 13, 18, 20, 22, 24, and 25. • 36
  • 37. void main(void) { int key , res , j ; int y[ ] = {-10, -3, 7, 12, 13, 18, 20, 22, 24, 25 }; cout << "Please enter the key number: "; cin >> key ; for(j = 0 ; j <= 9 ; j++) if(y[j] == key) break ; if(j == 10) cout << "Key does not exist n" ; else cout << " Key exists at " << j <<"n"; } 37
  • 38. Problem 9 • Write 2 programs to print the term number 10 from the series 0,1,1,2,3,5,8,........... using 1: loop without array, 2: loop with array. 38
  • 39. void main(void) //First solution { int k , a , b , c ; a = 0 ; b = 1 ; for(k = 3 ; k <= 10 ; k++) { c = a + b ; a = b ; b = c ; } cout << c ; } 39
  • 40. void main(void) // Second solution { int a[10] , k ; a[0] = 0 ; a[1] = 1 ; for(k = 2 ; k <= 9 ; k++) a[k] = a[k-1] + a[k-2] ; cout << a[9] ; } 40
  • 41. Problem 10 • Write 2 programs (one using array and the other without using array) to read a date: year, month, and day. Then calculate and print how many days passed from the beginning of this year to the specified date. 41
  • 42. void main() { int mon[] = {31,28,31,30,31,30,31,31,30,31,30,31}; int d , m , y , days ; cout << "Enter day month year: "; cin >> d >> m >> y ; days = 0 ; for(int k = 0 ; k < m-1 ; k++) days = days + mon[k] ; if((m > 2)&&(y%4 == 0)) days++; days = days + d ; cout << "n Number of days = %d n" << days; } 42
  • 43. void main(void) { int d , m , y , days ; cout << "Enter day month year: "; cin >> d >> m >> y ; days = 0 ; switch (m) { case 12 :days += 30 ; case 11:days += 31 ; case 10:days += 30 ; case 9:days += 31 ; case 8:days += 31 ; 43
  • 44. case 7:days += 30 ; case 6: days += 31 ; case 5: days += 30 ; case 4: days += 31 ; case 3: if(y%4 == 0) days+= 29 ; else days+= 28 ; case 2: days += 31 ; case 1: days += d ; break ; default: printf("Wrong month numbern"); } cout << "n Number of days = %d n" << days; } 44
  • 45. Problem 11 • Write a program to reverse elements of an array of length 10. For example, if the data of the array are already sorted in an ascending order, it will be after executing the program in descending order. Assume any data in the array. 45
  • 46. void main() { int x[ ] = { 1, 3, 7, 10, 12, 16, 19, 25, 29, 30 }; int y[10] , k ; for(k = 0 ; k <= 9 ; k++) y[k] = x[9 - k] ; for(k = 0 ; k <= 9 ; k++) { x[k] = y[k] ; cout << x[k] << “t”; } } 46
  • 47. Problem 12 Write a to calculate maximum, minimum, average, variance, and deviation of these 10 numbers: 5.3, 7.2, 9.4, 8.3, 7.6, 10.2, 1.4, 2.3, 8.7, 9.1 47
  • 48. Problem 13 • Write a program to print 10 random numbers with value less than 100. 48
  • 49. void main(void) { int k, num; for (k = 1; k <= 10; k++) { num = rand() % 100; cout << num << "t"; } } 49
  • 50. • If we run the program it will print these numbers which are random numbers. • 41 67 34 0 69 24 78 58 62 64 • The problem that if we rerun the program again it will print the same numbers as follows • 41 67 34 0 69 24 78 58 62 64 • To overcome this program we will use the function srand(seed) before using the function rand. Srand function will help us to get another sequence of numbers depends on the value of seed. For example, if we execute the following program 50
  • 51. #include < time.h > void main(void) { srand(time(NULL)); int k, num; for (k = 1; k <= 10; k++) { num = rand() % 100; cout << num << "t"; } } 51
  • 52. Problem 14 • Write a program to generate 10 integer numbers with values less than 20. The numbers must be unrepeated. So, any number must not be printed more than one time. 52
  • 53. Problem 15 • Write a program to print 10 unrepeated sorted (ascending) random integer numbers with values less than 20. 53
  • 54. Problem 16 • Write a program to multiply 2 matrices, the first has dimensions 4*6, and the second has dimensions 6*5 54
  • 55. Problem 17 • Write a program to read scores of 20 students in 5 subjects. Calculate the average score of each student, and the succeeding ratio of each subject. 55
  • 56. Problem 18 • Write a program to read scores of 10 students in mid term exam. Then, read scores of these students in final exam. Calculate the total score and the grade of each student. 56