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

W8-Module-Dimensions of Data Types

This document discusses dimensions of data types and arrays in programming. It begins by introducing the concept of dimensions and differentiating between variables and arrays. It then explains how computers allocate space for arrays, noting arrays can have multiple dimensions like 2D tables. The document provides formulas for calculating space allocated to arrays of different dimensions. It advises against using more than 2D arrays due to computational inefficiency and errors. Finally, it briefly discusses declaring and using arrays in C++.

Uploaded by

Jitlee Papa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

W8-Module-Dimensions of Data Types

This document discusses dimensions of data types and arrays in programming. It begins by introducing the concept of dimensions and differentiating between variables and arrays. It then explains how computers allocate space for arrays, noting arrays can have multiple dimensions like 2D tables. The document provides formulas for calculating space allocated to arrays of different dimensions. It advises against using more than 2D arrays due to computational inefficiency and errors. Finally, it briefly discusses declaring and using arrays in C++.

Uploaded by

Jitlee Papa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Module 008 Dimensions of Data Types

“The key to growth is the introduction of higher dimensions of consciousness


into our awareness.”
– Lao Tzu.

Armed with the fundamental knowledge in Computer Programming, it is now


time to expand those horizons and present more in-depth understanding of
the inner workings of the computer – in turn, know more about
programming right and efficient. This module will develop on what you
already know about variables, and introduce them in a way you might have
not yet imagined before – dimensions. Yes, dimensions!

At the end of this module, you will be able to:


1. Differentiate variables from arrays.
2. Identify the different properties of arrays.
3. Argue how the computer allocates spaces with arrays.
4. Argue the limitations of using arrays.

Again, researching beyond the coverage of this module is highly encouraged


to supplement your understanding of the topics covered. And as always,
think and see beyond the box.

So what are we waiting for? Let us continue our exploration of the world of
Computer Programming.

Course Module
Recall

In the previous module, we discussed mainly about what looping and iterations are. We
also identified the four (4) phases of a looping statement, namely:
(a) Initialization
(b) Condition
(c) Body
(d) Increment/Decrement
In addition, we identified the different looping statements in C++, namely:
(a) WHILE Statement
(b) FOR Statement
(c) DO WHILE Statement
Lastly, we discussed how the four (4) phases of looping are arranged in the looping
statements of C++.

Variables in Dimensions

Since Week 4, we have been using variables in the conventional way. We are only dealing
with them in one dimension where one variable can only store one value. However, that is
not the only way we can manage the data stored in the computer.

The First Dimension

A quick recap about variables, when the computer learns that a variable was
declared, it allocates several spaces in the RAM for the declared variable. The number
of spaces that will be allocated will depend on the data type of the variable.

Data Type Allocated Size

Int 32 bits

short 16 bits

long 64 bits

bool 1 bit

float 32 bits (floating point)

double 64 bits (floating point)


char 8 bits
Table 1. Allocation per Data Type

If we follow the allocated sizes per data type, int for example, the computer will
allocate 32 bits of space for one integer variable. Those bits are located adjacent each
other. Think of it as a train, one car is adjacent to one another as one (1) bit of the
thirty-two (32) bits integer is adjacent to one another, internally speaking.

The same thing is applied to characters. One character variable occupies eight (8)
bits of space in the RAM. How about strings since we talked about a string as a series
of characters? In this case, string is an example of an array. A string is a series of
characters, wherein, a string can be composed of two characters in one declaration
such as this: char jai[2] = “06”;

The Other Dimensions

An array is variable that can contain more than one value of similar data types.
Arrays are bounded still by the data type they are declared. For example, if we
declare an array of characters, the values that it stores are all characters. Assigning
non-character value in the said array would result to exceptions or errors. An
exception is a programming language- or developer-defined error that is the result of
inappropriate actions committed unexpectedly.

The syntax of declaring an array is: dataType variableName[size]; The dataType


in the syntax is similar to how we declare variables. It can be int, short, long, or any
of the remaining data types. The variableName is our typical alias we give the
variable to reference in the future. Lastly, the size is a non-zero integer which dictates
the maximum number of values the array can store.

In this example of char jai[2];, we are declaring an array of character type that
store up to two (2) values (characters). Take note that one character is eight (8) bits
in size, therefore when the computer recognizes that this array is declared, the
computer will allocate sixteen (16) bits of size. Similar to our example of the train,
think of a variable as one cart. Now, in that example, the array of two (2) characters
are two adjacent carts. If we declared char postalCode[4];, we are declaring a
maximum of four (4) values for the character; hence, we have four (4) adjacent carts.

bitsOf1DArray = bitsOfDataType * sizeOfArray


Figure 1. Formula of the Allocated Size of 1D Array.

Course Module
This analogy is important to recognize the internal workings of the computer. For
example, if we declare two arrays char jai[2], postalCode[4];, the computer will
allocate two separate trains, one with two carts and another with four carts. As to
where exactly in the RAM those two arrays would be allocated mainly depends on
the computer.

