0% found this document useful (0 votes)
37 views20 pages

Arrays (1D, 2D, 3D)

Uploaded by

atiq.rehman1105
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)
37 views20 pages

Arrays (1D, 2D, 3D)

Uploaded by

atiq.rehman1105
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/ 20

Lab Manual: Programming Fundamentals

University of Management and Technology,


Lahore Campus

Lab- 03 Manual
Lab Instructor: Riaz Ahmad
Department of Computer Science
Email: [email protected]
Lab 03: 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

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 1


Lab Manual: Programming Fundamentals

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.

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:

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 2


Lab Manual: Programming Fundamentals
0 1 4 9 16 25 36 49

[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
sum += x[2]; adds x[2] to sum. The new sum is 34.0
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])
cout<<x[2*i]; Invalid index. Attempt to display x[10]

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 3


Lab Manual: Programming Fundamentals

4. Examples

Example 1: 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 n[5]; // n is an array of 5 integers int i;
int i;
for (i = 0; i < 5; i++ )
{
cout<<"Please enter the element number "<<i+1<<": ";
cin>>n[i];
}
cout<<endl;
// output each array element's value
for (i = 0; i < 5; i++ )
{
cout<<"Element stored at index "<<i<< " is: "<<[i]<<endl;
}
return 0;
The output of the program is:

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 4


Lab Manual: Programming Fundamentals

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


#include<iostream>
using namespace std;
int main()
{
int n[5];
int i, sum = 0;
for (i = 0; i < 5; i++ )
{
cout<<"Please enter the element number "<<i+1<<": ";
cin>>n[i];
}
cout<<endl;
for (i = 0; i < 5; i++ )
{
sum = sum + n[i];
}
cout<<"Sum of array elements is "<<sum<<endl;
return 0;
}
The output of the program is:

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 5


Lab Manual: Programming Fundamentals

Example 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.

#include<iostream>
using namespace std;

int main()
{
int A[] = {99,89,79,69,59};
int B[5], i;
for (i = 0; i < 5; i++)
{
B[i] = A[i];
cout<<"A["<<i<<"] = " <<A[i]<<", ";
cout<<"B["<<i<<"] = " <<B[i]<<", "<<endl;
}
return 0;
}

The output of the program is:

Example 4: Write a program that takes an integer value from user and search it in array, If

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 6


Lab Manual: Programming Fundamentals
found then display message ‘Number Found’ else ‘Number Not Found.

#include <iostream>
using namespace std;
int main(){
int input[100], count, i, num;
cout << "Enter Number of Elements in Array\n";
cin >> count;
cout << "Enter " << count << " numbers \n";
// Read array elements
for(i = 0; i < count; i++)
{
cin >> input[i];
}
cout << "Enter a number to serach in Array\n";
cin >> num;
// search num in inputArray from index 0 to elementCount-1
for(i = 0; i < count; i++)
{
if(input[i] == num)
{
cout << "Element found at index " << i+1;
break;
}
}
if(i == count)
{
cout << "Element Not Present in Input Array\n";
}

return 0;
}

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 7


Lab Manual: Programming Fundamentals
Example 5: Write a Program that finds maximum number in an array

#include <iostream>
using namespace std;

int main() {
int i, n;
float arr[100];
cout << "Enter total number of elements(1 to 100): ";
cin >> n;
cout << endl;
// Store number entered by the user
for(i = 0; i < n; ++i) {
cout << "Enter Number " << i + 1 << " : ";
cin >> arr[i];
}
// Loop to store largest number to arr[0]
for(i = 1;i < n; ++i)
{
// Change < to > if you want to find the smallest element
if(arr[0] < arr[i])
arr[0] = arr[i];
}
cout << endl << "Largest element = " << arr[0];
return 0;
}
The output of the program is:

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 8


Lab Manual: Programming Fundamentals

5. Exercises for lab


Exercise 1:

Write a program that declares an array of 5 double 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.

Exercises 2:

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

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

10.2 Home Work


1. Write a program to search a value in an array. Your program should also notify:
a) Index of the array where value found
b) Number of times the value was found in array

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 9


Lab Manual: Programming Fundamentals

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?

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 10


Lab Manual: Programming Fundamentals
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
[1] 3 4 5
[2] 6 7 8

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

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 11


Lab Manual: Programming Fundamentals

 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];
}
}

 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])
{
// ...
}
Linear Search
#include<iostream>
using namespace std;

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 12


