Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 24

Arrays and Strings

Chapter (7)

1 Part I
Contents
 Learning Objectives
 Array Fundamentals
 Fundamental Array Operations
Bubble Sort with Descending Order
Linear Search
Binary Search
Multidimensional Arrays
Exercise
Summary

2
Learning Objectives
 To learn how to use array with its fundamental building blocks

To approach to the basic data structure called linear and binary search
To give the student hands-on experience with the concepts of sorting
and searching of the array
To understand the basic concepts of the multidimensional array of the
C++ programming language.

3
Array Fundamentals
 In everyday life we commonly group similar objects into units.
We buy peas by the can and eggs by the carton.
 In computer languages we also need to group together data
items of the same type.
 The most basic mechanism that accomplishes this in C++ is the
array.
 Arrays can hold a few data items or tens of thousands.
 The data items grouped in an array can be simple types such as
int or float, or they can be user-defined types such as structures
and objects.

4
Syntax of array definition
 An array must be defined before it
can be used to store information.
 And, like other definitions, an array
definition specifies a variable type
and a name.
 But it includes another feature: a
size. The size specifies how many
data items the array will contain.
 It immediately follows the name
and is surrounded by square
brackets.

5
Array Elements
The items in an array are called
elements.

all the elements in an array are of the


same type; only the values vary.

6
Array Fundamentals(Example)
#include<iostream> Here’s a sample
using namespace std; interaction with the program:
int main()
{
int age[4];
int j;
for(j=0; j<4; j++) //get 4 ages
{
cout << "Enter an age: ";
cin >> age[j]; //access array element
}
for(j=0; j<4; j++) //display 4 ages
cout << "You entered " << age[j] << endl;
return 0;
}
7
Averaging Array Elements
#include<iostream>
using namespace std; Here’s some sample
int main() interaction with SALES:
{ const int SIZE = 6; //size of array
double sales[SIZE]; //array of 6 variables
int j;
cout << "Enter Apple sales for 6 days\n"; Enter Apple sales for 6 days
for(j=0; j<SIZE; j++) //put figures in array 352.64
cin >> sales[j]; 867.70
double total = 0; 781.32
for(j=0; j<SIZE; j++) //read figures from array 867.35
total += sales[j]; //to find total 746.21
double average = total / SIZE; // find average 189.45
cout << "Average = "<< average << endl; Average = 634.11
return 0;
}

8
Syntax of array initialization
 can give values
to each array
element when
the array is first
defined

We don’t need to use the array size when we initialize all the array
elements, since the compiler can figure it out by counting the
initializing variables.

int days_per_month[ ] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

9
Example(shows days from start of year to date specified)
#include<iostream>
using namespace std;
int main()
{
int month, day, total_days;
int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
cout << "\nEnter month (1 to 12): ";
cin >> month; Here’s some sample interaction:
cout << "Enter day (1 to 31): ";
cin >> day; Enter month (1 to 12): 3
Enter day (1 to 31): 11
total_days = day; //separate days
Total days from start of year is: 70
for(int j=0; j<month-1; j++)
total_days += days_per_month[j];
cout << "Total days from start of year is: " << total_days << endl;
return 0;
}

10
Exercise 1
The height of 10 students in a class are recorded as follow:

5.6 5.5 5.3 4.9 5.2 5.6 4.8 5.0 4.9 5.1

Write a program to find the shortest and highest student in


the class. Then also find the average height of all students
and display the result on screen.

