Arrays
Introduction
● An array is a contiguous group of memory locations that all have the
same type.
● Array can store multiple values of the same type.
● Elements of arrays can be accessed randomly using indices of an array.
Array Declaration
Syntax:
dataType arrayName[arraySize];
Example:
int x[6];
Here,
int - type of element to be stored
x - name of the array
6 - size of the array
Array Declaration
Array Initialization
In C++, it's possible to initialize an array during declaration.
Example:
int x[6] = {19, 10, 8, 17, 9, 15};
Access Elements in C++ Array
Each element in an array is associated with a number. The number is known
as an array index. We can access elements of an array by using those
indices.
Syntax:
array_name[index];
Access Elements in C++ Array
Access Elements in C++ Array
● The array indices start with 0. Meaning x[0] is the first element stored
at index 0.
● If the size of an array is n, the last element is stored at index (n-1). In
this example, x[5] is the last element.
● Elements of an array have consecutive addresses. For example,
suppose the starting address of x[0] is 2120d. Then, the address of the
next element x[1] will be 2124d, the address of x[2] will be 2128d and
so on. Here, the size of each element is increased by 4. This is because
the size of int is 4 bytes.
Array Declaration without size
● It is possible to declare array without specifying array size, in this way
In such cases, the compiler automatically computes the size.
For Example:
int x[] = {19, 10, 8, 17, 9, 15};
Array Declaration without elements
● It is possible to declare array without specifying it’s element
Int x[6]={ }
● In this way In such cases, the compiler will automatically fill the array
elements to 0.
Array With Some Empty Members
● In C++, if an array has a size n, we can store upto n number of elements
in the array. However, what will happen if we store less than n number
of elements.
● For example:
int x[6] = {19, 10, 8};
● Here, the array x has a size of 6. However, we have initialized it with
only 3 elements. In such cases, the compiler assigns random values to
the remaining places. Oftentimes, this random value is simply 0.
Access Elements in C++ Array
A sample Program to represent the usage of arrays
#include <iostream>
using namespace std;
int main() {
int mark[5] = {19, 10, 8, 17, 9};
//display the value of specific element
cout<<mark[0]<<endl;
//change value of specific element
mark[3] = 9;
// take input from the user
cin >> mark[2];
int i=5;
// take input from the user
// insert at ith position
cin >> mark[i-1];
// print ith element of the array
cout<<mark[i-1]<<endl;
//add value of two arrays
cout<<mark[4]+mark[3];
return 0;
}
Iterate Array using loop
#include <iostream>
using namespace std;
int main() {
int mark[5] = {19, 10, 8, 17, 9};
for( int i=0;i<5;i++)
{
cout<<mark[i]<<endl;
}
return 0;
}
19
10
8
17
9
OUTPUT
For each Loop
● Foreach loop is used to access elements of an array quickly without
performing initialization, testing and increment/decrement.
● The working of foreach loops is to do something for every element
rather than doing something n times.
Take input from user in array and show elements of array
#include <iostream>
using namespace std;
int main() {
int arr[5];
for( int i=0;i<5;i++)
{
cout<<"Enter a number:";
cin>>arr[i];
}
cout<<"The numbers are:";
for(int num : arr )
{
cout<<num<<endl;
}
return 0;
}
Enter a number:78
Enter a number:90
Enter a number:45
Enter a number:78
Enter a number:34
The numbers are:78
90
45
78
34
OUTPUT
Display Sum and Average of Array Elements Using for Loop
#include <iostream>
using namespace std;
int main() {
int numbers[] = {7, 5, 6, 12, 35, 27};
int sum = 0;
int count = 0;
double average;
cout << "The numbers are: ";
for (int n : numbers) {
cout << n << " ";
sum += n;
++count;
The numbers are: 7 5 6 12
35 27
Their Sum = 92
Their Average = 15.3333
OUTPUT
}
cout << "nTheir Sum = " << sum << endl;
average = sum /(double) count;
cout << "Their Average = " << average << endl;
return 0;
}
Array Out of Bounds
● If we declare an array of size 10, then the array will contain elements
from index 0 to 9.
● However, if we try to access the element at index 10 or more than 10, it
will result in Undefined Behaviour.
#include <iostream>
using namespace std;
int main() {
int numbers[] = {7, 5, 6, 12, 35, 27};
for(int i=0;i<10;i++)
{
cout<<numbers[i]<<" ";
}
return 0;
}
7 5 6 12 35 27 1 7
1774496 0
OUTPUT
Write a program that access array element out of bound
#include <iostream>
using namespace std;
int main() {
int responces;
int frequency_ctr[11]={0};
for(int i=0;i<40;i++)
{
cout<<"Enter your rating about food from 1-10:";
cin>>responces;
++frequency_ctr[responces];
}
Forty students were asked to rate the quality of the food in the student
cafeteria on a scale of 1 to 10 (1 means awful and 10 means excellent).
Place the 40 responses in an integer array and summarize the results of
the poll.
cout<<endl<<"RatingtFrequency"<<endl;
for(int rating=1; rating<11; rating++)
{
cout<<rating<<"t"<<frequency_ctr[rating]<<endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int responces;
int frequency_ctr[11]={0};
for(int i=0;i<40;i++)
{
cout<<"Enter your rating about food from 1-10:";
cin>>responces;
++frequency_ctr[responces];
}
cout<<endl<<"RatingtFrequencytBar Chart"<<endl;
Modify the program such that the frequency is represented with
bar chart.
for(int rating=1; rating<11; rating++)
{
cout<<rating<<"t"<<frequency_ctr[rating]<<"tt";
for(int i=0;i<frequency_ctr[rating];i++)
cout<<"*";
cout<<endl;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int i, n, max;
cout << "Enter total number of elements you want to enter: ";
cin >> n;
float arr[n];
cout << endl;
for(i = 0; i < n; ++i) {
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}
max=arr[0];
Write a program to find the largest element in the array
for(i = 1;i < n; ++i) {
if(arr[i]>max)
max = arr[i];
}
cout << endl << "Largest element = "<<max;
return 0;
}
Enter total number of
elements you want to enter:
5
Enter Number 1 : 78
Enter Number 2 : 568
Enter Number 3 : 346
Enter Number 4 : 986
Enter Number 5 : 457
Largest element = 986
OUTPUT
Sorting and Searching arrays
● Sorting:
Sorting is a process of placing the data in ascending or descending
order.
● Searching:
The process of finding a particular element of an array is called
searching.
Write a program in C++ to find an element in the array using
linear search
#include <iostream>
using namespace std;
# define SIZE 10
int main() {
int arr[10]={12, 67, 34, 89, 23, 45, 90, 123, 456, 32}, i, num;
cout << "Enter a number to search in Array:";
cin >> num;
for(i = 0; i < SIZE; i++){
if(arr[i] == num)
{
Enter a number to search in
Array:90
Element found at index: 6
OUTPUT
cout << "Element found at index: " << i;
break;
}
}
if(i == SIZE){
cout << "Element Not Present in Input Array.";
}
return 0;
}
Write a program in C++ to sort the array using Bubble sort.
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 12, 11, 13, 5, 6 }, temp, n=5;
for (int pass = 1; pass<n; pass++)
{
for(int i=0; i<n-1;i++)
{
if(arr[i]>arr[i+1])
Sorted array is: 5 6 11 12 13
OUTPUT
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
cout<<"Sorted array is: ";
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
}
Multi-Dimensional Array
● Arrays can be used with two dimensions (i.e., subscripts) to represent
tables of values consisting of information arranged in rows and
columns.
● To identify a particular table element, we must specify two subscripts—
the first identifies the element’s row and the second identifies the
element’s column.
Multi-Dimensional Array
● The general form of declaring N-dimensional arrays:
data_type array_name[size1][size2]....[sizeN];
data_type: Type of data to be stored in the array.
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions
2D Array
● Arrays that require two subscripts to identify a particular element are
called two-dimensional arrays or 2-D arrays.
● Syntax:
data_type array_name[x][y];
● We can find out the total number of elements in the array simply by
multiplying its dimensions:
2 x 4 x 3 = 24
2D Array
● For Example: int a[3][4];
2D Array
● Initializing a 2D Array:
int x[3][4] = {0,1,2,3, 4,5,6,7,8,9,10,11};
int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}};
● Accessing a 2D Array:
Elements in Two-Dimensional arrays are accessed using the row
indexes and column indexes.
Example:
x[2][1];
2D Array
● For Example: int a[3][4]={{4,7,8,9},{90,34,50,2},{12,56,87,30}};
Col 0 Col 1 Col 2 Col 3
Row 0 4 7 8 9
Row 1 90 34 50 2
Row 2 12 56 87 30
Write a program in C++ to access the element of 2-D array
#include <iostream>
using namespace std;
int main()
{
int x[3][2] = {{0,1}, {2,3}, {4,5}};
for (int i = 0; i < 3; i++)
{
cout<<"Row "<<i<<": ";
for (int j = 0; j < 2; j++)
{
cout<<x[i][j]<<" ";
}
cout<<endl;
}
}
Row 0: 0 1
Row 1: 2 3
Row 2: 4 5
OUTPUT
EXERCISE
1. Write a program that take 10 integer inputs from user and store them in an array.
Now, copy all the elements in another array but in reverse order.

