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

Unit - 4 Array (28th March 2025)

Uploaded by

Tanishqa Mishra
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)
16 views14 pages

Unit - 4 Array (28th March 2025)

Uploaded by

Tanishqa Mishra
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/ 14

Unit-IV

Unit-IV syllabus : Arrays-Introduction to Arrays- Declaration of Arrays-


Different Types of Arrays: One Dimensional Array, Two Dimensional
Array. Array Examples on Variables–Array Examples on Constants.

1
C++ Arrays

Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type, specify the name of the array

followed by square brackets and specify the number of elements it should


store:

string cars[4];

We have now declared a variable that holds an array of four strings. To insert
values to it, we can use an array literal - place the values in a comma-separated
list, inside curly braces:
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of three integers, you could write:

int myNum[3] = {10, 20, 30};

In below example : This statement accesses the value of the first


element in cars:

string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

cout << cars[0];


// Outputs Volvo

Note: Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

Int marks[500]

An array is a collection of similar items stored in contiguous memory locations.


In programming, sometimes a simple variable is not enough to hold all the data.
For example, lets say we want to store the marks of 500 students, having 500
different variables for this task is not feasible, we can define an array with size
500 that can hold the marks of all students.

2
Declaring an array in C++

There are couple of ways to declare an array.


Method 1:

int arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

Method 2:
int arr[] = {10, 20, 30, 40, 50};

Method 3:
int arr[5] = {10, 20, 30, 40, 50, 60};

Accessing Array Elements

You access an array element by referring to the index number.

Array index starts with 0, which means the first array element is at index 0,
second is at index 1 and so on. We can use this information to display the array
elements. See the code below:

3
#include <iostream>
using namespace std;

int main(){
int arr[] = {11, 22, 33, 44, 55};
cout<<arr[0]<<endl;
cout<<arr[1]<<endl;
cout<<arr[2]<<endl;
cout<<arr[3]<<endl;
cout<<arr[4]<<endl;
return 0;
}
Output:

11
22
33
44
55
Although this code worked fine, displaying all the elements of array like this is
not recommended. When you want to access a particular array element then this
is fine but if you want to display all the elements then you should use a loop like
this:

#include <iostream>
using namespace std;

int main(){
int arr[] = {11, 22, 33, 44, 55};

int n=0;

while(n<=4){
cout<<arr[n]<<endl;
n++;(n=n+1)
}
return 0;
}

4
Change an Array Element

To change the value of a specific element, refer to the index number:

Example
cars[0] = "Opel";

Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo

C++ Arrays and Loops

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the cars array:

Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};

for(int i = 0; i < 4; i++) {


cout << cars[i] << "\n";
}

The following example outputs the index of each element together with its
value:

Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
for(int i = 0; i < 4; i++) {
cout << i << ": " << cars[i] << "\n";
}

5
Omit Array Size

You don't have to specify the size of the array. But if you don't, it will only be
as big as the elements that are inserted into it:

string cars[] = {"Volvo", "BMW", "Ford"}; // size of array is always 3

This is completely fine. However, the problem arise if you want extra space for
future elements. Then you have to overwrite the existing values:

string cars[] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

If you specify the size however, the array will reserve the extra space:

string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even though


it's only three elements inside it

Now you can add a fourth and fifth element without overwriting the others:

cars[3] = "Mazda";
cars[4] = "Tesla";

Omit Elements on Declaration

It is also possible to declare an array without specifying the elements on


declaration, and add them later:

string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...

6
Two dimensional array

Lets see how to declare, initialize and access Two Dimensional Array elements.

How to declare a two dimensional array?

int myarray[2][3];

Initialization:
We can initialize the array in many ways:

Method 1:

int arr[2][3] = {10, 11 ,12 ,20 ,21 , 22};


arr[0][0] =10
arr[0][1]=11
arr[0][2]=12
arr[1][0]=20
arr[1][1]=21
arr[1][2]=22
Colum (0) column (1) column (2)
Row (0) 00 A 01 B 02 C

Row(1) 10 D 11 E 12 F

Method 2:
This way of initializing is preferred as you can visualize the rows and columns
here.

int arr[2][3] = {{10, 11 ,12} , {20 ,21 , 22}};

Accessing array elements:


arr[0][0] – first element
arr[0][1] – second element
arr[0][2] – third element
arr[1][0] – fourth element
arr[1][1] – fifth element
arr[1][2] – sixth element

7
Example: Two dimensional array in C++

#include <iostream>
using namespace std;

int main(){
int arr[2][3] = {{11, 22, 33}, {44, 55, 66}};
for(int i=0; i<2;i++){
for(int j=0; j<3; j++){
cout<<"arr["<<i<<"]["<<j<<"]: "<<arr[i][j]<<endl;
}
}
return 0;
}

Output:

arr[0][0]: 11
arr[0][1]: 22
arr[0][2]: 33
arr[1][0]: 44
arr[1][1]: 55
arr[1][2]: 66

Difference Between one-dimensional and two-dimensional array

