Skip to main content

Chapter 6. Array



Learning Outcomes

At the end of this chapter, you should be able to:
Understand the concept of array.
Perform the array declaration and initialization.
Apply on how to access elements in an array.
Perform operations (summation, maximum and minimum) in an array.
Perform passing array to function.

Introduction

In C++ programming, an array is a data structure. It is process of group the same categories of data.
Array is a collection of data of the same data type. An array allows us to group and store same variables which have a same data type.
Usually a variable can hold one value at a time, but by using an array, we can store more than one value in a single variable.

Figure 6.1 shows the difference between variable and array.

Figure 6.2 shows the arrays for variablessalary, name and staff ID.

An array can store many values, and each of the values is known as an element and has its own array index that can be used to access it.
A variable can be easily retrieved by referring to the index.
An array index is also known as subscripts.
A subscript is a number that indicates the position of a particular array element that is being used.

Figure 6.4 illustrates the array elements and array indexing of a variable named temperature.
The figure shows four elements stored in the array.
The subscripts must start with 0, which is why the last subscript ends with three.
An array will start with the 0th element and end with array size -1.
The figure also shows the arrangement of the array in a portrait orientation (a) and landscape orientation (b).

Array Declaration

As in normal programming steps, we have to declare the entire variable before we use it. Like normal variables, arrays also have to be declared.
An array can be declared as:
datatype arrayName[size];
For array declarations, firstly, type any simple data type, continue with arrayName, with any legal identifier, and the size (in square bracket).
The size represents the number of elements the array contains.

Example of array declaration statement:
int listNumber [100];
the array named listNumber which reserve 100 elements of integer values.
char codeId [ 6];
the array reserves 6 element of characters named codeId.

Array Initialization

In C++ programming, we can assign or initialize values to the array. Initialization means assigning values to an array.
The format to write the array initialization is:
datatype arrayName[size]={ elements};
An array’s initial values are written using curly brackets
{ } and commas (,) to differentiate each element in the array as shown in the following example.

We can also initialize the values to an array without declaring the size of the array.
The number of elements in an array can define the size of an array as shown in Example 6.3.
This means we can declare an array with or without size, but we must initialize the values to it.
There can also be a situation whereby we have declared the size of an array with 6 and initialized the values for 3 elements only—the compiler will assume the next three elements are zero as shown in Example 6.4.

Restrictions in Array Operation

There are some restrictions in array operation that we should consider in a few situations.
In the first situation, an error message will appear once we want to copy one array to another array as shown in Example 6.5.

We will also have a problem once we want to insert values into an array. We cannot insert or read data to an array using the normal way.
For the solution, we have to insert data to an array using the looping method as shown in Example 6.6.

In another situation, we have to specify the index number once to retrieve the value from an array or it will display an error message. Example 6.7 shows the solution for the situation.

Accessing Array Elements

The for loop is commonly used to manipulate all the operations in arrays. Usually, with the iteration or loop process, it will make the process easier because it allows us to access the elements by referring to the subscript in the sequence.
Besides using for loop to perform the accessing process, we also can access and initialize the elements using the various methods as shown in Example 6.8.

Besides all the methods shown, we can use other ways such as the for loop to initialize or access arrays. Example 6.9 shows the general form of how to read elements into an array.
As in a normal iteration process, we have to define the for loop argument based on the array size.
As usual, we have to start the iteration with zero (0), and stop the loop once we reach the arraysize-1.
The counter for the loop should be increased by one  with each iteration.

Example 6.10 shows the general form to display the array’s contents. Here, we will also use the for loop method to display all the elements of an array by sequence.

Example 6.11 shows a complete C++ program that creates an array and display its contents. This program will have an array with 10 elements that will be initialized with values and then display them.

Example 6.12 shows a complete C++ program that creates an array and displays its contents.
The program will have two arrays, named StudentNo and Student_Marks. Both arrays will store 3 values each.
The program will prompt the user to insert the values for the arrays.
Then, the program will display the contents of the arrays in table form as shown in the output.

The program in Example 6.13 will declare an array named EvenList [ ] with 10 elements in it.
The array will store 10 values consisting of even numbers that are less than 20, then display them.
Then, the program will identify the even numbers from the list of numbers entered by the user.

