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

DS Lab 1 - Arrays (Static, Dynamic and Multi-Dimensional)

This document provides an introduction to arrays in C++. It discusses static arrays, dynamic memory allocation, and multi-dimensional arrays. The document contains sections on basic concepts, array initialization and access, static versus dynamic arrays, and multi-dimensional arrays up to three dimensions.

Uploaded by

Asim Shareef
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)
28 views

DS Lab 1 - Arrays (Static, Dynamic and Multi-Dimensional)

This document provides an introduction to arrays in C++. It discusses static arrays, dynamic memory allocation, and multi-dimensional arrays. The document contains sections on basic concepts, array initialization and access, static versus dynamic arrays, and multi-dimensional arrays up to three dimensions.

Uploaded by

Asim Shareef
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/ 15

Department of Computer Science, Faculty of Computing

International Islamic University, Islamabad

Lab Manual for Data Structures


Lab-1
Development of Arrays (Static, Dynamic and Multi-
dimensional) in C++
Lab 1: Development of Arrays

Table of Contents
1. Introduction............................................................................................................................................................3
1.1. Basic Concepts about Data Structures...................................................................................................................3
1.2. Arrays in C++........................................................................................................................................................3
1.3. Dynamic Memory Allocation................................................................................................................................4
1.4. Multi-Dimensional Arrays.....................................................................................................................................4
1.5. Relevant Lecture Readings....................................................................................................................................4
2. Activity Time boxing.............................................................................................................................................4
3. Objectives of the experiment.................................................................................................................................5
4. Concept Map..........................................................................................................................................................5
4.1. Arrays in C++........................................................................................................................................................5
4.2. Initializing Arrays..................................................................................................................................................6
4.3. Accessing values from an array.............................................................................................................................6
4.4. Static Arrays..........................................................................................................................................................6
4.5. Dynamic Memory Allocation in C++....................................................................................................................7
4.6. Multi-Dimensional Arrays.....................................................................................................................................8
4.6.1. Two Dimensional Arrays in C++...........................................................................................................................9
4.6.2. Three Dimensional Arrays in C++.......................................................................................................................10
5. Homework before Lab.........................................................................................................................................10
5.1. Problem Solution Modeling.................................................................................................................................10
5.2. Problem description:............................................................................................................................................11
6. Procedures & Tools.............................................................................................................................................11
6.1. Tools....................................................................................................................................................................11
6.2. Editing, Compiling and Running programs in Visual Studio 2017[Expected time = 5mins].............................11
6.3. Walk through Task [Expected time = 20mins]................................................................................................11
7. Practice Tasks......................................................................................................................................................14
7.5. Out comes............................................................................................................................................................14
8. Evaluation Task (Unseen) [Expected time = 60mins for two tasks]................................................................14
9. Evaluation criteria................................................................................................................................................15
10. Further Readings..................................................................................................................................................15
10.1. C++ Tutorial Web Sites.......................................................................................................................................15
10.2. Web sites containing supporting material............................................................................................................15

Department of Computer Science Page 2


IIUI, Islamabad
Lab 1: Development of Arrays

Lab 01: Development of Arrays

1. Introduction

Objective of this lab is to provide you knowledge about development of arrays in C++. You have
come to know about the basic concepts about C++ language in courses: Computer programming and
Object oriented programming. You have learned about the statements used in this language like
input/output statements, selection statements (if..else, switch) and iterative statements/loops (while,
do..while, for). Further you will also have knowledge about classes, encapsulation, inheritance and
polymorphism.

In C++, every application/program contains a function called main(), which is a global function.
Execution of every program starts from this function, so you have to write this function in each C++
program. You may write other functions also in your program beside main() function, which depends on
modular solution you have developed to solve your problem.

1.1. Basic Concepts about Data Structures

A program is a set of instructions that processes data which is given as input to it. If we need to
develop a good (efficient) program, we need to organize data in computer’s memory in effective way.
This organized data is called a Data Structure.

Study of computer science includes the study of how data (information) is organized in computer
and how it can be manipulated and utilized by programs. It is extremely important for you to understand
the concepts of data (information) organization and manipulation. Data structures for storing information
are lists, stacks, queues, trees, graphs and tables.

1.2. Arrays in C++

In C++ arrays are used to store such items whose data type is same. Normally arrays are used to
represent lists, trees and graphs; which are types of data structure. We can perform different operations on
arrays such as: inserting an item, removing an item, finding a value in array, performing mathematical
operations on elements of array etc. If we want to initialize any global or local array by assigning some
values to its element we can do so. We can access value of an element of array in our program as it was a
normal variable. We are allowed to read and modify the values of these elements.

