Sunteți pe pagina 1din 12

Lab no 4 Array Basics ICP

Note:

This is a document that describes, with examples, the basic concepts


associated with an array. [Can be helpful in final exam]

Read and try to understand the document before attempting to write the
example code.

Do not copy and paste the code.

Exercise at the end of this document is mandatory for each student.

The exercise to be shown with in the allotted time.

1
Array basics

Let's start by looking at a single variable used to store a person's age.

C++ Code Listing 1


1: #include <iostream>
2:
3: int main()
4: {
5: short age;
6: age=23;
7: cout << age <<endl;
8: return 0;
9: }

Not much to it. The variable age is created at line (5) as a short. A value is assigned to
age. Finally, age is printed to the screen.

Now let's keep track of 4 ages instead of just one. We could create 4 separate variables,
but 4 separate variables have limited appeal. (If using 4 separate variables is appealing to
you, then consider keeping track of 93843 ages instead of just 4). Rather than using 4
separate variables, we'll use an array.

Here's how to create an array and one way to initialize an array:

C++ Code Listing 2


1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: age[0]=23;
7: age[1]=34;
8: age[2]=65;
9: age[3]=74;
10: return 0;
11: }

2
On line (5), an array of 4 short's is created. Values are assigned to each variable in the
array on line (6) through line (9).

Accessing any single short variable, or element, in the array is straightforward. Simply
provide a number in square braces next to the name of the array. The number identifies
which of the 4 elements in the array you want to access.

The program above shows that the first element of an array is accessed
with the number 0 rather than 1. Later in the tutorial, We'll discuss why
0 is used to indicate the first element in the array.

Printing arrays

Our program is a bit unrevealing in that we never print the array to screen. Here is the
same program with an attempt to print the array to the screen:

C++ Code Listing 3


1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: age[0]=23;
7: age[1]=34;
8: age[2]=65;
9: age[3]=74;
10:
11: cout<<age<<endl;
12: return 0;
13: }

Line (11) is meant to print the 4 ages to the screen. But instead of printing out the four
short variables, what appears to be nonsense prints out instead.

What the "nonsense" output actually is and why the 4 array values were
not printed will be addressed later in the tutorial. For now, the
important point to come away with is that simply providing the name

3
of the array in an output statement will not print out the elements of the
array.

How about printing out each of the values separately? Try this:

C++ Code Listing 4


1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: age[0]=23;
7: age[1]=34;
8: age[2]=65;
9: age[3]=74;
10: cout << age[0] << endl;
11: cout << age[1] << endl;
12: cout << age[2] << endl;
13: cout << age[3] << endl;
14: return 0;
15: }

Lines (10) through line (13) produce the output we are expecting.

There is no single statement in the language that says "print an entire array to the screen".
Each element in the array must be printed to the screen individually.

Copying arrays

Suppose that after filling our 4 element array with values, we need to copy that array to
another array of 4 short's? Try this:

C++ Code Listing 5


1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7: age[0]=23;
8: age[1]=34;
9: age[2]=65;
10: age[3]=74;
11:
12: same_age=age;
13:
14: cout << same_age[0] << endl;
15: cout << same_age[1] << endl;
16: cout << same_age[2] << endl;
17: cout << same_age[3] << endl;
18: return 0;
19: }

4
Line (12) tries to copy the age array into the same_age array. What happened when you
tried to compile the program above?

The point here is that simply assigning one array to another will not
copy the elements of the array. The hard question to answer is why the
code doesn't compile. Later in the tutorial this example will be re-
examined to explain why line (12) doesn't work. This code should not
compile on either C or C++ compilers. However, some older C++
compilers may ignore the ISO C++ standard and allow line 12 to
compile. If it does compile on your C++ compiler, make a mental note
that it is incorrect behavior.

Let's try copying arrays using a technique similar to the technique used to print arrays
(that is, one element at a time):

C++ Code Listing 6


1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7:
8: age[0]=23;
9: age[1]=34;
10: age[2]=65;
11: age[3]=74;
12:
13: same_age[0]=age[0];
14: same_age[1]=age[1];
15: same_age[2]=age[2];
16: same_age[3]=age[3];
17:
18: cout << same_age[0] << endl;
19: cout << same_age[1] << endl;
20: cout << same_age[2] << endl;
21: cout << same_age[3] << endl;
23: return 0;
23: }

This technique for copying arrays works fine. Two arrays are created: age and same_age.
Each element of the age array is assigned a value. Then, in order to copy of the four
elements in age into the same_age array, we must do it element by element.

5
Copy first element

Copy second element

Like printing arrays, there is no single statement in the language that says "copy an
entire array into another array". The array elements must be copied individually.

The technique used to copy one array into another is exactly the same as the technique
used to copy 4 separate variables into 4 other variables. So what is the advantage to using
arrays over separate variables?

