Vous êtes sur la page 1sur 20

CL103-Computer Programming

Lab # 03: Arrays in C/C++


Objectives:

Arrays Overview
Declaring Arrays
Initializing arrays
Accessing the values of an array
Default Initialization of Arrays
Sizeof operator for arrays
Operations of Array
Array & Functions
Parallel Arrays
Two Dimensional Arrays
Declaration of Two-Dimensional Array
Examples of Two Dimensional Arrays:
Default Initialization of 2-Dimensional Arrays
Two Dimensional Array in Functions
Multidimensional Arrays
Live Demonstration in Lab

Instructions:

1. You are allowed to use your own laptops.


2. You can consult the books, manuals and class lectures.
3. You should have stationary like register and ballpoint to analyze the tasks first.
4. Ensure that your environment is working properly.
5. In practice session, consultation is allowed.
6. No discussion is allowed during tasks solution.
7. Attempt all questions yourself.
8. Submission of all tasks solutions is necessary in any way.
9. Tasks completed in specified time will be graded.
Lab # 03: Arrays in C/C++ Page 2 of 20
Arrays Overview
Getting Started

Arrays Overview
An array is a series of elements of the same type placed in contiguous memory locations that can be
individually referenced by adding an index to a unique identifier.

An array is a group of items that can be identified as similar because they are of the same nature.

An array of airplanes An array of bugs

An array of characters
An array of cards
Figure 1: One-Dimensional Array

Arrays come in two flavors: one dimensional and multi-dimensional array. Every one of the pictures
above represents a single dimensional array.

Declaring Arrays

Figure 2: Array Layout

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 3 of 20
Arrays Overview
int billy[5];

Initializing arrays
billy[0]=16;
billy[1]=2;
billy[2]=77;
billy[3]=40;
billy[4]=12071;

Accessing the values of an array

Default Initialization of Arrays


You can give values to each array element when the array is first defined.
// arrays example
#include <iostream>
using namespace std;

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


int n, result=0;

int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}
/*Output:
12206
*/

Heres an example, DAYS, that sets 12 array elements in the array days_per_month to the number of
days in each month.

#include <iostream>
#include <conio.h>

using namespace std;

void main()
{
int month, day, total_days;

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 4 of 20
Arrays Overview
int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31 };

cout << "\nEnter month (1 to 12): ";


cin >> month;

cout << "Enter day (1 to 31): ";


cin >> day;

total_days = day; //separate days

for(int j=0; j<month-1; j++) //add days each month


total_days += days_per_month[j];

cout << "Total days from start of year is: " << total_days << endl;

_getch();
}
Enter month (1 to 12): 3
Enter day (1 to 31): 5
Total days from start of year is: 64

#include <iostream>
using namespace std;

int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

cout << "2nd member = " << distance[1] << endl;


cout << "5th member = " << distance[4] << endl;

return 0;
}
/*
2nd member = 720.52
5th member = 6.28
*/

Using this approach, each member of the array can have its value accessed. Here is an example:

#include <iostream>
using namespace std;
int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

cout << "Distance 1: " << distance[0] << endl;


cout << "Distance 2: " << distance[1] << endl;
cout << "Distance 3: " << distance[2] << endl;
cout << "Distance 4: " << distance[3] << endl;
cout << "Distance 5: " << distance[4] << endl;
return 0;
}

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 5 of 20
Arrays Overview
/*Output

Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
*/

Sizeof operator for arrays


#include <iostream>
using namespace std;

int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
// Using the sizeof operator to get the dimension of the array
int index = sizeof(distance) / sizeof(double);

cout << "Array members and their values\n";


// Using a for loop to scan an array
for(int i = 0; i < index; ++i)
cout << "Distance : " << i + 1 << distance[i] << endl;

return 0;
}
/*
Array members and their values
Distance : 144.14
Distance : 2720.52
Distance : 396.08
Distance : 4468.78
Distance : 56.28
*/

You can use such a constant in a for loop to scan the array and access each of its members. Here is an
example:

#include <iostream>
using namespace std;

int main()
{
const int numberOfItems = 5;
double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};

cout << "Members of the array\n";


for(int i = 0; i < numberOfItems; ++i)
cout << "Distance " << i + 1 << ": " << distance[i] << endl;

return 0;
}

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 6 of 20
Arrays Overview
/* Output:

Members of the array


Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
*/

