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

Arrays: Namiq Sultan

This document discusses arrays in C++. It begins by explaining that arrays can hold multiple values of the same type, unlike regular variables which hold a single value. It then covers how to declare and initialize arrays, access array elements using indexes, pass arrays to functions, and process array contents. Code examples are provided to demonstrate these array concepts.

Uploaded by

omer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Arrays: Namiq Sultan

This document discusses arrays in C++. It begins by explaining that arrays can hold multiple values of the same type, unlike regular variables which hold a single value. It then covers how to declare and initialize arrays, access array elements using indexes, pass arrays to functions, and process array contents. Code examples are provided to demonstrate these array concepts.

Uploaded by

omer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 55

Chapter 7

Arrays

Namiq Sultan
University of Duhok
Department of Electrical and Computer Engineering

Reference: Starting Out with C++, Tony Gaddis, 2nd Ed.

C++ Programming, Namiq Sultan 1


7.1 Arrays Hold Multiple values

• Unlike regular variables, arrays can hold multiple values.

C++ Programming, Namiq Sultan 2


Figure 7-1

int count Enough memory for 1 int


12345

float price Enough memory for 1 float


56.981

char letter Enough memory for 1 char

C++ Programming, Namiq Sultan 3


Figure 7-2

int Days[6]; Days[0] 1st Element


Days[1] 2nd Element
Days[2] 3rd Element
Days[3] 4th Element
Days[4] 5th Element
Days[5] 6th Element

C++ Programming, Namiq Sultan 4


Table 7-1

Number of Size of Size of the


Array Declaration
Elements Each Element Array

c h a r le tte r s [2 5 ]; 25 1 byte 25 bytes

s h o r t r in g s [ 1 0 0 ]; 100 2 bytes 200 bytes

in t m ile s [ 8 4 ]; 84 4 bytes 336 bytes

flo a t t e m p [ 1 2 ]; 12 4 bytes 48 bytes

d o u b le d D is ta n c e [ 1 0 0 0 ]; 1000 8 bytes 8000 bytes

C++ Programming, Namiq Sultan 5


7.2 Accessing Array elements

• The individual elements of an array are assigned unique


subscripts. These subscripts are used to access the
elements.

C++ Programming, Namiq Sultan 6


Program 7-1
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element int array to store the values.

#include <iostream>
using namespace std;
int main()
{
short hours[6];
cout << "Enter the hours worked: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];

C++ Programming, Namiq Sultan 7


cin >> hours[4];
cin >> hours[5];
cout << "The hours you entered are:";
cout << " " << hours[0];
cout << " " << hours[1];
cout << " " << hours[2];
cout << " " << hours[3];
cout << " " << hours[4];
cout << " " << hours[5] << endl;
}

C++ Programming, Namiq Sultan 8


Program Output with Example Input

Enter the hours worked: 20 12 40 30 30 15 [Enter]


The hours you entered are: 20 12 40 30 30 15

C++ Programming, Namiq Sultan 9


Figure 7-7

C++ Programming, Namiq Sultan 10


Program 7-2
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array.
#include <iostream>
using namespace std;
int main()
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
for (int i = 0; i < 6; i++)
cin >> hours[i];
cout << "The hours you entered are:";
for (int i = 0; i < 6; i++)
cout << " " << hours[i];
cout << endl;
}
C++ Programming, Namiq Sultan 11
Program Output with Example Input

Enter the hours worked by six employees: 20 12 40 30 30 15 [Enter]


The hours you entered are: 20 12 40 30 30 15

C++ Programming, Namiq Sultan 12


7.4 Array Initialization

• Arrays may be initialized when they are declared.

C++ Programming, Namiq Sultan 13


Program 7-6
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream>
using namespace std;
int main()
{
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int i = 0; i < 12; i++)
{
cout << "Month " << (i + 1) << " has ";
cout << days[i] << " days.\n";
}
return 0;
}