Static arrays are allocated memory at compile time and their size is fixed, it means it cannot be
changed latter during program execution. If we want to change the size of array at program execution
time, we will need to declare dynamic arrays. A dynamic array is allocated memory using new operator
and is used in the same way as a static array. Dynamic arrays are accessed using pointers.

Department of Computer Science Page 3


IIUI, Islamabad
Lab 1: Development of Arrays

1.3. Dynamic Memory Allocation

Assume you have a program which is used to store information about the employees of some
organization, when this program starts its execution we are not sure that how many number of employee
records will be stored in this program. Therefore how much memory is required for this program is
dependent on the fact that how many records we will enter when program will be executing. So memory
required by program is to be estimated at program execution time, so we will need a memory allocation
mechanism which is called dynamic memory allocation for this program, which should allocate and de
allocate memory at runtime according to requirements of program.

1.4. Multi-Dimensional Arrays

Sometimes the data which we need to process in our program is more easily interpretable if
represented in the form of a table. A table is a structure which contains some rows and some columns, on
intersection of each row and a column some data is stored. Examples of such data representations may be
a parcel weight-location chart used by some post office; a public transport rent chart and representation of
a digital image etc. So we may easily understand this data representation if we use a two dimensional
array to represent it (remember a two dimensional array is a special case of a multi-dimensional array).

Sometimes data to be represented is based on more than two dimensions, for example if we need
to represent the sales of some departmental stores by product, year of sale and location wise, it can be
easily represented by a three dimensional structure, which may be logically represented as a cube. To
represent such data we will use three dimensional arrays.

1.5. Relevant Lecture Readings

a) From books: C++ Data Structures by Nell Dale (Page79-85) and Data structures using
C++ by D. S. Malik (Page130-135).
b) From books: C++ Data Structures by Nell Dale (Page 99-102) and Data structures
using C++ by D. S. Malik (Page 138-145).

2. Activity Time boxing


Table 1 Activity Time Boxing

Task Activity Name Activity time Total Time


No.
5.1 Design Evaluation 15 mins 15 mins
6.2 Editing and compiling a C+ 5mins 5mins
+ program in Visual Studio
2017
6.3 Walk Through Task 20mins 20mins
7 Practice tasks 30 mins for task 1,2 and 40 70mins
mins for task 3, 4
9 Evaluation Task 60mins for all assigned 60mins
task
Department of Computer Science Page 4
IIUI, Islamabad
Lab 1: Development of Arrays

3. Objectives of the experiment

 To get basic understanding of static and dynamic arrays in C++.


 To get basic understanding of dynamic memory allocation and multi-dimensional arrays in C++
 To write programs in C++ using Microsoft Visual Studio 2017 environment.
 To get an understanding of identifying basic errors in a C++ program by using debugging
techniques.
 To get an understanding of identifying basic errors in a C++ program by using debugging
techniques.

4. Concept Map
This concept map will help students to understand the main concepts of topic covered in lab.

4.1. Arrays in C++


In C++ arrays are used to store such items whose data type is same. Normally arrays are used to
represent lists, trees and graphs; which are types of data structure. We may perform different operations
on arrays such as: inserting an item, removing an item, finding a value in array, performing mathematical
operations on elements of array etc.

Example:

An array named “Numbers” containing five elements of type integer (int) can be defined as:

int Numbers [5];

Figure 1 represents the logical representation of this array, which shows elements of the array are
located consecutively:

Figure 1 Logical representation of an array of integer elements

4.2. Initializing Arrays

When an array is declared in a local scope, if not specified otherwise, its elements are not initialized by
some value by default. Elements of global and static arrays are automatically initialized by their default
values (zeros for numeric data types).

If we want to initialize any global or local array by assigning some values to its element we can do
so. Following example represents the initialization of an array of 5 integer elements.

Department of Computer Science Page 5


IIUI, Islamabad
Lab 1: Development of Arrays

Example:

int Numbers [5] = { 16, 2, 77, 40, 12071 };


OR
int Numbers [] = { 16, 2, 77, 40, 12071 };

Figure 2 represents the above initialized array with values.

Figure 2 An array initialized by values

4.3. Accessing values from an array


We can access value of an element of array in our program as it was a normal variable. We are
allowed to read and modify the values of these elements. Following the previous examples in which
Numbers array has 5 elements and each of those elements was of type int, the name which we can use to
refer to each element is the following:

For example, to store the value 25 in the third element of Numbers, we could write the following
statement:

Numbers [2] = 75;

To pass the value of the third element of Numbers to a variable called a, we could write:

a = Numbers[2];

4.4. Static Arrays


Static arrays are allocated memory at compile time and their size is fixed, it means it cannot be
changed latter during program execution. For example two int arrays are declared, one initialized and one
without initialization.

int a[10];
int b[5] = {8, 20, 25, 9, 14};