Operations of Array
#include <iostream>
#include <conio.h>
using namespace std;
const int SIZE = 7;
void main()
{
int a[SIZE], i;
cout << "Enter <<SIZE<< numbers : ";
for(i=0; i<SIZE; i++)
{
cin >> a[i]; // read array
}
cout << "\n\nNumbers are : ";
for(i=0; i< SIZE; i++)
{
cout << " , "<< a[i]; // print array
}
int sum = 0;
for(i=0; i< SIZE; i++)
{
sum = sum + a[i];
}
cout<<"\n\nSum of array Elements: "<<sum;
int mul=1;
for(i=0; i< SIZE; i++)
{
mul = mul * a[i];
}
cout<<"\n\nMultiplication of array Elements: "<<mul;
getch();
}
/*Output:

Enter 7 numbers : 1 2 3 4 5 6 7

Numbers are : , 1 , 2 , 3 , 4 , 5 , 6 , 7

Sum of array Elements: 28

Multiplication of array Elements: 5040


*/

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 7 of 20
Array & Functions
Array & Functions
#include <iostream>
using namespace std;

void DisplayTheArray(double mbr[], int count);

int main()
{
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55,
6234.12};

// Processing 5 members of the array


cout << "Members of the array";
DisplayTheArray(distance, 5);

// Processing all members of the array


int sizeOfArray = sizeof(Distance)/sizeof(double);

cout << "\nMembers of the array";


DisplayTheArray(distance, sizeOfArray);

return 0;
}

void DisplayTheArray(double member[], int counter)


{
for(int i = 0; i < counter; ++i)
cout << "\nDistance " << i + 1 << ": " << member[i];
cout << endl;
}
/*
Members of the array
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28

Members of the array


Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
Distance 6: 68.04
Distance 7: 364.55
Distance 8: 6234.12
*/

Another example to illustrate arrays and functions in a logical way.

//Arrays as parameters to functions


#include <iostream>
using namespace std;

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 8 of 20
Array & Functions
const int ARRAY_SIZE = 10;
void initializeArray(int x[],int sizeX);
void fillArray(int x[],int sizeX);
void printArray(const int x[],int sizeX);
int sumArray(const int x[],int sizeX);
int indexLargestElement(const int x[],int sizeX);
void copyArray(int list1[], int src, int list2[],
int tar, int numOfElements);
int main()
{
int listA[ARRAY_SIZE] = {0}; //Declare the array listA
//of 10 components and
//initialize each component
//to 0.
int listB[ARRAY_SIZE]; //Declare the array listB
//of 10 components.
cout << "Line 1: listA elements: "; //Line 1
//Output the elements of listA using
//the function printArray
printArray(listA, ARRAY_SIZE); //Line 2
cout << endl; //Line 3
//Initialize listB using the function
//initializeArray
initializeArray(listB, ARRAY_SIZE); //Line 4
cout << "Line 5: listB elements: "; //Line 5
//Output the elements of listB
printArray(listB, ARRAY_SIZE); //Line 6
cout << endl << endl; //Line 7
cout << "Line 8: Enter " << ARRAY_SIZE
<< " integers: "; //Line 8
//Input data into listA using the
//function fillArray
fillArray(listA, ARRAY_SIZE); //Line 9
cout << endl; //Line 10
cout << "Line 11: After filling listA, "
<< "the elements are:" << endl; //Line 11
//Output the elements of listA
printArray(listA, ARRAY_SIZE); //Line 12
cout << endl << endl; //Line 13
//Find and output the sum of the elements
//of listA
cout << "Line 14: The sum of the elements of "
<< "listA is: "
<< sumArray(listA, ARRAY_SIZE) << endl
<< endl; //Line 14
//Find and output the position of the largest
//element in listA
cout << "Line 15: The position of the largest "
<< "element in listA is: "
<< indexLargestElement(listA, ARRAY_SIZE)
<< endl; //Line 15
//Find and output the largest element
//in listA
cout << "Line 16: The largest element in "
<< "listA is: "
<< listA[indexLargestElement(listA, ARRAY_SIZE)]
<< endl << endl; //Line 16
//Copy the elements of listA into listB using the

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 9 of 20
Parallel Arrays
//function copyArray
copyArray(listA, 0, listB, 0, ARRAY_SIZE); //Line 17
cout << "Line 18: After copying the elements "
<< "of listA into listB," << endl
<< " listB elements are: "; //Line 18
//Output the elements of listB
printArray(listB, ARRAY_SIZE); //Line 19
cout << endl; //Line 20
return 0;
}
/* Output

Line 1: listA elements: 0 0 0 0 0 0 0 0 0 0


Line 5: ListB elements: 0 0 0 0 0 0 0 0 0 0
Line 8: Enter 10 integers: 33 77 25 63 56 48 98 39 5 12
Line 11: After filling listA, the elements are:
33 77 25 63 56 48 98 39 5 12
Line 14: The sum of the elements of listA is: 456
9
Arrays | 505
Line 15: The position of the largest element in listA is: 6
Line 16: The largest element in listA is: 98
Line 18: After copying the elements of listA into listB,
listB elements are: 33 77 25 63 56 48 98 39 5 12
*/