Arrays_in_c++.pptx

  • 1.
  • 2.
    Introduction ● An arrayis a contiguous group of memory locations that all have the same type. ● Array can store multiple values of the same type. ● Elements of arrays can be accessed randomly using indices of an array.
  • 3.
    Array Declaration Syntax: dataType arrayName[arraySize]; Example: intx[6]; Here, int - type of element to be stored x - name of the array 6 - size of the array
  • 4.
  • 5.
    Array Initialization In C++,it's possible to initialize an array during declaration. Example: int x[6] = {19, 10, 8, 17, 9, 15};
  • 6.
    Access Elements inC++ Array Each element in an array is associated with a number. The number is known as an array index. We can access elements of an array by using those indices. Syntax: array_name[index];
  • 7.
  • 8.
    Access Elements inC++ Array ● The array indices start with 0. Meaning x[0] is the first element stored at index 0. ● If the size of an array is n, the last element is stored at index (n-1). In this example, x[5] is the last element. ● Elements of an array have consecutive addresses. For example, suppose the starting address of x[0] is 2120d. Then, the address of the next element x[1] will be 2124d, the address of x[2] will be 2128d and so on. Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.
  • 9.
    Array Declaration withoutsize ● It is possible to declare array without specifying array size, in this way In such cases, the compiler automatically computes the size. For Example: int x[] = {19, 10, 8, 17, 9, 15};
  • 10.
    Array Declaration withoutelements ● It is possible to declare array without specifying it’s element Int x[6]={ } ● In this way In such cases, the compiler will automatically fill the array elements to 0.
  • 11.
    Array With SomeEmpty Members ● In C++, if an array has a size n, we can store upto n number of elements in the array. However, what will happen if we store less than n number of elements. ● For example: int x[6] = {19, 10, 8}; ● Here, the array x has a size of 6. However, we have initialized it with only 3 elements. In such cases, the compiler assigns random values to the remaining places. Oftentimes, this random value is simply 0.
  • 12.
  • 13.
    A sample Programto represent the usage of arrays #include <iostream> using namespace std; int main() { int mark[5] = {19, 10, 8, 17, 9}; //display the value of specific element cout<<mark[0]<<endl; //change value of specific element mark[3] = 9; // take input from the user cin >> mark[2];
  • 14.
    int i=5; // takeinput from the user // insert at ith position cin >> mark[i-1]; // print ith element of the array cout<<mark[i-1]<<endl; //add value of two arrays cout<<mark[4]+mark[3]; return 0; }
  • 15.
    Iterate Array usingloop #include <iostream> using namespace std; int main() { int mark[5] = {19, 10, 8, 17, 9}; for( int i=0;i<5;i++) { cout<<mark[i]<<endl; } return 0; } 19 10 8 17 9 OUTPUT
  • 16.
    For each Loop ●Foreach loop is used to access elements of an array quickly without performing initialization, testing and increment/decrement. ● The working of foreach loops is to do something for every element rather than doing something n times.
  • 17.
    Take input fromuser in array and show elements of array #include <iostream> using namespace std; int main() { int arr[5]; for( int i=0;i<5;i++) { cout<<"Enter a number:"; cin>>arr[i]; }
  • 18.
    cout<<"The numbers are:"; for(intnum : arr ) { cout<<num<<endl; } return 0; } Enter a number:78 Enter a number:90 Enter a number:45 Enter a number:78 Enter a number:34 The numbers are:78 90 45 78 34 OUTPUT
  • 19.
    Display Sum andAverage of Array Elements Using for Loop #include <iostream> using namespace std; int main() { int numbers[] = {7, 5, 6, 12, 35, 27}; int sum = 0; int count = 0; double average; cout << "The numbers are: "; for (int n : numbers) { cout << n << " "; sum += n; ++count; The numbers are: 7 5 6 12 35 27 Their Sum = 92 Their Average = 15.3333 OUTPUT
  • 20.
    } cout << "nTheirSum = " << sum << endl; average = sum /(double) count; cout << "Their Average = " << average << endl; return 0; }
  • 21.
    Array Out ofBounds ● If we declare an array of size 10, then the array will contain elements from index 0 to 9. ● However, if we try to access the element at index 10 or more than 10, it will result in Undefined Behaviour.
  • 22.
    #include <iostream> using namespacestd; int main() { int numbers[] = {7, 5, 6, 12, 35, 27}; for(int i=0;i<10;i++) { cout<<numbers[i]<<" "; } return 0; } 7 5 6 12 35 27 1 7 1774496 0 OUTPUT Write a program that access array element out of bound
  • 23.
    #include <iostream> using namespacestd; int main() { int responces; int frequency_ctr[11]={0}; for(int i=0;i<40;i++) { cout<<"Enter your rating about food from 1-10:"; cin>>responces; ++frequency_ctr[responces]; } Forty students were asked to rate the quality of the food in the student cafeteria on a scale of 1 to 10 (1 means awful and 10 means excellent). Place the 40 responses in an integer array and summarize the results of the poll.
  • 24.
    cout<<endl<<"RatingtFrequency"<<endl; for(int rating=1; rating<11;rating++) { cout<<rating<<"t"<<frequency_ctr[rating]<<endl; } return 0; }
  • 25.
    #include <iostream> using namespacestd; int main() { int responces; int frequency_ctr[11]={0}; for(int i=0;i<40;i++) { cout<<"Enter your rating about food from 1-10:"; cin>>responces; ++frequency_ctr[responces]; } cout<<endl<<"RatingtFrequencytBar Chart"<<endl; Modify the program such that the frequency is represented with bar chart.
  • 26.
    for(int rating=1; rating<11;rating++) { cout<<rating<<"t"<<frequency_ctr[rating]<<"tt"; for(int i=0;i<frequency_ctr[rating];i++) cout<<"*"; cout<<endl; } return 0; }
  • 27.
    #include <iostream> using namespacestd; int main() { int i, n, max; cout << "Enter total number of elements you want to enter: "; cin >> n; float arr[n]; cout << endl; for(i = 0; i < n; ++i) { cout << "Enter Number " << i + 1 << " : "; cin >> arr[i]; } max=arr[0]; Write a program to find the largest element in the array
  • 28.
    for(i = 1;i< n; ++i) { if(arr[i]>max) max = arr[i]; } cout << endl << "Largest element = "<<max; return 0; } Enter total number of elements you want to enter: 5 Enter Number 1 : 78 Enter Number 2 : 568 Enter Number 3 : 346 Enter Number 4 : 986 Enter Number 5 : 457 Largest element = 986 OUTPUT
  • 29.
    Sorting and Searchingarrays ● Sorting: Sorting is a process of placing the data in ascending or descending order. ● Searching: The process of finding a particular element of an array is called searching.
  • 30.
    Write a programin C++ to find an element in the array using linear search #include <iostream> using namespace std; # define SIZE 10 int main() { int arr[10]={12, 67, 34, 89, 23, 45, 90, 123, 456, 32}, i, num; cout << "Enter a number to search in Array:"; cin >> num; for(i = 0; i < SIZE; i++){ if(arr[i] == num) { Enter a number to search in Array:90 Element found at index: 6 OUTPUT
  • 31.
    cout << "Elementfound at index: " << i; break; } } if(i == SIZE){ cout << "Element Not Present in Input Array."; } return 0; }
  • 32.
    Write a programin C++ to sort the array using Bubble sort. #include <iostream> using namespace std; int main() { int arr[] = { 12, 11, 13, 5, 6 }, temp, n=5; for (int pass = 1; pass<n; pass++) { for(int i=0; i<n-1;i++) { if(arr[i]>arr[i+1]) Sorted array is: 5 6 11 12 13 OUTPUT
  • 33.
  • 34.
    Multi-Dimensional Array ● Arrayscan be used with two dimensions (i.e., subscripts) to represent tables of values consisting of information arranged in rows and columns. ● To identify a particular table element, we must specify two subscripts— the first identifies the element’s row and the second identifies the element’s column.
  • 35.
    Multi-Dimensional Array ● Thegeneral form of declaring N-dimensional arrays: data_type array_name[size1][size2]....[sizeN]; data_type: Type of data to be stored in the array. array_name: Name of the array size1, size2,... ,sizeN: Sizes of the dimensions
  • 36.
    2D Array ● Arraysthat require two subscripts to identify a particular element are called two-dimensional arrays or 2-D arrays. ● Syntax: data_type array_name[x][y]; ● We can find out the total number of elements in the array simply by multiplying its dimensions: 2 x 4 x 3 = 24
  • 37.
    2D Array ● ForExample: int a[3][4];
  • 38.
    2D Array ● Initializinga 2D Array: int x[3][4] = {0,1,2,3, 4,5,6,7,8,9,10,11}; int x[3][4] = {{0,1,2,3}, {4,5,6,7}, {8,9,10,11}}; ● Accessing a 2D Array: Elements in Two-Dimensional arrays are accessed using the row indexes and column indexes. Example: x[2][1];
  • 39.
    2D Array ● ForExample: int a[3][4]={{4,7,8,9},{90,34,50,2},{12,56,87,30}}; Col 0 Col 1 Col 2 Col 3 Row 0 4 7 8 9 Row 1 90 34 50 2 Row 2 12 56 87 30
  • 40.
    Write a programin C++ to access the element of 2-D array #include <iostream> using namespace std; int main() { int x[3][2] = {{0,1}, {2,3}, {4,5}}; for (int i = 0; i < 3; i++) { cout<<"Row "<<i<<": "; for (int j = 0; j < 2; j++) { cout<<x[i][j]<<" "; } cout<<endl; } } Row 0: 0 1 Row 1: 2 3 Row 2: 4 5 OUTPUT
  • 41.
    EXERCISE 1. Write aprogram that take 10 integer inputs from user and store them in an array. Now, copy all the elements in another array but in reverse order.