C++ Programming, Namiq Sultan 14


Program Output

Month 1 has 31 days.


Month 2 has 28 days.
Month 3 has 31 days.
Month 4 has 30 days.
Month 5 has 31 days.
Month 6 has 30 days.
Month 7 has 31 days.
Month 8 has 31 days.
Month 9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.

C++ Programming, Namiq Sultan 15


Program 7-7
// This program uses an array of ten characters to store
// the first ten letters of the alphabet. The ASCII codes
// of the characters are displayed.
#include <iostream>
using namespace std;
int main()
{
char letters[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
cout << "Character" << "\t" << "ASCII Code\n";
cout << "--------" << "\t" << "----------\n";
for (int i = 0; i < 10; i++)
{
cout << letters[i] << "\t\t";
cout << int(letters[i]) << endl;
}
return 0;
}
C++ Programming, Namiq Sultan 16
Program Output

Character ASCII Code


--------- ----------
A 65
B 66
C 67
D 68
E 69
F 70
G 71
H 72
I 73
J 74

C++ Programming, Namiq Sultan 17


Partial Array Initialization

• When an array is being initialized, C++ does not require a


value for every element.

int numbers[7] = {1, 2, 4, 8};

C++ Programming, Namiq Sultan 18


Implicit Array Sizing
• It is possible to declare an array without specifying its size, as
long as you provide an initialization list.

float ratings[]={1.0, 1.5, 2.0, 2.5, 3.0};

C++ Programming, Namiq Sultan 19


Initializing With Strings

• When initializing a character array with a string, simply


enclose the string in quotation marks:

char name[] = "Warren";

C++ Programming, Namiq Sultan 20


Figure 7-11

C++ Programming, Namiq Sultan 21


Program 7-9
// This program displays the contents of two char arrays.
#include <iostream>
using namespace std;
int main()
{
char name1[] = "Holly";
char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'};

cout << name1 << endl;


cout << name2 << endl;
}

C++ Programming, Namiq Sultan 22


Program Output

Holly
Warren

C++ Programming, Namiq Sultan 23


7.5 Processing Array Contents

• Individual array elements are processed like any other type


of variable.

C++ Programming, Namiq Sultan 24


Program 7-10
// This program stores, in an array, the hours worked by 5
// employees who all make the same hourly wage.
#include <iostream>
using namespace std;
int main()
{
int hours[5];
float payRate, grossPay ;

cout << "Enter the hours worked by 5 employees who all\n";


cout << "earn the same hourly rate.\n";
for (int index = 0; index < 5; index++)
{
cout << "Employee #" << (index + 1) << ": ";
cin >> hours[index];
}
C++ Programming, Namiq Sultan 25
cout << "Enter the hourly pay rate for the employees: ";
cin >> payRate;
cout << "Here is the gross pay for each employee:\n";

for (int index = 0; index < 5; index++)


{
grossPay = hours[index] * payRate;
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}

C++ Programming, Namiq Sultan 26


Program Output with Example Input
Enter the hours worked by 5 employees who all
earn the same hourly rate.
Employee #1: 5 [Enter]
Employee #2: 10 [Enter]
Employee #3: 15 [Enter]
Employee #4: 20 [Enter]
Employee #5: 40 [Enter]
Enter the hourly pay rate for all the employees: 12.75 [Enter]
Here is the gross pay for each employee:
Employee #1: $63.75
Employee #2: $127.50
Employee #3: $191.25
Employee #4: $255.00
Employee #5: $510.00

C++ Programming, Namiq Sultan 27


7.8 Arrays As Function Arguments

• To pass an array as an argument to a function, pass the


name of the array.

C++ Programming, Namiq Sultan 28


Program 7-13 Passing array element
#include <iostream>
using namespace std;

void Show(int Num)


{
cout << Num << " ";
}
int main()
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
for (int i = 0; i < 8; i++)
Show(collection[i]);
return 0;
}
C++ Programming, Namiq Sultan 29
Program Output

5 10 15 20 25 30 35 40

C++ Programming, Namiq Sultan 30


Program 7-14 Passing Array
void show(int nums[])
{
for (int index = 0; index < 8; index++)
cout << nums[index] << " ";
}

int main()
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
show(collection); // Passing address of array collection
}