Parallel Arrays
Parallel arrays are several arrays with the same number of elements that work in tandem to organize
data. True beauty of parallel arrays, is that each array may be of a different data type

for(int index = 0; index < dogname.length( ); index++)


{
cout<<setw(10)<<dogname[index]
<<setw(10)<<round1[index]
<<setw(10)<<round2[index]<<endl;
}

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 10 of 20
Two Dimensional Arrays
Two Dimensional Arrays
It is a collection of data elements of same data type arranged in rows and columns (that is, in two
dimensions).

Declaration of Two-Dimensional Array


//Type arrayName[numberOfRows][numberOfColumn];
int Sales[3][5];

Examples of Two Dimensional Arrays:

#include <iostream>
#include <conio.h>
using namespace std;
void main()
{
int a[3][3], i, j;
cout << "\n\t Enter matrix of 3*3 : \n";
for(i=0; i<3; i++)
{
cout<<"\t\t\t\t";
for(j=0; j<3; j++)
{
cin >> a[i][j]; //read 3*3 array
}
}
cout << "\n\t\t
Matrix is : \n";
for(i=0; i<3; i++)
{
cout<<"\n\t\t\t\t";
for(j=0; j<3; j++)
{
cout <<a[i][j]<<"\t";
}
}
getch();
}
/* Output:
Enter matrix of 3*3 :
1 2 3

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 11 of 20
Two Dimensional Arrays
4 5 6
7 8 9
Matrix is :
1 2 3
4 5 6
7 8 9
*/

#include <iostream>
#include <conio.h>

using namespace std;

const int DISTRICTS = 4;


const int MONTHS = 3;

void main()
{
int d, m;
double sales[DISTRICTS][MONTHS];

for(d=0; d<DISTRICTS; d++)


for(m=0; m<MONTHS; m++)
{
cout << "Enter sales for district " << d+1;
cout << ", month " << m+1 << ": ";
cin >> sales[d][m];
}

cout << "\n\n";


cout << " Month \t";
cout << " \t1 \t2 \t3";

for(d=0; d<DISTRICTS; d++)


{
cout <<"\nDistrict " << d+1;
for(m=0; m<MONTHS; m++)
cout << "\t" << sales[d][m];
}
cout << endl;

_getch();
}

/*Sample Output
Enter sales for district 1, month 1: 55
Enter sales for district 1, month 2: 32.5
Enter sales for district 1, month 3: 65.2
Enter sales for district 2, month 1: 95.1
Enter sales for district 2, month 2: 25.4
Enter sales for district 2, month 3: 45.0
Enter sales for district 3, month 1: 63.8
Enter sales for district 3, month 2: 45.9
Enter sales for district 3, month 3: 25.1

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 12 of 20
Two Dimensional Arrays
Enter sales for district 4, month 1: 12.2
Enter sales for district 4, month 2: 32.1
Enter sales for district 4, month 3: 75.66

Month 1 2 3
District 1 55 32.5 65.2
District 2 95.1 25.4 45
District 3 63.8 45.9 25.1
District 4 12.2 32.1 75.66
*/

Default Initialization of 2-Dimensional Arrays


#include <iostream>
#include <conio.h>

using namespace std;

const int DISTRICTS = 4;


const int MONTHS = 3;

void main()
{
int d, m;
double sales[DISTRICTS][MONTHS]
= {{ 1432.07, 234.50, 654.01 },
{ 322.00, 13838.32, 17589.88 },
{ 9328.34, 934.00, 4492.30 },
{ 12838.29, 2332.63, 32.93 } };

cout << " Month \t";


cout << " \t1 \t2 \t3";

for(d=0; d<DISTRICTS; d++)


{

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 13 of 20
Two Dimensional Arrays
cout <<"\nDistrict " << d+1;
for(m=0; m<MONTHS; m++)
cout << "\t" << sales[d][m];
}
cout << endl;

_getch();
}

