0% found this document useful (0 votes)
16 views53 pages

07 Arrays

The document provides an overview of arrays in programming, detailing their structure, declaration, initialization, and various operations such as accessing elements, searching, and sorting. It includes examples of one-dimensional and two-dimensional arrays, as well as practical programming assignments to reinforce the concepts. Additionally, it discusses functions related to arrays and how they can be passed as parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views53 pages

07 Arrays

The document provides an overview of arrays in programming, detailing their structure, declaration, initialization, and various operations such as accessing elements, searching, and sorting. It includes examples of one-dimensional and two-dimensional arrays, as well as practical programming assignments to reinforce the concepts. Additionally, it discusses functions related to arrays and how they can be passed as parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 53

Arrays

• A variable that can store multiple values of the same


type
• The values stored in consecutive memory locations
• The memory location in an array are called an
element of array

1
Arrays
• The total number of elements in the array is called its
length
• Each element in the array is accessed with reference
to its position of location in the array called subscript
or index
• Subscript/index start at 0

2
Declaring one dimensional array
• A type of array in which all elements are arranged in
the form of a list is known as one-dimensional
array/linear list
• It consist of one column/one row
• The process of specifying array name, length and
data type is called array declaration
• Syntax – Data_Type Identifier [Length]
• int marks[5]

3
Example
• int marks[5];

• The above example declares an integer array marks of five


elements
• It allocates five consecutive locations in memory
• The index or subscript of first element is 0 and index of
last element is 4
4
Accessing array elements
• Each individual element of an array is accessed by
specifying the following:
• Name of array
• Index or subscript of element
• Syntax – Array_Name[index]

5
Example
#include<iostream>
using namespace std;
int main()
{
int arr[5];
cout<<"enter five integers: "<<endl;
cin>>arr[0];
cin>>arr[1];
cin>>arr[2];
cin>>arr[3];
cin>>arr[4];
cout<<"the values in array are: "<<endl;
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
return 0;
}

6
Example
#include<iostream>
using namespace std;
int main()
{
int arr[5], i;
for (i=0; i<5;i++)
{
cout<<“enter an integer: ”;
cin>>arr[i];
}
cout<<“the values in array are: ”;
for (i=0; i<5;i++)
cout<<arr[i]<<endl;
return 0;
}
7
Array initialization
• The process of assigning values to array elements at the time of array
declaration is called array initialization
• Syntax – Data_Type Identifier[Length] = {List of values};

• The above statement declares an integer array marks with five elements
• It also initializes the array with values given in the braces
• In this declaration, marks[0] is initialized to 70, marks[1] is initialized to 54 and
so on..
• A syntax error occurs if the values in the braces are more than the length of 8
Array initialization
• An array size can be omitted when it is initialized in
the declaration:

• The compiler determines the size of the age array


according to the initialized values on the right side
• The size of an array in above example is 9

9
Partial initialization of array during
declaration
• If the number of initial values is less than the array
size, the remaining array elements are initialized to
zero
• Initial values are used in order; you cannot skip over
element to initialize a noncontiguous range
• You cannot have more values in the initialization list
than the declared size of the array

10
Question
• Write a program that inputs current day and
month from the user. It then calculates and
display the total number of days in the current
year till the entered date.

11
Example
• #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): "; //get date
• cin >> month;
• cout << "Enter day (1 to 31): ";
• cin >> day;
• total_days = day; //separate days
• 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;
• }

12
Question
• Write a program that inputs the age of
different persons and counts the number of
persons in the age group of 50 and 60

13
Example
#include <iostream>
using namespace std;
int main()
{
int age[150], i, n, count =0 ;

cout << "Enter the number of person required";


cin >> n;
cout << "Enter ages of"<<n<<"person"<<endl;
for(int i=0; i<n; i++)
{
cin>>age[i];
if (age[i] >= 50 && age[i] <= 60)
count = count +1;
}
cout<< count<<"persons are between 50 and 60: " << endl;
return 0;
}

14
Question
• Write a program that inputs 10 numbers from
the user in array and displays the minimum
number

15
Example
#include <iostream>
using namespace std;
int main()
{
int arr[10], i, min;
for(int i=0; i<10; i++)
{
cout << "Enter the value";
cin >> arr[i];
}
min = arr[0];
for(int i=0; i<10; i++)
if (min > arr[i])
min = arr [i];
cout<< “minimum value is " << min<< endl;
return 0;
}

16
Searching in Arrays
• Searching is the process of finding the required data in the array
• Searching becomes more important when the length of array is very large
• Two method: linear search and binary search

• Linear search: Visit the first element of the array and compare its value with the
required value
• If the value of array matches with the desired value, the search is complete
• If the value of array does not match, move to next element and repeat the same process
• Loops are frequently used to visit elements of array for searching a value