4.5. Dynamic Memory Allocation in C++

Dynamic memory allocation in C++ is performed using new and delete operators. These operators
can be used with primitive data types (int, float, char etc) as well as with user defined data types (UDT),
such as classes. Following examples illustrate usage of new and delete operators for primitive as well as
user defined data types.

For int data type, new operator can be used as:

int *pointer;
Department of Computer Science Page 6
IIUI, Islamabad
Lab 1: Development of Arrays

pointer = new int;


*pointer = 5;
delete pointer;

Above code will create a pointer variable named “pointer” which is pointing to a dynamic variable
of int type created by new operator. After the creation of variable a constant value 5 is assigned to this
variable using the pointer variable, because a dynamic variable does not have a name to be referenced.
When dynamic variable is used and is no more required, we can de allocate its memory by using delete
operator. With delete operator we use name of pointer variable which is pointing to that dynamic variable
required to be de allocated.

We may allocate and de allocates memory space dynamically to an array of integers. Following
example illustrates this concept.

int size;

cout<< "Enter size of array: ";


cin>> size;

int* array = new int[size];

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


{
array[i] = i+1;
cout<< array[i] << " ";
}

delete [] array;

new and delete operators can be used with a user defined type or class/struct as well. Assume
following is a class definition for which we need to create a dynamic object.

class Rectangle {
private: int x, y;

public:
void set_values (int,int);
int area () {return (x*y);}
};

void Rectangle::set_values (int a, int b) {


x = a;
y = b;
}
Department of Computer Science Page 7
IIUI, Islamabad
Lab 1: Development of Arrays

Following code segment creates and destroys a dynamic object of above described class.

Rectangle *ptr = new Rectangle();


ptr->set_values(3,5);
cout<<ptr->area();
delete ptr;

4.6. Multi-Dimensional Arrays

An array of arrays is called a multi dimensional array. Number of dimensions in a multi


dimensional array is represented by number of subscripts in definition of that array. A multi dimensional
array can represent data from different dimensions point of view. For example product sales information
of departmental store from product, location/city and year of sale dimensions point of view is an example
of multi dimensional array. It can be logical represented by following figure 1.

Figure 3 A logical representation of a multi dimensional (3-dimensional) array

4.6.1. Two Dimensional Arrays in C++

A two dimensional array is a specific case of multi-dimensional array in which two subscripts are
involved in definition of array. For example “Numbers” represents an array of 3 per 5 elements. The way
to declare this array in C++ should be:

int numbers [3][5];

Following figure 2 shows a logical representation of a two dimensional array “numbers”.


Department of Computer Science Page 8
IIUI, Islamabad
Lab 1: Development of Arrays

Figure 4 A logical representation of a two dimensional array

Indices of first subscripts are logical represented as rows and indices of second subscripts are
logically represented as columns. Now for example the way to reference the second element vertically and
fourth horizontally in an expression would be:
numbers [1][3];

Following figure 3 shows the element in the two dimensional array which is referred above.

Figure 5 Referencing an element in two dimensional arrays

To assign some value to elements of a two-dimensional array, we simply use two subscripts:

numbers[1][3] = 7;

To initialize a two-dimensional array, it is easiest way to use nested braces, with each set of
numbers representing a row:

int numbers[3][5] =
{{ 1, 2, 3, 4, 5, }, // row 0
{ 6, 7, 8, 9, 10, }, // row 1
{ 11, 12, 13, 14, 15 } // row 2 };

We may initialize a two dimensional array of type int by values 0 by using following statement.
Remember that we have to specify the size of array in terms of rows and columns for proper initialization.

int numbers[3][5] = { 0 };

Two dimensional arrays can be created and accessed using pointers to pointers. Following code
segment provides information that such array usage.

Department of Computer Science Page 9


IIUI, Islamabad
Lab 1: Development of Arrays

int **a = new int*[height];


for(int i=0; i < height; i++ )
a[i] = new int[width];

The above code segment declares an array of integer pointers to integer pointers. The first thing
we do is then make a point to an array of integer pointers. Then we have to loop through all of those
pointers and assign them to an array of ints of size width. What this does is create an array in the size of
Height x Width.

4.6.2. Three Dimensional Arrays in C++

Multi-dimensional arrays may be larger than two dimensions, arrays which have 3
dimensions are called multi-dimensional arrays, they can be logical represented by a cube
shape. An array representing product sales for departmental stores at five cities/locations, 10
products and containing sale information for 7 years can be declared as:

float productSales[5][10][7];

Where first subscript represents the location/city number, second subscript represents
the product number and third subscript represents the year number for which product sale
information will be stored in this array.

Three dimensional arrays cannot be easily initialized as compared to two dimensional


arrays initialization, so normally they are initialized by zero/blank value and then further
initialization is performed by using nested loops.

5. Homework before Lab

This homework will help students to study the concepts of topic before start of lab.

5.1. Problem Solution Modeling

After studying the introduction and concept map sections you should be ready to provide the
solution of following problems. Design the solutions of the problems in C++ and bring your code
to lab so that lab instructor should assess and grade it.

5.2. Problem description:


Design a program which should contain two arrays, both arrays should contain elements of type
integer (int). One of these arrays should be a static array and other should be a dynamic array. User
will provide numerical values as input for these arrays. Your program should read value form each
element and add these values to a single variable. After completion of addition operation for two
arrays, value of this variable should be displayed on computer screen.

Department of Computer Science Page 10


IIUI, Islamabad
Lab 1: Development of Arrays

6. Procedures & Tools


This section provides information about tools and programming procedures used for the lab.

6.1. Tools
Microsoft Visual Studio 2017 with Visual C++ compiler configured.

6.2. Editing, Compiling and Running programs in Visual Studio


2017[Expected time = 5mins]

You are required to use Microsoft Visual Studio 2017 environment for programming on data
structures. It is expected that you are already familiar with this environment in your courses of Computer
Programming and Object Oriented Programming. You should be able to write code in source code files
(cpp files) and perform compilation of code. Beside that you are also required to be proficient in
performing line by line debugging and break point based debugging to remove the errors from your code.

6.3. Walk through Task [Expected time = 20mins]

Following program represents the concept related to static and dynamic arrays; you are required to
type this program in editor of Visual Studio 2017, compile and run to see the output of this program.
Figure 3 shows the source code window of this program in Visual Studio 2017.

Figure 6 A programs about static and dynamic arrays in Visual Studio 2017

Department of Computer Science Page 11


IIUI, Islamabad
Lab 1: Development of Arrays

Output of this program is shown in figure 4, when program is compiled and executed.

Figure 7 Output window displaying results of program after compilation

Department of Computer Science Page 12


IIUI, Islamabad
Lab 1: Development of Arrays

Figure 8 Use of two dimensional arrays in Microsoft Visual Studio 2017

Figure 6 represents the output of this program when executed.

Figure 9 Output window displaying values of elements of two dimensional arrays in Microsoft Visual Studio 2017

7. Practice Tasks

This section will provide information about the practice tasks which are required to be performed in lab
session. Design solutions of problems discussed in each task and placesolution code in a folder specified
by your lab instructor.

7.1. Write a C++ program to create two pointers of integer type, now take values in these pointers and
pass them to a function. Function will update both the values by adding “1” to them. Display the
updated values in main.
7.2. Create a dynamic array of user defined size. Now take input in array from user. Take a new
(integer) value from user and search that how many times the entered number is present in the
array.
7.3. Write a program to create a dynamic array of user defined size. Array should be of character type.
Write a function ChangeCase() that should convert all the small alphabets to capital and vice
versa. All array operations should be done using pointers.
7.4. Write a program to create a dynamic array of user defined size. Size should be in the range of 0 to
15. Write a function FindLarge that should ask user to enter a non-negative number. Function
should find the next largest number than the input number in the list.

Department of Computer Science Page 13


IIUI, Islamabad
Lab 1: Development of Arrays

Sample input:

Enter size: 5

After insertion:

13 4 55 29 32

Sample output:

Enter number: 15

Next largest number from 15 is: 29

7.5. Out comes

After completing this lab, student will be able to understand and develop programs related to static and
dynamic arrays in C++ using Microsoft Visual Studio 2017 environment.

8. Evaluation Task (Unseen) [Expected time = 60mins for two


tasks]

The lab instructor will give you unseen task depending upon the progress of the class.

9. Evaluation criteria

The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is
assigned the marks percentage which will be evaluated by the instructor in the lab whether the student has
finished the complete/partial task(s).

Table 2 Evaluation of the Lab

Sr. No. Task Description Marks


No
1 4 Problem Modeling 20
2 6 Procedures and Tools 10
3 7 Practice tasks and Testing 35
4 8 Evaluation Tasks (Unseen) 20
5 Comments 5
6 Good Programming Practices 10

Department of Computer Science Page 14


IIUI, Islamabad
Lab 1: Development of Arrays

10. Further Readings

10.1. C++ Tutorial Web Sites

1. http://www.cplusplus.com/doc/tutorial/
2. http://www.learncpp.com/
3. http://www.tutorialspoint.com/cplusplus/

10.2. Web sites containing supporting material

1. http://www.engppt.com/2012/08/data-structures-with-c-ppt-slides.html
2. http://www.compgeom.com/~piyush/teach/3330/slides/

Department of Computer Science Page 15


IIUI, Islamabad

You might also like