One significant advantage of an array over separate variables is the name. In our
examples, using four separate variables requires 4 unique names. The 4 short variables
in our array have the same name, age. The 4 short's in the array are identical except for
an index number used to access them. This distinction allows us to shorten our code in a
way that would be impossible with 4 variables, each with unique names:

C++ Code Listing 7


1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7: int i, j;

6
8: age[0]=23;
9: age[1]=34;
10: age[2]=65;
11: age[3]=74;
12:
13: for(i=0; i<4; i++)
14: same_age[i]=age[i];
15:
16: for(j=0; j<4; j++)
17: cout << same_age[j] << endl;
18: return 0;
19: }

Since the only difference between each of the short's in the arrays is their index, a loop
and a counter can be used to more easily copy all of the elements. The same technique is
used to shorten the code that prints the array to the screen.

Even though arrays give us some convenience when managing many variables of the
same type, there is little difference between an array and variables declared individually.
There is no single statement to copy an array, there is no single statement to print an
array.

If we want to perform any action on an array, we must repeatedly perform that


action on each element in the array.

Example -- adding all elements of an array


This program values into an array and sum them. Assume fewer than 1000 input values.
Yes, we could have summed them in the input loop.
// arrays/readsum.cpp -- Read numbers into an array and sum them.
// Fred Swartz - 2003-11-20

#include <iostream>
using namespace std;

int main() {
int a[1000]; // Declare an array of 1000 ints
int n = 0; // Number of values in a.

while (cin >> a[n]) {


n++;
}
int sum = 0; // Start the total sum at 0.
for (int i=0; i<n; i++) {
sum = sum + a[i]; // Add the next element to the total
}

cout << sum << endl;

return 0;
}

7
Why read numbers into memory

The previous example, which reads numbers into an array then sums the elements of the
array, is not a convincing use of arrays. It would have been just as easy to add them while
we were reading them.

But usually the computation can not be performed while reading, for example, sorting
them and printing them in order by their value. An even simpler example is given below -
printing them in reverse order of input.

Example -- printing the input values last to first


Here is something than can't be done with a simple input loop.
// arrays/reverse-input.cpp - Reverses order of numbers in input.
#include <iostream>
using namespace std;

int main() {
//--- Declare array and number of elements in it.
float a[100000];
int n; // Number of values currenlty in array.

//--- Read numbers into an array


n = 0;
while (cin >> a[n]) {
n++;
}

//--- Print array in reverse order


for (int i=n-1; i>=0; i--) {
cout << a[i] << endl;
}

return 0;
}//end main

8
Exchanging Values of Variables
ƒ It is sometimes necessary to shuffle the order of the elements of an array.
ƒ Sorting arrays calls for the values of some elements to be exchanged. It would
therefore be helpful to first learn the technique of swapping variables.
ƒ How would you swap the values of the variables, let say, num1 and num2 (that is
exchanging the value of num1 in num2)?
ƒ You must use a third variable as in the following example:

// assign num1 to third_var

third_var = num1;

// then assigns num2 to num1

num1 = num2;

// finally assigns third_var to num2

num2 = third_var;

ƒ The process can be illustrated as shown below.

Sorting Variables

ƒ Sorting is defined as arranging data in a certain order, is a very common activity


in data processing. Many algorithms (techniques) are available to perform
sorting.
ƒ One sorting algorithm, which is quite simple to understand, but not necessarily the
best, is given in the following program example. It sorts a list of integers in
ascending order of magnitude by using an array.

9
// a simple sorting program that sort a list of n

// integer numbers, entered by the user, ascending

#include <iostream>

#define maxsize 100

int main()

int temp, i, j, n, list[maxsize];

cout<<"\n--You are prompted to enter your list size.--";

cout<<"\n--Then, for your list size, you are prompted to enter--";

cout<<"\n--the element of your list.--";

cout<<"\n--Finally your list will be sorted ascending!!!--\n";

// get the list size...

cout<<"\nEnter your list size: ";

cin>>n;

// prompting the data from user and store it in the list...

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

cout<<"Enter list's element #"<<i<<"-->";

cin>>list[i];

// do the sorting...

for(i=0; i<n-1; i++)

for(j=i+1; j<n; j++)

10
if(list[i] > list[j])

// these three lines swap the elements list[i] and list[j].

temp = list[i];

list[i] = list[j];

list[j] = temp;

cout<<"\nSorted list, ascending: ";

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

cout<<" "<<list[i];

cout<<endl;

return 0;

Output:

11
Exercise
• Write a program to find the smallest number in an array ?
• Write a program that calculates the grade for 20 students, grades shall be
calculated according to the following rule

if marks < 50 F if marks < 60 & > 50 C

if marks < 70 & > 60 B if marks <80 & >70 A

Use array to store grades and marks of students.

12

S-ar putea să vă placă și