[go: up one dir, main page]

0% found this document useful (0 votes)
40 views56 pages

05 Arrays

Uploaded by

bodzzaa21
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)
40 views56 pages

05 Arrays

Uploaded by

bodzzaa21
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/ 56

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 number\n");
}
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

You might also like