Lab Manual: Programming Fundamentals
int main()
{
int arr[10], i, num, index;
cout<<"Enter 10 Numbers: ";
for(i=0; i<10; i++)
cin>>arr[i];
cout<<"\nEnter a Number to Search: ";
cin>>num;
for(i=0; i<10; i++)
{
if(arr[i]==num)
{
index = i;
break;
}
}
cout<<"\nFound at Index No."<<index;
cout<<endl;
return 0;
}

4. Examples
Example 11.1: A program to input elements in a two dimensional array and print it.
#i#include <iostream>
using namespace std;
int main()
{
int a[3][3]; int i,j;
cout<<"enter nine elements in the array:";
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 13


Lab Manual: Programming Fundamentals
cin>>a[i][j];
}
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
cout<<a[i][j]<<" ";
cout<<"\n";
}
return 0;
}

The output of the program is

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 14


Lab Manual: Programming Fundamentals

Example 11.2: Write a program that will add two matrixes entered by the user
and print it.
#include <iostream>
using namespace std;
int main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
cout<<"enter nine elements of a 3X3 Matrix A:";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cin>>a[i][j];
}
cout<<"enter nine elements of a 3X3 Matrix B:";
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cin>>b[i][j];
}
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
c[i][j]=a[i][j]+b[i][j];
cout<<c[i][j]<<" ";
}
cout<<"\n";
}

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 15


Lab Manual: Programming Fundamentals
return 0;
}

The output of the program is:

Example 11.3: A program to input a matrix and print its transpose.

#include <iostream>
using namespace std;
int main()
{
int a[3][3];
int i,j;

cout<<"Enter nine elements of a 3X3 Matrix :";


for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
cin>>a[i][j];
}
cout<<"Original 3X3 Matrix is:"<<endl;
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
cout<<"Transposed 3X3 Matrix is:"<<endl;
for(i=0 ; i<3 ; i++)
{
for(j=0 ; j<3 ; j++)
{
cout<<a[j][i]<<" ";
}
cout<<"\n";

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 16


Lab Manual: Programming Fundamentals
}
return 0;
}
The output of the program is:

Example: Passing One-dimensional Array to a Function

// C++ Program to display marks of 5 students

#include <iostream>
using namespace std;

// declare function to display marks


// take a 1d array as parameter
void display(int m[5]) {
cout << "Displaying marks: " << endl;

// display array elements


for (int i = 0; i < 5; ++i) {
cout << "Student " << i + 1 << ": " << m[i] << endl;
}
}

int main() {

// declare and initialize an array


int marks[5] = {88, 76, 90, 61, 69};

// call display function


// pass array as argument
display(marks);

return 0;
}

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 17


Lab Manual: Programming Fundamentals
Example 11.4: Passing multi-dimensional array to a function.
#include <iostream>
using namespace std;

void Function(int x[2][2]);


int main()
{
int c[2][2],i,j;
cout<<"Enter four elements of a 2X2 Matrix :";
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
cin>>c[i][j];
}
cout<<"Original 2X2 Matrix is:"<<endl;

for(i=0 ; i<2 ; i++)


{
for(j=0 ; j<2 ; j++)
{
cout<<c[i][j]<<" ";
}
cout<<"\n";
}
Function(c); // passing multi-dimensional array to
function
return 0;
}

void Function(int g[2][2])

{ // void Function(int c[][2]){ is also valid


cout<<"Received 2X2 Matrix is:"<<endl;
int i,j;
for(i=0 ; i<2 ; i++)
{
for(j=0 ; j<2 ; j++)
{
cout<<g[i][j]<<" ";

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 18


Lab Manual: Programming Fundamentals
}
cout<<"\n";
}
}
The output of the program is:

Example: Three-Dimensional Array


#include <iostream>

using namespace std;

int main( )

int Array[2][2][4];

cout << "Please enter 16 values of your choice: \n";

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

for (int j = 0; j < 2; j++)

for(int k = 0; k < 4; k++ )

cin >> Array[i][j][k];

cout<<"\n Below are the values you have stored in the array"<< endl;

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

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 19


Lab Manual: Programming Fundamentals
{

for (int j = 0; j < 2; j++)

for(int k = 0; k < 4; k++)

cout << "[" << i << "][" << j << "][" << k << "] =" <<Array[i][j][k] << endl;

5. Exercises for lab


Exercise 10.1 Declare and initialize a 2D arrays with different methods.
Exercise 10.2 Multiply two matrices and store result in third matric.
Exercise 10.3 Write a program that will sort 2d array in ascending order and descending order
(using function).
Exercise 10.4 A program to input a matrix and find its determent (by using function).

6. Home Work
1. A program to input a matrix and find its inverse (using function).
2. A program to input a matrix and find its singular or non-singular (using function).

Department of Computer Science, UMT, Lahore. Riaz Ahmad Page # 20

You might also like