Output
Month 1 2 3
District 1 1432.07 234.5 654.01
District 2 322 13838.3 17589.9
District 3 9328.34 934 4492.3
District 4 12838.3 2332.63 32.93

#include <iostream>
using namespace std;

int main()
{
// A 2-Dimensional array
double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04,
364.55, 6234.12};

// Scan the array from the 3rd to the 7th member


cout << "Members of the array";
cout << "\nDistance [0][0]" << ": " << distance[0][0];
cout << "\nDistance [0][1]" << ": " << distance[0][1];
cout << "\nDistance [0][2]" << ": " << distance[0][2];
cout << "\nDistance [0][3]" << ": " << distance[0][3];
cout << "\nDistance [1][0]" << ": " << distance[1][0];
cout << "\nDistance [1][1]" << ": " << distance[1][1];
cout << "\nDistance [1][2]" << ": " << distance[1][2];
cout << "\nDistance [1][3]" << ": " << distance[1][3];

cout << endl;


return 0;
}
/*
Members of the array
Distance [0][0]: 44.14
Distance [0][1]: 720.52
Distance [0][2]: 96.08
Distance [0][3]: 468.78
Distance [1][0]: 6.28
Distance [1][1]: 68.04
Distance [1][2]: 364.55
Distance [1][3]: 6234.12
*/

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 14 of 20
Two Dimensional Arrays
Two Dimensional Array in Functions
#include <iostream>
#include <conio.h>
using namespace std;
void print(double temp[][])
{
cout << "Members of the array";
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 4; ++j)
cout << "\nDistance [" << i << "][" << j << "]: " <<
temp[i][j];

cout << endl;


}
int main()
{
// A 2-Dimensional array
double distance[][4] = {
{ 44.14, 720.52, 96.08, 468.78 },
{ 6.28, 68.04, 364.55, 6234.12 }
};

print(distance);

getch();
return 0;
}

error C2087: 'temp' : missing subscript

error C2664: 'print' : cannot convert parameter 1 from 'double [2][4]' to


'double [][1]'
Types pointed to are unrelated; conversion requires reinterpret_cast, C-style
cast or function-style cast

So how we can remove this error? But it seems to be valid for single dimensional array. Now change the
prototype of the function like this.

void print(double temp[][4])

#include <iostream>
#include <conio.h>

using namespace std;

const int DISTRICTS = 4;


const int MONTHS = 3;

void display( double funsales[DISTRICTS][MONTHS] );

void main()
{

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 15 of 20
Multidimensional Arrays
double sales[DISTRICTS][MONTHS]
= {{ 1432.07, 234.50, 654.01 },
{ 322.00, 13838.32, 17589.88 },
{ 9328.34, 934.00, 4492.30 },
{ 12838.29, 2332.63, 32.93 } };
display(sales);
cout << endl;

_getch();
}

void display( double funsales[DISTRICTS][MONTHS] )


{
int d, m;

cout << " Month \t";


cout << " \t1 \t2 \t3";

for(d=0; d<DISTRICTS; d++)


{
cout <<"\nDistrict " << d+1;
for(m=0; m<MONTHS; m++)
cout << "\t" << funsales[d][m];
}
cout << endl;
}

Output
Month 1 2 3
District 1 1432.07 234.5 654.01
District 2 322 13838.3 17589.9
District 3 9328.34 934 4492.3
District 4 12838.3 2332.63 32.93

Multidimensional Arrays
An array having more than two dimensions is called a multidimensional array.

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 16 of 20
Multidimensional Arrays

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 17 of 20
Live Demonstration in Lab
Live Demonstration in Lab
//---------------------------Author: Najeeb-Ur-Rehman------------------------------------
//---------------------------DATE: 27/02/2013------------------------------------------
//---------------------------Lab # 03--------------------------------------------------
//---------------------------Title: Array Practice -------------------------------------

#include<iostream>
#include<conio.h>
using namespace std;
int arraySum(int[]);
void arrayReferenceTest(int[]);
void printArray(int[]);
void changeMe(int&);

const int SIZE = 5;


const int ROWS = 3;
const int COLS = 5;