There is a way to get exactly the address used by the computer to reference the
arrays, and by extension, the variables as well. These will be covered in the
topic of Pointers and References in Week 12 and 13.

Up until now, we are only talking about one-dimension (1D) arrays. But the
computer is powerful enough to allow multiple-dimension arrays. Let us take a two-
dimension (2D) array. When we compare a one-dimension array to a train, we can
think of a two-dimension array as a table. For example char matrix[5][5];, here we
have a five-by-five array. In relation to a table, we have a table with five rows and five
columns. Similar to the rest of the examples, the said array can only contain character
values.

A limitation to this is that each row has exactly the same number of columns. Row 0
has five columns; row 1 has five columns; until row 4 which has five columns as well.
Notice that I started my counting using the number zero (0). When we call the first
cart using the variable name of the array, we use the index 0. An index is an integer
reference used to indicate which element of the array is being accessed. An element is
a value of the array. If we call matrix[0][0], we are calling the first column of the
first row. If we call matrix[0][1], we are calling the second column of the first row. If
we call matrix[1][0], we are calling the first column of the second row. The reason
behind this approach of calling the values in an array is because of how the computer
interprets the call. For example, remember our train example with a certain number
of carts? To call the second cart, we use index 1 since we are calling the value 1
element away from the first cart. If we use index 2, we are calling the value 2
elements away from the first cart. If we use index 0, we are calling the value 0
element away from the first cart, hence the first cart itself.

bitsOf2DArray = bitsOfDataType * rowsOfArray * columnsOfArray


Figure 2. Formula of the Allocated Size of 2D Array.

It is still possible to create three-dimension, four-dimension arrays but representing


them in the real-world application becomes tedious like a three-dimension array is a
cube and a four-dimension array is like a cube with the factor of time per se. In
addition, creating these kinds of arrays are computationally expensive and they
consume resources which grows exponentially.

bitsOf3DArray = bitsOfDataType * lengthOfArray * widthOfArray *


heightOfArray
Figure 3. Formula of the Allocated Size of 3D Array.

bitsOf4DArray = bitsOfDataType * size1 * size2 * size3 * size4


Figure 4. Formula of the Allocated Size of 3D Array.

Never use more than two-dimensional arrays since not only they are
computationally and resource-expensive, but also are hard to maintain code-
wise. In addition, referencing those kinds of array are erroneous. Should the
need to use more than two-dimensional arrays arise, rethink the identified
solution. There are always better option rather than using more than two-
dimensional arrays. The factor to weigh in here is the approach used by the
solution.

Arrays in C++

Arrays in C++ follow the general descriptions of the arrays as discussed in the previous
topics, syntax- and data-wise. Here are some applications of arrays that will be used
throughout this course:

Declaring Arrays

When declaring an array, we use the syntax:

dataType variableName[size];
Figure 5. Declaring a 1D Array.

dataType variableName[rowSize][columnSize];
Figure 6. Declaring a 2D Array.

Course Module
The same syntax used in the previous topic is shown in Figures 5 and 6. Declaring
arrays are similar to how we declare variables in C++ with only the slight difference
in the size part. In array, we explicitly declare the size of the array. C++ does not
allow array of dynamic sizes.

Assigning Values to Arrays

We assign values to the array as follow:

variableName[index] = value;
Figure 7. Assigning a Value to a 1D Array by Element.

variableName[index1][index2] = value;
Figure 8. Assigning a Value to a 2D Array by Element.

The syntax for assigning values to arrays by element is show in figures 7 and 8. We
can also assign the multiple values of the array in one line as follow:

variableName = { value1, value2, … valueN };


Figure 9. Assigning All Values to a 1D Array.

variableName[index] = { value1, value2, … valueN };


Figure 10. Assigning One-row Values to a 2D Array.

variableName = { { value01, value02, … value0N }, { value11, value12, …


value1N }, … { valueN1, valueN2, … valueNN } };
Figure 11. Assigning All Values to a 2D Array.

The syntax to assign multiple values for 1D array is shown in Figure 9. If we have int
id[5] array, then we assign values to it using one line by doing id = { 9765, 1214,
9678, 23, 78 };

The syntax to assign multiple values for 2D array equivalent to one row is shown in
Figure 10. If we have int cube[5][5] array, then we assign values to row 0 of it in
one line by doing cube[0] = { 9765, 1214, 9678, 23, 78 };
The syntax to assign multiple values for 2D array equivalent is shown in Figure 11. If
we have int idx[3][2] array, then we assign values to it using one line by doing
idx= { { 8, 9 }, { 2, 90 }, { 100, 121 } };

Referencing Arrays

We call the stored values in the array as follow:

std::cout << variableName[index];


