0% found this document useful (0 votes)
26 views

Lab Manual 02 - Arrays (1D, 2D)

Uploaded by

f2023065259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Lab Manual 02 - Arrays (1D, 2D)

Uploaded by

f2023065259
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

University of Management and Technology,

Lahore
Lab Manual: Data Campus
Structures and Algorithm

Lab- 02 Manual
Lab Instructor: Sameer Ahmed
Department of Software Engineering
Email: [email protected]
Lab 02:
Arrays
1. Objective:
Learn how to declare, initialize and use one-dimensional arrays.
2. Scope:
The student should know the following:
1. Syntax of array declaration
2. assigning and processing and elements

3. Useful Concepts:
An array is a collection of two or more adjacent memory cells, called array elements that are
associated with a particular symbolic name. Arrays are very useful construct to store related
values together instead of declaring several variables for each value.
To set up an array in memory, we must declare both the name of the array and the number of
cells associated with it.
The following declaration will instruct the compiler to allocate eight memory cells with the
name x; these memory cells will be adjacent to each other. Each element may contain a value of
type double. double x[8];
x

0 1 2 3 4 5 6 7

As you can see; the name of the array x points to the first element of the array. We can define a
constant for array size and use it whenever we declare an array.
Lab Manual: Data Structures and Algorithm

const int NUM_STUDENTS


= 8; int
id[NUM_STUDENTS];
double
gpa[NUM_STUDENTS];

To access the data stored in an array, we reference each individual element by specifying the
array name and identifying the element desired.
x[0] the value of the first element
x[3] the value of the fourth element
x[7] the value of the eighth element
NOTE: The indices of the elements start from zero, not from one.
Array initialization:
We can initialize an array directly by specifying each cell value individually as follows:
double values [] = {12.5,17.9,23.5,-2.5,115.75,-55.3};
Hence here we do not need to specify the size of the array or how many elements this array
should have. This number can be deduced from the initialization list.

We can also use for loop which is the common way to deal with arrays in general. The following
code initializes array square to squares of the indices:

int square [8], i;

for (i=0;i<8;++i)
square[i] = i *
i;

The array square will be like this after the loop:

0 1 4 9 16 25 36 49
Lab Manual: Data Structures and Algorithm

[0] [1] [2] [3] [4] [5] [6] [7]

Array Processing:
Elements of the array are dealt as normal variables, the only difference here is to specify
the index desired. These statements are examples of using array elements:

16.0 12.0 28.0 26.0 2.5 12.0 14.0 -54.5

x[0] x[1] x[2] x[3] x[4] x[5] x[6] x[7]

cout<< x[0]; display the value of x[0], which is 16.0

x[3] = 25.0; stores the value 25.0 in x[3]


sum = x[0] + x[1]; stores the sum of x[0] and x[1], which is 28.0
in the variable sum
x[3] += 1.0; increments x[3] by 1
x[2] = x[0] + x[1]; stores the sum of x[0] and x[1] in x[2]
Now the new x[2] is 28.0
We can apply any expression to specify the index as well. Consider these statements:
i = 5;
cout<< x[i+1]; display 14.0 (value of x[6])
x[i-1] = x[i]; assigns 12.0 (value of x[5]) to x[4]
cout<<x[i++]; display 12.0 (value of x[5])
Invalid index. Attempt to display x[10]

1D dynamic array
#include <iostream>
Lab Manual: Data Structures and Algorithm