C++ Programming, Namiq Sultan 31


Program Output

5 10 15 20 25 30 35 40

C++ Programming, Namiq Sultan 32


Program 7-16
// Display the contents of an integer array of any size.
void show(int nums[], int elements){
for (int index = 0; index < elements; index++)
cout << nums[index] << " ";
}
int main(){
int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[4] = {2, 4, 6, 8};
int set3[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
show(set1, 8);
cout << endl;
show(set2, 4);
cout << endl;
show(set3, 12);
}
C++ Programming, Namiq Sultan 33
Program Output

5 10 15 20 25 30 35 40
2468
1 2 3 4 5 6 7 8 9 10 11 12

C++ Programming, Namiq Sultan 34


Program 7-17
// Double the contents of the elements within an array.

void doubleArray(int [], int); // Function prototype


const int Size = 12;

int main()
{
int set[Size] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
cout << "The arrays values are:\n";
for (int index = 0; index < Size; index++)
cout << set[index] << " ";
cout << endl;
doubleArray(set, Size);
cout << "After calling doubleArray, the values are:\n";
C++ Programming, Namiq Sultan 35
for (int index = 0; index < Size; index++)
cout << set[index] << " ";
cout << endl;
return 0;
}

void doubleArray(int nums[], int size)


{
for (int index = 0; index < size; index++)
nums[index] *= 2;
}

C++ Programming, Namiq Sultan 36


Program Output

The array values are:


1 2 3 4 5 6 7 8 9 10 11 12
After calling doubleArray, the values are:
2 4 6 8 10 12 14 16 18 20 22 24

C++ Programming, Namiq Sultan 37


Examples
• C++ program to find the largest number in a given array.
• Repeat (1) using a function that accepts an array and returns the
largest element.
• Construct an array of 20 elements of Fibonacci series 1, 1, 2, 3, 5,
8, 13, ...
• Sort an array of three elements.

HW:
• Count the repetition of number 0 in a given array.
• Find the sum of smallest and largest elements of a given array.
• Reverse the elements of a given array.
• C++ program to find the largest two numbers in a given array.
C++ Programming, Namiq Sultan 38
7.10 Two-dimensional Arrays

• A two-dimensional array is like several identical arrays put


together. It is useful for storing multiple sets of data.

C++ Programming, Namiq Sultan 39


Program 7-18
// This program demonstrates a two-dimensional array.
#include <iostream>
using namespace std;

int main()
{
float sales[3][4]; // 2D array, 3 rows and 4 columns.
float totalSales = 0;// To hold the total sales.
int div, qtr; // Loop counters.

cout << "This program calculate the total sales of\n";


cout << "all the company's divisions.\n";
cout << "Enter the following sales information:\n\n";

C++ Programming, Namiq Sultan 40


// Nested loops to fill the array with quarterly
// sales figures for each division.
for (div = 0; div < 3; div++)
{
for (qtr = 0; qtr < 4; qtr++)
{
cout << "Division " << (div + 1);
cout << ", Quarter " << (qtr + 1) << ": $";
cin >> sales[div][qtr];
}
cout << endl; // Print blank line.
}

C++ Programming, Namiq Sultan 41


// Nested loops to add all the elements.
for (div = 0; div < 3; div++)
for (qtr = 0; qtr < 4; qtr++)
totalSales += sales[div][qtr];

cout << "The total sales for the company are: $";
cout << totalSales << endl;
}

C++ Programming, Namiq Sultan 42


Program Output with Example Input
This program will calculate the total sales of
all the company's divisions.
Enter the following sales information:

Division 1, Quarter 1: $31569.45 [Enter]


Division 1, Quarter 2: $29654.23 [Enter]
Division 1, Quarter 3: $32982.54 [Enter]
Division 1, Quarter 4: $39651.21 [Enter]

Division 2, Quarter 1: $56321.02 [Enter]


Division 2, Quarter 2: $54128.63 [Enter]
Division 2, Quarter 3: $41235.85 [Enter]
Division 2, Quarter 4: $54652.33 [Enter]

C++ Programming, Namiq Sultan 43


Output continues

Division 3, Quarter 1: $29654.35 [Enter]


Division 3, Quarter 2: $28963.32 [Enter]
Division 3, Quarter 3: $25353.55 [Enter]
Division 3, Quarter 4: $32615.88 [Enter]

The total sales for the company are: $456782.34

C++ Programming, Namiq Sultan 44


Continued …

• Task: Modify the last program to print the sales of each


division quarterly.

C++ Programming, Namiq Sultan 45


Two-dimensional Array Initialization

• Both of the following declarations perform the same


initialization:
int Hours[3][2]={{8,5},{7,9},{6,3}};
int Hours[3][2]={8,5,7,9,6,3};

• It is helpful to write the declaration as:


int Hours[3][2]={ 8,5,
7,9,
6,3};

C++ Programming, Namiq Sultan 46


Passing Two-dimensional Arrays to Functions

• When a two-dimensional array is passed to a


function, the parameter type must contain a size
declarator for the number of columns.

C++ Programming, Namiq Sultan 47


Program 7-19
// This program demonstrates a function that accepts a two-
// dimensional array as an argument.
#include <iostream>
using namespace std;
void show(int [][4], int); // Function prototype

int main()
{
int Table[3][4] ={1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12};

C++ Programming, Namiq Sultan 48


int Table2[4][4] = {10, 20, 30, 40,
50, 60, 70, 80,
90, 100, 110, 120,
130, 140, 150, 160};
Cout<<"The contents of Table1 are:\n";
show(Table1, 3);
Cout<<"The contents of Table2 are:\n";
show(Table2, 4);
}

C++ Programming, Namiq Sultan 49


// This function accepts a two-dimensional integer array as an
// argument. The array must have four columns. The second
// argument, Rows, specifies the number of rows in the array.
// The function displays the contents of the array.
void show(int Array[][4], int Rows)
{
for(int x=0; x<Rows; x++)
{
for(int y=0; y<4; y++)
cout<< Array[x][y] << "\t";
cout << endl;
}
}
C++ Programming, Namiq Sultan 50
7.10 Arrays of Strings

• A two-dimensional array of characters can be used as an


array of C-strings.

C++ Programming, Namiq Sultan 51


Program 7-20
int main()
{
char months[12][10] = {"January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November",
"December"};
int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for (int i = 0; i < 12; i++){
cout << months[i] << " has ";
cout << days[i] << " days.\n";
}
return 0;
}
C++ Programming, Namiq Sultan 52
Program Output
January has 31 days.
February has 28 days.
March has 31 days.
April has 30 days.
May has 31 days.
June has 30 days.
July has 31 days.
August has 31 days.
September has 30 days.
October has 31 days.
November has 30 days.
December has 31 days.
C++ Programming, Namiq Sultan 53
Three Dimensional Arrays and Beyond

• C++ allows you to create arrays with virtually any number


of dimensions.
• Here is an example of a three-dimensional array
declaration:

float seat[3][5][8];

C++ Programming, Namiq Sultan 54


Homework
• Add two 3x3 matrices and put the result in a third matrix.
• Exchange the elements of first column and second column of a
given matrix.
• Find the sum of elements of upper-right triangle of a 5x5 matrix.
• Print the lower-left triangle of a 5x5 matrix.
• Write a program to print transpose of a matrix .

C++ Programming, Namiq Sultan 55

You might also like