11
Solution:
#include<iostream> cout<<"\nThe shortest height="<<shortest;
using namespace std; cout<<"\nThe hightest height="<<hightest;
int main() }
{
    float height[10]={5.6,5.5,5.3,4.9,5.2,5.6,4.8,5.0,4.9,5.1};
    float sum=0.0, avg; Output:
    float shortest=height[0];
    float hightest = height[0]; The average height of all students =5.19
    for(int i=0;i<10;i++) The shortest height=4.8
  { The hightest height=5.1
        sum+=height[i];
        if(shortest>height[i]) shortest=height[i];
        if(shortest<height[i]) hightest=height[i];
  }
    avg=sum/10;
    cout<<"\nThe average height of all students ="<<avg;   

12
Exercise 2

At the Best Auto Car Show room, the total number of cars that are
ordered from customer for MarkII, Surff, Pradom Fir, Harrier, Crown,
Carina, Suziki: 400, 550, 600, 750, 300, 940, 630, 557. Use these total
numbers of cars to initialize to an integer array and write a program to
find the average number of cars and also find which brand of car is the
maximum ordered from the customer. (Hint: use 1 dimensional array)

13
Solution:
#include<iostream>
using namespace std;         switch(brand)
int main()   {
{ int car[8]={400, 550, 600, 750, 300, 940, 630, 557};         case 0:cout<<"MarkII";break;
    float avg;         case 1:cout<<"Surff";break;
    int sum=0, max=car[0],brand=0;         case 2:cout<<"Prado";break;
    for(int i=0;i<8;i++)         case 3:cout<<"Van";break;
    { sum+=car[i];         case 4:cout<<"Harrier";break;
        if(max<car[i])         case 5:cout<<"Crown";break;
    {         case 6:cout<<"Carina";break;
            max=car[i];         case 7:cout<<"Suziki";break;
            brand=i;   }
    }   return 0;
  } }
avg=sum/8;
    cout<<"\nThe average number of cars="<<avg;
    cout<<"\nThe maximum ordered from the customer is";

14
Exercise 3

Write a program that asks the user to enter 4 integer value from
keyboard and store entered data into 1_D numeric array. Then
sort the array in descending order. Your program should display
the array element before sort and after sort on screen.

15
Bubble Sort with Descending Order
#include<iostream> for(i=0;i<4;i++) i=0 0 1 2 3
using namespace std; { j 20 30 10 40
int main() for(j=0;j<4-i-1;j++) 0 30 20 10 40
{ { if(a[j] < a[j+1]) 1 30 20 10 40
int a[4],temp,j; { temp = a[j]; 2 30 20 40 10
int i; a[j] = a[j+1];
for(i=0;i<4;i++) a[j+1] = temp; 0 1 2 3
i=1
{ } j 30 20 40 10
cout<<"\nEnter Marks:"; } 0 30 20 40 10
} 1 30 40 20 10
cin>>a[i]; cout<<"\nAfter Sorting : ";
} for(i=0;i<4;i++)
i=2 0 1 2 3
cout<<"\nBefore Sorting : "; cout<<a[i]<<"\t";
j 30 40 20 10
for(i=0;i<4;i++) return 0;
0 40 30 20 10
{ }
cout<<a[i]<<"\t";
}
16
Exercise 4

Write a program that creates an array of 5 elements of type


integer. Display this array and then prompts the user to enter a
key and search that key number using linear search. If the key
element is found in that array, display the message ‘found’ and
the position of key number in the array. If the key element is not
found, display the message ‘not found’.

17
Linear Search
#include<iostream> while( found == 0 && i<5) 0 1 2 3 4
10 7 5 3 4
using namespace std; {
int main() if(a[i] == key)
{ found =1; key
int a[5],key,i,found=0; else
found 0
for(i=0;i<5;i++) i++;
{ }
cout<<"\nEnter number:"; if( found == 1)
cout<<"\nFound in "<<i<< " position of array";
cin>>a[i]; else
} cout<<"\nNot Found";
cout<<"\nEnter key:"; return 0;
cin>>key; }
i=0;

18
Binary Search(Exercise 5)
int main(){
f m l key
int a[5],temp, key;
int j ,f ,l, m, found=0; 0 1 2 3 4
10 20 30 40 50 found 0
for(int i=0;i<5;i++)
{ cout<<"\nEnter Marks:";
cout<<"\nEnter key : ";
cin>>a[i];
cin>>key;
} f=0; l = 5-1;
//Sort with Ascending Order while(found == 0 && f<=l)
for(int i=0;i<5;i++) { m = (f+l)/2;
{ for(j=0;j<5-i-1;j++) if(a[m] ==key) found=1;
{ if(a[j] > a[j+1]){ else if (a[m] < key) f= m + 1;
else l = m - 1;
temp = a[j]; }
a[j] = a[j+1]; if (found == 1)
a[j+1] = temp; cout<<"\nFound in "<< m << " position of array";
} else cout<<"\nNot Found";
} return 0;
}
}

19
Multidimensional Arrays
 Arrays can have higher dimensions.
 The array is defined with two size specifiers, each enclosed in brackets:
int student[Year][Section];
double sales[DISTRICTS][MONTHS];

There can be arrays of more than two dimensions.


 A three-dimensional array is an array of arrays of arrays accessed with three
indexes:
float dimension[x][y][z];

20
Multidimensional Arrays(Example 1)
#include<iostream> for(i=0;i<2;i++)
using namespace std; {
for(j=0;j<3;j++)
int main()
{
{
cout<<twoD[i][j]<<'\t';
int twoD[2][3]; }
int i,j; cout<<endl;
for(i=0;i<2;i++) }
{ return 0;
for(j=0;j<3;j++) }
{
cout<<"Enter an integer number: ";
cin>>twoD[i][j];
}
}

21
Program for adding two array((Example 2)
#include<iostream> for(i=0;i<m;i++) 0 1 2
using namespace std; { 0 10 20 30
int main() for(j=0;j<n;j++) 1 40 50 60
A
{ { 2 70 80 90
int i,j; C[i][j]=A[i][j]+B[i][j]; 3 100 110 120
const int m = 4; } 0 1 2
const int n= 3; } 0 1 2 3
int A[m][n],B[m][n],C[m][n]; for(i=0;i<m;i++) 1 4 5 6
for(i=0;i<m;i++) { B 2 7 8 9
{ for(j=0;j<n;j++) 3 10 11 12
for(j=0;j<n;j++) {
{ cout<< C[i][j]<<"\t"; 0 1 2
cout<<"Enter two numbers } 0 11 22 33
for Array A and B: "; cout<<endl; 1 44 55 66
cin>>A[i][j]>>B[i][j]; } C 2 77 88 99
} return 0; 3 11 121 132
} } 0

22
Exercises
1. Write a C++ program to take 5 integer inputs form user and store them in an
array. Display the value of the array. Again, ask user to give a number. And then
update every array element by multiplication by this number. Display the update
value of array. The interaction of the program might look like this:
Before multiplication : 1 2 3 4 5
Enter number :3
After multiplication : 3 6 9 12 15

2. Write a program that ask user to enter integer value from keyboard. Then display
the enter integer in reverse order.
i.e. if user entered 3 4 5, your program should display 5 4 3.

23
THANK YOU.

24

You might also like