Figure 12. Referencing an Element of a 1D Array.

std::cout << variableName[index1][index2];


Figure 13. Referencing an Element of a 2D Array.

The syntax to display the values of an array is shown in Figures 12 and 13. We call
the elements of the array similar to how we assign values to the array. They only
differ in the presence of the assignment syntax = value. In referencing the array, we
do not use the assignment syntax as shown in Figure 12 and 13.

Arrays in Action

In this section, we will dissect several examples of how arrays are used in actual C++
applications.

Displaying Values of an Array

To start of, we will work on a problem about assigning values to an array and
displaying them back to the user afterward. Figure 14 details the problem-at-hand.

Write a program that accepts five (5) integers from the user and display
them back in one line.
Figure 14. Problem Statement 1.

Let us dissect first the problem. We have only two technical work items for Problem
1:
(a) To accept five (5) integers from the user

Course Module
(b) To display the five (5) numbers in one line.

Is the problem simple enough? Figure 14 shows us a version of the solution for
Problem 1.

Figure 15. Source Code for Problem 1.

The solution is pretty much straight forward approach. We start with reserving space
for our array of integers which contains five elements. By this time, our application
already has consumed 32 bits * 5 elements = 160 bits. Next, we used FOR loop
to get the user input. We specified the condition to be until five (5) since we will
accept only five (5) inputs. Lastly, we display the output using cout and consecutive
streams of string formatting.

Sorting Values of an Array

For our last example of using arrays in C++, we will work with sorting problems.
Sorting problems are problems that involve arranging the values of a given array in a
specific arrangement. Usually, the arrangement is ascending for numerical values,
and alphabetically for textual values.

Write a program that accepts five (5) integers from the user, sort in
ascending order and display the sorted array in one line.
Figure 16. Problem Statement 2.

Let us dissect first the problem. In this problem, we have three technical work items:
(a) To accept five (5) integers from the user
(b) To sort the five (5) integers in ascending order
(b) To display the five (5) sorted numbers in one line.

Figure 17. Source Code for Problem 2.

We start again with reserving space for our array of integers which contains five (5)
elements. Again, by this time, we consumed 160 bits of space. Next, we get the user
input using FOR loop. The sorting snippet is harder though. We used nested FOR
Course Module
loops. The outer FOR loop simply iterate through the five (5) user inputs. The inner
FOR loop iterate to the next user inputs past the currently selected of the outer loop.

To make this clearer, let us take an example of int[5]{ 1, 9, 4, 2, 0 }. The outer


FOR loop will pass through 1, then 9 and so on until 0. The inner FOR loop will pass
through 9 and 4 until 0, if the outer FOR loop is currently at 1. If the outer FOR loop is
now at 9, the inner FOR loop will pass through 4 and 2 until 0.

Now, inside the inner FOR loop, we have a conditional which checks if the element
selected by the outer FOR loop is greater than the element selected by the inner FOR
loop. This is configured like this since we are arranging the elements ascendingly.
Hence, we are checking if the elements in the left is larger in value than the ones in
the right. And if it is the case, interchange the two.

In order to interchange the two elements, we used a separate integer variable to


temporarily store the value of the element selected by the outer FOR loop n[i] (left
side). Next we replaced the value of n[i] with the element selected by the inner FOR
loop n[t] (right side). Lastly, we assign the value in the temporary variable to our
n[t].

By the time the outer FOR loop completes, we will have n[0] =< n[1] =< n[2] =<
n[3] =< n[4]. In example of int[5]{ 1, 9, 4, 2, 0 }, we will have int[5]{ 0,
1, 2, 4, 9 }.

Lastly, we display the sorted integers to the user.


Glossary
Array: A variable that can store more than one value of similar data types.
dataType (Array): The data type to bind the array.
Element (Array): A sector of the array that either contains value or not.
Exception: A programming language- or developer-defined error.
Index (Array): An integer which dictates which element of the array is being accessed.
size (Array): A non-zero integer which dictates the maximum number of values that the
array will store.
Snippet: A part of the entire code.
Sorting Problem: A problem that involves arranging the elements of an array in a
specific order.
variableName (Array): The alias given to reference the array, similar to variables.

Course Module
References and Supplementary Materials
Books and Journals
Stephen Davis; 2014; Beginning Programming with C++ For Dummies, 2 nd Edition; United
States; For Dummies, A Wiley Brand
Richard Halterman; 2017; Fundamentals of C++ Programming; United States of America;
Southern Adventist University

Online Supplementary Reading Materials


for loop; http://en.cppreference.com/w/cpp/language/for; June 20, 2017
Range-based for loop; http://en.cppreference.com/w/cpp/language/range-for; June 20,
2017
std::array; http://en.cppreference.com/w/cpp/container/array; June 25, 2017
std::sort; http://en.cppreference.com/w/cpp/algorithm/sort; June 25, 2017

You might also like