Array is a data structure that is used to store variables that are of similar data
types at contiguous locations. The main advantage of the array is random access
and cache friendliness. There are mainly three types of the array:
One Dimensional (1D) Array
Two Dimension (2D) Array

One Dimensional Array:


• It is a list of the variable of similar data types.
• It allows random access and all the elements can be accessed with the
help of their index.
• The size of the array is fixed.
• For a dynamically sized array, vector can be used in C++.
• Representation of 1D array:

8
Two Dimensional Array:
• It is a list of lists of the variable of the same data type.
• It also allows random access and all the elements can be accessed with
the help of their index.
• It can also be seen as a collection of 1D arrays. It is also known as the
Matrix.
• Its dimension can be increased from 2 to 3 and 4 so on.
• They all are referred to as a multi-dimension array.
• The most common multidimensional array is a 2D array.
• Representation of 2 D array:

Difference Table: between one dimension and Two Dimension Array:

Basis One Dimension Array Two Dimension Array


Definition Store a single list of the Store a ‘list of lists’ of the element
element of a similar of a similar data type.
data type.
Representatio Represent multiple data Represent multiple data items as a
n items as a list. table consisting of rows and
columns.
Declaration The declaration varies The declaration varies for different
for different programing language:
programing language: For C++,
For C++, datatype
datatype variable_name[capacity1][capacit
variable_name[capacit y2]
9
y]
Dimension One Two
Size(bytes) size of(datatype of the size of(datatype of the variable of
variable of the array) * the array)* the number of rows*
size of the array the number of columns.
Address Address of a[index] is Address of a[i[[j] can be calculated
calculation. equal to (base in two ways row-major and
Address+ Size of each column-major
element of array * 1. Column Major: Base
index). Address + Size of each
element (number of
rows(j-lower bound of the
column)+(i-lower bound
of the rows))
2. Row Major: Base
Address + Size of each
element (number of
columns(i-lower bound of
the row)+(j-lower bound
of the column))

Applications of Arrays:
• 2D Arrays are used to implement matrices.
• Arrays can be used to implement various data structures like
a heap, stack, queue, etc.
• They allow random access.
• They are cache-friendly.

10
A Simple C++ program to add two Matrices

Here we are asking user to input number of rows and columns of matrices and
then we ask user to enter the elements of both the matrices, we are storing the
input into a multidimensional array for each matrix and after that we are adding
corresponding elements of both the matrices and displaying them on screen.

#include<iostream>
using namespace std;

int main()
{
int row, col, m1[10][10], m2[10][10], sum[10][10];

cout<<"Enter the number of rows(should be >1 and <10): ";


cin>>row;
cout<<"Enter the number of column(should be >1 and <10): ";
cin>>col;
cout << "Enter the elements of first 1st matrix: ";
for (int i = 0;i<row;i++ ) {
for (int j = 0;j < col;j++ ) {
cin>>m1[i][j];
}
}
cout << "Enter the elements of first 1st matrix: ";
for (int i = 0;i<row;i++ ) {
for (int j = 0;j<col;j++ ) {
cin>>m2[i][j];
}
}

cout<<"Output: ";
for (int i = 0;i<row;i++ ) {
for (int j = 0;j<col;j++ ) {
sum[i][j]=m1[i][j]+m2[i][j];
cout<<sum[i][j]<<" ";
}
}

return 0;
}

11
Output:

Enter the number of rows(should be >1 and <10): 2


Enter the number of column(should be >1 and <10): 3
Enter the elements of first 1st matrix: 1 2 3 4 5 6
Enter the elements of first 1st matrix: 5 5 5 5 5 5
Output: 6 7 8 9 10 11

#include <iostream>
using namespace std;
int main(){
float percentage[4];
percentage[0] = 56.3;
percentage[1] = 99.12;
percentage[2] = 78.32;
percentage[3] = 61.3;
cout<<"3rd element is "<<percentage[2];
return 0;
}

Output
3rd element is 78.32

12
Example 2: Take Inputs from User and Store Them in an Array

#include <iostream>
using namespace std;

int main() {
int numbers[5];

cout << "Enter 5 numbers: " << endl;


// store input from user to array
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}
cout << "The numbers are: ";
// print array elements
for (int n = 0; n < 5; ++n) {
cout << numbers[n] << " ";
}
return 0;

Example 3: Display Sum and Average of Array Elements Using for Loop

#include <iostream>
using namespace std;

int main() {

// initialize an array without specifying size


double numbers[] = {7, 5, 6, 12, 35, 27};

double sum = 0;
double count = 0;
double average;
cout << "The numbers are: ";
// print array elements
// use of range-based for loop
for (const double &n : numbers) {
cout << n << " ";

13
// calculate the sum
sum += n;

// count the no. of array elements


++count;
}
// print the sum
cout << "\nTheir Sum = " << sum << endl;

// find the average


average = sum / count;
cout << "Their Average = " << average << endl;

return 0;
}

Output

The numbers are: 7 5 6 12 35 27


Their Sum = 92
Their Average = 15.3333

14

You might also like