17
Question
• Write a program that initializes an array. It
inputs a value from the user and searches the
number in the array.

18
Example
#include <iostream>
using namespace std;
int main()
{
int i, n, loc = -1;
int arr[10] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
cout << "Enter value to find: ";
cin >> n;
for (int i=0; i<10; i++)
{
if (arr[i] == n)
loc = i;
}
if (arr[i] == -1)
cout << "value not found in the array";
else
cout << "value found at index"<<loc;
return 0;
}

19
Sorting Arrays
• Sorting is the process of arranging values of
array into an order:
• Alphabetical, ascending (smallest to largest)
numeric, descending (largest to smallest)
numeric
• Two methods: bubble sort and selection sort

20
Bubble sort
• Bubble sort is also known as exchange sort
• Compare 1st two elements and exchange them if
they are out of order
• Move down one element and compare 2 nd and 3rd
elements. Exchange if necessary. Continue until
the end of the array.
• Pass through the array again, repeating the
process and exchanging as necessary
• Repeat until the pass is made with no exchanges
21
Bubble sort

22
Bubble sort

23
Example
#include <iostream> for (int i=0; i<5; i++)
using namespace std; for (int j=0; j<4; j++)
int main() if (arr[j]>arr[j+1])
{
{
temp = arr[j];
int arr[5], i, j, temp; arr[j] = arr[j+1];
for (int i=0; i<5; i++) arr[j+1] = temp;
{ }
cout<<"enter value: "; cout << "The sorted value
cin>>arr[i]; in array is: ";
for (i=0; i<5; i++)
}
cout <<arr[i]<<" ";
cout<<"The orginal return 0;
value in array is: "; }
for (int i=0; i<5; i++)
cout<<arr[i]<<" ";

24
Assignment q#1
• Write a program that inputs two integers. It
passes first integer to a function that
calculates and returns its square. It passes the
second integer to another function that
calculates and returns its cube. The main ()
function adds both returned values and
displays the result.

25
Solution
#include <iostream>
using namespace std;
int sqr(int n);
int cube(int n);
int main()
{
int a,b,r;

cout<<"enter an integer ";


cin>>a;
cout<<"enter an integer ";
cin>>b;
r = sqr(a) + cube(b);
cout<<"result is "<<r;
}

int sqr(int n)
{
return n*n;
}
int cube(int n)
{
return n*n*n;
26
}
Assignment q#2
• Write a function called circlearea() that finds
the area of a circle. It should take an argument
of type float and return the argument of the
same type. Write a main () function that gets a
radius value from the user, calls circlearea()
and displays the result.

27
Solution
#include <iostream>
using namespace std;
float circlearea(float r);

int main()
{
float radius, area;

cout<<"enter radius ";


cin>>radius;
area = circlearea(radius);
cout<<"The area of the circle is "<<area;
}

float circlearea(float r)
{
float a;
a = 3.14 * r * r;
return a;
} 28
Assignment q#3
• Write a program that inputs five values from
the user, stores them in an array and displays
the sum and average of these values.

29
Solution
#include <iostream>
using namespace std;
int main()
{
int arr[5], i, sum = 0;
float avg = 0.0;
for (int i=0; i<5; i++)
{
cout<<"enter value: ";
cin>>arr[i];
sum = sum + arr[i];
}
avg = sum/5.0;
cout<<"The sum is “<<sum<<endl;
cout<<“The average is”<<avg<<;
}

30
Assignment q#4
• Write a program that inputs five numbers in
an array and displays them in actual and
reverse order

31
Solution
#include <iostream>
using namespace std;
int main()
{
int num[5], i;
for (int i=0; i<5; i++)
{
cout<<"enter an integer: ";
cin>>num[i];
}
cout<<"The array in actual order is:";
for (int i=0; i<5; i++)
cout<< num[i]<<" ";
cout<<"The array in reverse order:";
for (int i=4; i>=0; i--)
{
cout<<num[i]<<" ";
}
}

32
Two Dimensional array
• Two dimensional array has a table that consist
of rows and column.
• One index is used to indicate the row of an
element and the second index indicate the
column of the element
• Syntax – Data_Type identifier [Rows] [Cols]
• For example: the statement below declares a 2-
D array with three rows and four columns
• int Arr[3][4]
33
Two Dimensional array initialization

• The 2-D array can be initialized at the time of declaration


• The process of initialization is performed by assigning the initial
values in braces separated by commas
• Example: int Arr[3] [4] = { {12, 5, 22, 84},
{95, 3, 41, 59},
{77, 6, 53, 62} };

For number arrays, if the values for all elements are not specified, the unspecified
elements are initialized by zero. In this case at least, one value must be given
34
Two Dimensional array initialization
• The initialization can also be performed
without using the inner braces as follows:
• int Arr [3][4] = { 12, 5 ,22, 84,
95, 3, 41, 59,
77, 6, 53, 62}

35
Two-Dimensional Array Illustration

36
Example
Write a program that initializes a two
dimensional array of 2 rows and 3 columns and
then displays its values

37
Solution
#include <iostream>
using namespace std;
int main ()
{
int i, j, arr[2][3] = {15, 21, 9, 84, 33, 72};
for (i=0; i <2; i++)
{
for (j=0; j <3; j++)
cout<<"arr["<<i<<"]["<<j<<"]="<<arr[i][j]<<"\t";
}
}
38
Example
• Write a program that initializes a two
dimensional array of 2 rows and 4 columns
and then displays minimum and maximum
number in the array

39
Solution
#include <iostream>
using namespace std;
int main ()
{
int i, j, max, min;
int arr[2][4] = {{15, 21, 9, 84}, {33, 72,18,47}};
max = min = arr[0][0];
for (i=0; i <2; i++)
{
for (j=0; j <4; j++)
{
if (arr[i][j] > max)
max = arr[i][j];
if (arr[i][j] < min)
min = arr[i][j];
}
}
cout<<"Maximum ="<<max<<endl<<"Minimum =" <<min<<endl;
}

40
Example
• Write a program that multiplies each element
of an array by 2 that has 3 rows and 2
columns. It displays the value in the form of
matrix. The array is initialized with the values
from 1 to 12.

41
Solution
#include <iostream>
using namespace std;
int main ()
{
int i, j;
int arr[3][4] = {{1, 2, 3, 4}, {5, 6,7,8}, {9, 10,11,12} };
for (i=0; i <3; i++)
{
for (j=0; j <4; j++)
{
cout<<arr[i][j]*2<<"\t";
}
cout<< endl;
}
}
42
Example
• Write a program that finds the sum of all
positive numbers in the given array:
• int arr[3] [4] = { {4, 18, -16, 11}, {-5, 10, -2, 12},
{15, -3, 17, 18}}

43
Solution
#include <iostream>
using namespace std;
int main ()
{
int x, y, sum =0;
int arr[3][4] = { {4, 18, -16, 11}, {-5, 10, -2, 12}, {15, -3, 17, 18}};
for (x=0; x <3; x++)
for (y=0; y <4; y++)
if (arr[x][y] > 0)
sum = sum + arr [x] [y];
cout<<"sum of positive numbers = "<<sum;
}
44
Functions and Arrays
• An array can be passed to a function as parameter
• When an array is passed as parameter to a
function, only the address of first element of the
array is passed
• An array is passed by reference not by value
• A separate copy of the array is not created in the
function,
• Syntax – return-type function-name (parameter[]);
• Example: void display ( int [] );
45
Calling a function
with array parameter
• A function with array parameter is called by giving
the name of the array as actual parameter.
• The index of the array is not used in function call.
• The name of the array refers to the memory
address of its first element.
• The memory address is passed to the function
• The function then access the array by using the
memory address.

46
Example
• Write a program that inputs five integers in an
array and passes the array to a function. The
function displays the value of the array.

47
Solution
#include <iostream>
using namespace std;
void show(int arr[]);
int main ()
{
int i, num[5];
cout<<"enter five integers= "<<endl;
for (i=0; i <5; i++)
cin>>num[i];
show(num);
}
void show(int arr[])
{
int j;
cout<<"the values in array are:\n "<<endl;
for (j=0; j <5; j++)
cout<<arr[j]<<"\t";
}

48
// C++ program to demonstrate passing of 2D Array with known
// number of rows and columns

#include <iostream>
using namespace std;

// function to print the array


void printArr(int arr[3][2])
{
// iterating through 2D array and printing elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main()
{

int arr[3][2] = { 10, 15, 20, 25, 30, 35 };

// calling print function by passing array with row and


// column size
printArr(arr);
49
return 0;
Passing individual Array element to
function
• Individual element of array can also be passed to
function.
• The datatype of array and the datatype of function
parameter must be same.
• The individual element is passed to a function like
sample variable
• Suppose a function is defined to accept an integer
parameter. It can accept an individual element of an
integer array in the same way as it can accept a
simple integer variable.
50
Example
• Write a program that inputs five integers in an
array. It passes all elements of the array to a
function one by one. The function displays the
actual value of the array.

51
Solution
#include <iostream>
using namespace std;
void square(int n);
int main ()
{
int i, num[5];
cout<<"enter five integers= "<<endl;
for (i=0; i <5; i++)
cin>>num[i];
for (i=0; i <5; i++)
square (num[i]);
}
void square(int n)
{
cout<<n<<"\t"<<n*n<<endl;
} 52
Solution
How the program works?
• The program inputs 5 integers in an array and
passes each element to function.
• The value in each element is passed to n.
• The function displays the original value and its
square on the screen.

53

You might also like