int main() {
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;

// Dynamically allocate memory for a 1D array


int* arr = new int[size];

// Input elements
std::cout << "Enter " << size << " elements: ";
for(int i = 0; i < size; i++) {
std::cin >> arr[i];
}

// Display elements
std::cout << "Array elements: ";
for(int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;

// Free the allocated memory


delete[] arr;

return 0;
}

Searching in 1D Arrays
#include <iostream>

int linearSearch(int arr[], int size, int key) {


for(int i = 0; i < size; i++) {
if(arr[i] == key) {
return i; // Return the index if the key is found
}
}
return -1; // Return -1 if the key is not found
}

int main() {
int size, key;
std::cout << "Enter the size of the array: ";
std::cin >> size;

int* arr = new int[size];


Lab Manual: Data Structures and Algorithm

std::cout << "Enter " << size << " elements: ";
for(int i = 0; i < size; i++) {
std::cin >> arr[i];
}

std::cout << "Enter the element to search for: ";


std::cin >> key;

int result = linearSearch(arr, size, key);


if(result != -1) {
std::cout << "Element found at index: " << result <<
std::endl;
} else {
std::cout << "Element not found" << std::endl;
}

delete[] arr; // Free the allocated memory

return 0;
}

Two Dimensional Arrays


1. Objective:

Learn how to declare, assign and manipulate two dimensions array.


2. Scope:

The student should know the following:


1. What is 2-D array?
2. Declaring 2-D arrays and bound checking.
3. Storing data in 2-D arrays and printing.
4. Passing 2-D arrays to functions.

3. Useful Concepts:

What is 2-D Array?


Just like single dimensional arrays we can have multidimensional arrays which are
arrays of arrays. The multidimensional arrays can be visualized as a matrix.

[0] [1] [2]


[0] 1 2 3
3 4 5
6 7 8
Lab Manual: Data Structures and Algorithm

[1]
[2]

General representation of 2-D Array

How to declare and initialize two multidimensional Array?


int myarray[2][3];
The name of the array to be “myarray”, type of the array elements to be “int”, dimension to be 2 (two
pairs of brackets []). The number of elements or size to be 2*3 = 6.

Array type Array name Array dimensions=2

int myarray[2][3] = {(51, 52, 53),(54, 55, 56)};

Two Rows Three Columns First Row Second Row

We can also write


int b[2][3] = {51, 52, 53, 54, 55, 56};

Or
b[0][0] = 51; b[0][1] = 52; b[0][2] = 53; b[1][0] =
54; b[1][1] = 55; b[1][2] = 56;
or
int b[][3] = {{51, 52, 53}, {54, 55, 56}};

Storing and printing data in 2-D arrays


• A nested for loop is used to input elements in a two dimensional array.
• In this way by increasing the index value of the array the elements can be entered in a 2d
array

for(int i=0 ; i<3 ; i++)


{ for(int j=0 ; j<3 ; j++)
{ cin<a[i][j];
}
}
Lab Manual: Data Structures and Algorithm

• The output of two-dimensional arrays should be in the form of rows and columns for
readability. Nested for loops are used to print the rows and columns in row and column
order.
• By increasing the index value of the array the elements stored at that index value are printed
on the output screen.

for(int i=0 ; i<3 ; i++)


{ for(int j=0 ; j<3 ; j++)
{ cout<<a[i][j];
} cout<<endl;
}

Passing 2-D arrays to function:


// Function Call

int array[10][10];
passFunc(array)

;
// Function Definition

void passFunc(int a[][10])


{
// ...

2D dynamic Arrays
#include <iostream>

int main() {
int rows, cols;
std::cout << "Enter the number of rows and columns: ";
std::cin >> rows >> cols;

// Dynamically allocate memory for a 2D array


int** arr = new int*[rows]; // Allocate memory for rows
for(int i = 0; i < rows; i++) {
arr[i] = new int[cols]; // Allocate memory for columns in each row
}

// Input elements
Lab Manual: Data Structures and Algorithm

std::cout << "Enter elements for the 2D array: \n";


for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
std::cin >> arr[i][j];
}
}

// Display elements
std::cout << "2D Array elements:\n";
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}

// Free the allocated memory


for(int i = 0; i < rows; i++) {
delete[] arr[i]; // Free each row
}
delete[] arr; // Free the row pointers

return 0;
}

Searching in2D Arrays


#include <iostream>

bool search2DArray(int** arr, int rows, int cols, int key) {


for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(arr[i][j] == key) {
std::cout << "Element found at position: (" << i << ", " << j << ")\n";
return true;
}
}
}
return false;
}

int main() {
int rows, cols, key;
std::cout << "Enter the number of rows and columns: ";
std::cin >> rows >> cols;
Lab Manual: Data Structures and Algorithm

int** arr = new int*[rows];


for(int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}

std::cout << "Enter elements for the 2D array: \n";


for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
std::cin >> arr[i][j];
}
}

std::cout << "Enter the element to search for: ";


std::cin >> key;

if(!search2DArray(arr, rows, cols, key)) {


std::cout << "Element not found\n";
}

// Free the allocated memory


for(int i = 0; i < rows; i++) {
delete[] arr[i];
}
delete[] arr;

return 0;
}

4. Task

Example: Write a program that contains an array of five elements, take five values from user,
assign the value to each element of array and display the all array elements.

#include <iostream> using


namespace std;

int main() {
int arr[5];

// Taking input from the user


cout << "Enter 5 values: " << endl;
Lab Manual: Data Structures and Algorithm

for (int i = 0; i < 5; i++)


{ cin >> arr[i];

// Displaying the values


cout << "Array elements are: ";
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";

}
return 0;

2: Write a C++ program that adds all elements of array.


3: Suppose there are two arrays of the same size. Array A consists of five elements while array B
in not initialized yet. Write a program that copies the values of A into B. Verify your code by
displaying the contents of B.

4: Write a program that takes an integer value from user and search it in array, If found then
display message ‘Number Found’ else ‘Number Not Found. 5: Write a Program that finds
maximum number in an array
6: Write a program that declares an array of 5 numbers. Use a loop to read 5 real numbers from
user and fill the array. Then print the following on screen:

a. All the elements of array


b. The average of all the numbers in the array
c. The numbers below average
d. The numbers above average.

7: Consider the following list of student’s grade

64 36 56 47 40 54 61 60 58 64 54

48 59 45 63 54 50 49 51 60 58 59
Lab Manual: Data Structures and Algorithm

Initialize an array with above grades and find the following things about the above data.

a. The minimum grade


b. The maximum grade
c. Average

4. Task

1. A program to input elements in a two dimensional array and print it.


2. Write a program that will add two matrixes entered by the user and print it.
3. A program to input a matrix and print its transpose.

You might also like