void initializeMat(int[][COLS]);
void squareMatElement(int[][COLS]);
void printMat(int[][COLS]);
void initializeArray1(int[]);
void main()
{

int nums[SIZE];
cout<<"Enter "<<SIZE<<" elements: ";
initializeArray1(nums);
cout<<"Entered array is: ";
for(int i=0; i<SIZE; i++)
{
cout<<nums[i]<<", ";
}
cout<<"\nPrint the array in reverse order:"<<endl;
for(int i=SIZE-1; i>=0;i--)
{
cout<<nums[i]<<" ";
}
int xy = arraySum(nums);
cout<<"\n Array sum : "<<xy<<endl;
printArray(nums);
arrayReferenceTest(nums);
cout<<"\n\n Modified array by refference test: ";
printArray(nums);

int mat2d[ROWS][COLS];

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


{
initializeArray1(mat2d[i]);
}
cout<<"Print ";
for(int i=0; i<ROWS; i++)
{
printArray(mat2d[i]);
}

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 18 of 20
Live Demonstration in Lab

int matrix[ROWS][COLS];

initializeMat(matrix);
cout<<"\nAfter Initialization: ";
printMat(matrix);
cout<<"\nAfter Square: ";
squareMatElement(matrix);
printMat(matrix);

int matrix3d[2][ROWS][COLS];

initializeMat(matrix3d[0]);
initializeMat(matrix3d[1]);
cout<<"\nAfter Initialization: ";
cout<<"\nLayer -1 [0]\n";
printMat(matrix3d[0]);
cout<<"\nLayer -2 [1]\n";
printMat(matrix3d[1]);

cout<<endl;
system("PAUSE");
}
void initializeArray1(int t[])
{
for(int i=0; i<SIZE; i++)
{
//cin>>nums[i];
t[i] = i*i;
}
}
int arraySum(int a[])
{
int sum=0;
for(int i = 0; i< SIZE; i++)
{
sum+= a[i]; //sum= sum + a[i];
}
return(sum);
}
void printArray(int x[])
{
cout<<"\n";
for(int i=0; i<SIZE; i++)
{
cout<<"["<<i<<"]: "<<x[i]<<" ";
}
cout<<"\n";
}

void arrayReferenceTest(int temp[])


{
int y=0;
for(int i=0; i<SIZE; i++)
{
y = temp[i];
temp[i] = temp[SIZE-i-1]; /// temp[0] = temp [10-0-1= 9]
temp[SIZE-i-1] = y; //

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 19 of 20
Live Demonstration in Lab
}
printArray(temp);
}

void initializeMat(int mat[][COLS])


{
for(int i = 0; i< ROWS; i++)
{
for(int j = 0; j< COLS; j++)
{
mat[i][j]=i+j;
}
}
}
void printMat(int mat[][COLS])
{
for(int i = 0; i< ROWS; i++)
{
cout<<"\n\t";
for(int j = 0; j< COLS; j++)
{
cout<<mat[i][j]<<" ";
}
}
}
void squareMatElement(int mat[][COLS])
{
for(int i = 0; i< ROWS; i++)
{
for(int j = 0; j< COLS; j++)
{
mat[i][j]*=mat[i][j];
}
}

}
/* Output

Enter 5 elements: Entered array is: 0, 1, 4, 9, 16,


Print the array in reverse order:
16 9 4 1 0
Array sum : 30

[0]: 0 [1]: 1 [2]: 4 [3]: 9 [4]: 16

[0]: 0 [1]: 1 [2]: 4 [3]: 9 [4]: 16

Modified array by refference test:


[0]: 0 [1]: 1 [2]: 4 [3]: 9 [4]: 16
Print
[0]: 0 [1]: 1 [2]: 4 [3]: 9 [4]: 16

[0]: 0 [1]: 1 [2]: 4 [3]: 9 [4]: 16

[0]: 0 [1]: 1 [2]: 4 [3]: 9 [4]: 16

After Initialization:

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman


Lab # 03: Arrays in C/C++ Page 20 of 20
Live Demonstration in Lab
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
After Square:
0 1 4 9 16
1 4 9 16 25
4 9 16 25 36
After Initialization:
Layer -1 [0]

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
Layer -2 [1]

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
Press any key to continue . . .
*/

CL103-Computer Programming By: Mr. Najeeb -Ur-Rehman

Vous aimerez peut-être aussi