Array Operations

Traversing

Traversing is an operation whereby each element in an array is accessed for a specific purpose.
Actually, in the traversal operation, we will use the values in many programs because it is a basic operation that we have discussed before.
The process of printing the elements, and calculations between the elements are all examples of the traversal operation.

Inserting

Inserting is a process of adding a new element into an existing array.
We can add the element in the beginning, middle, or at the end of the array.
The inserting process can be applicable only if the size that has been declared is large enough. For example, an array with size 5 has only 3 elements initialized to it. In this case, we can apply the insertion process.
However, if there is not enough space (size) available, then we cannot proceed with the operation.

Searching

Searching means the process of finding an element in the array.
If the element is in the array, the location or the subscript of the element will be displayed and if the element is not available in  the array, an appropriate message will be displayed.
There are two types of searching methods available—linear search and binary search.

Summation

Summation is a process of adding two or more values together.
So, in arrays, summation can be performed to find the total of the values in an array.
Besides that, summation can also be done between any elements in an array as will be discussed in Example 6.15.

Example 6.16 shows a program segment for summation operation to find the total of an array price[ ].
Here, for calculating the total of the values in an array, we have declared a variable to accumulate the total.
The variable should be initialized to zero (0) before we start to accumulate the value.

Finding the Maximum

For finding the largest value in an array, we can use the maximum operation, which will compare each element in an array to find the largest value.
Example 6.18 shows the general form to find the largest value. We will use for loops and if methods to check and compare each of the values in the array to find the maximum value.
In the operation, firstly, we have to define a variable named MaxIndext and assign zero (0) to it.
Then, we will start to compare the values in the array using the sequence until we fulfil the objective to find the largest value.

Example 6.18 shows the general form to find the largest value.

Finding the Minimum

We can find the lowest value in an array using the same steps for finding the maximum value. Here also, the operation will compare each element in an array to find the lowest value.
Example 6.20 shows the general form to find the lowest value in an array. We will use for loops and if methods to check and compare each of the values in the array to find the minimum value.

Passing Array to Function

Arrays can also apply in functions in C++ program.
An array can be passed as a parameter in a function. Example 6.22 shows the array usage in a function.
The program shows that a function named calculateTotal ( ) receives a parameter of type array.
The function will receive the values in the array, then calculate the total. It returns the total to the main function.

Conclusion

An array is a collection of similar data type value.
In C++ programming, array is also known as a simple data structure.
Array will store the group data for a temporary basis in memory.
Each data in the array is stored in a sequence and has its own address that known as index. Index is also called as subscript.
Summation, and finding the maximum and minimum values, are some common operations of an array method.

Comments

Popular posts from this blog

BT-BASIC commands used

8.10     Some of the most frequently used BT-BASIC commands used are: msi                               Changes default working directory. Mass storage is            Same as “msi” cat                               Catalogs (list)the node names in the specified directory.             get                               Brings the contents of a file into the system workspace.             load                             Same as “get”.             msi$                            Returns the directory pathname of the current working directory.             msi “..”                       Backs up one directory level.             findn                            Locates the next occurrence of the a given sting in the workspace. 8.11           If you wish to invoke the HP Board Graphics Viewer, type board graphics at the BT-BASIC command line and press the “ENTER” key on the keyboard. 8.12           A HP Board Graphics Viewer window should now appear

Perhitungan & Cara Merubah Kumparan Blender Dari 220 V Menjadi 12 V

          Seperti yang telah dijelaskan pada buku “menggulung motor listrik arus bolak-balik, servis peralatan listrik rumah tangga kelompok penggerak dan perbaikan peralatan listrik pertukangan”, bahwa motor penggerak yang digunakan pada perlatan listrik rumah tangga dan pertukangan seperti blender, mixer, bor tembak, gerinda dsb menggunakan jenis motor universal. Motor universal adalah jenis motor listrik yang dapat disuplai dengan sumber listrik arus bolak-balik (AC) dan arus searah (DC). Jadi peralatan-peralatan listrik rumah tangga dan pertukangan tersebut yang biasanya kita suplai dengan sumber listrik AC dari PLN atau Genset sebesar 220 V sebenarnya dapat juga kita suplai dengan sumber listrik DC yang tentunya tegangan juga harus sama yakni 220 V.           Yang menjadi permasalahan bagaimana kalau peralatan listrik rumah tangga atau pertukangan tersebut, sebagai contoh misalkan blender yang ingin digunakan atau dioperasikan pada tempat yang tidak terdapat sumber listrik PLN ata

BT-BASIC command line

8.8       At the BT-BASIC command line type the command  msi  and the directory path, then press the “ENTER” key on the keyboard.  Example:                   msi ‘/hp3070/boards/aspect/main’ 8.9       At the BT-BASIC command line type the command  get ‘testplan’ and press the   ENTER” key on the keyboard.  You should now see the body of the testplan file displayed in the work space of the BT-BASIC window. 8.10     Some of the most frequently used BT-BASIC commands used are:

Autodesk SketchBook Pro 2021 Full Version

BAGAS31 – Sesuai dengan namanya, Autodesk SketchBook Pro 2021 Full Version ini merupakan software digital sketching atau drawing terbaik yang bisa kamu gunakan. Pada versi terbaru kali ini, ada beberapa penambahan fitur yang sangat efektif. Dengan fitur baru tersebut, diharapkan mampu meningkatkan proses sketching maupun drawing kamu. Autodesk SketchBook sendiri sudah bisa kamu dapatkan secara gratis melalui website resminya. Namun untuk kamu yang mau download versi Autodesk Sketchbook Pro, maka bisa langsung download melalui link yang sudah saya sediakan di bawah ini. Download Autodesk SketchBook Pro 2021 Full Version Screenshot: System Requirements: Windows 10 2.5 – 2.9 GHz of Intel or AMD CPU 4 GB of Memory 256 MB Graphics card with OpenGL 2.0 support We recommend that you use a pressure-sensitive tablet and pen for basic features Download: Autodesk SketchBook Pro 2021 Full Version [ FileUp ][ Uptobox ][ UsersDrive ] Jamu Only [ FileUp ][ Uptob

Testhead

4.3         Testhead The testhead is that portion of the tester that supports the PIN, ASRU and Controller cards.   The testhead is divided into two BANKS and each BANK is divided into two MODULES, see figure 2 below.  Bank 1 contains modules 0 and 1, bank 2 contains modules 2 and 3.  The test fixtures are placed on the banks of the tester and locked down for board testing.  The testhead cards interface to the test fixture through the spring loaded pogo pin “nails” at the top edge on each of these card types. 4.4       Support Bay The support bay is a stand-alone cabinet that houses the power supplies for the Unit Under Test.  This bay also houses the test station power distribution unit and test station controller on earlier models. 4.5       Emergency Shutdown Switch The emergency shutdown switch is the large red button located at the lower left corner on the front of the testhead.  It turns off all AC power to the testhead, and is equivalent to turning off the m

Kelebihan dan Kekurangan Saluran Listrik Jenis Saluran Udara dan Saluran Bawah Tanah

Berdasarkan pemasangannya,   saluran distribusi dibagi menjadi dua kategori, yaitu : saluran udara (overhead line) merupakan sistem penyaluran tenaga listrik melalui kawat penghantar yang ditompang pada tiang listrik. Sedangkan saluran bawah tanah (underground cable) merupakan sistem penyaluran tenaga listrik melalui kabel-kabel yang ditanamkan di dalam tanah. 1.    Saluran Bawah Tanah (Underground Lines) Saluran distribusi yang menyalurkan energi listrik melalui kabel yang ditanam didalam tanah. Kategori saluran distribusi seperti ini adalah yang favorite untuk pemasangan di dalam kota, karena berada didalam tanah, maka tidak mengganggu keindahan kota dan juga tidak mudah terjadi gangguan akibat kondisi cuaca atau kondisi alam. Namun juga memilik kekurangan, yaitu mahalnya biaya investasi dan sulitnya menentukan titik gangguan dan perbaikannya. Kedua cara penyaluran memiliki keuntungan dan kerugian masing-masing. Keuntungan yang dapat diperoleh dari suatu jaringan bawah tanah adalah