Matrix multiplication2

Download Report

Transcript Matrix multiplication2

GE 211 Programming in C++
Array &Matrix
Dr. Ahmed Telba
Initializing an Array
• DataType ArrayName[dimension] = { element1, element2, …, elementn};
• examples of declaring an initializing arrays:
• int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
• double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
#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;
}
• This would produce:
• 2nd member = 720.52
• 5th member = 6.28
#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;
}
•
•
•
•
•
•
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
This would produce:
// 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;
}
In both cases, this would produce:
Members of the array
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
Filling Up an Array
When you declare an array without initializing it, we have mentioned that the compiler reserves an amount of memory
space for the members of the array. But that is only what the compiler does. Each part of such reserved space is
filled with garbage. Therefore, you must make sure that you know the value held by a member of the array before
making any attempt to process the value held by that member of the array. Consider the following example:
#include <iostream>
using namespace std;
int main()
{
const int numberOfItems = 5;
double distance[numberOfItems];
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;
}
This would produce:
Distance 1: -9.25596e+061
Distance 2: -9.25596e+061
Distance 3: -9.25596e+061
Distance 4: -9.25596e+061
Distance 5: -9.25596e+061
#include <iostream>
using namespace std;
int main()
{
const int numberOfItems = 5;
double distance[numberOfItems] = {44.14, 720.52, 96.08};
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;
}
•
•
•
•
•
•
This would produce:
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 0
Distance 5: 0
#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 << "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;
cout << "Distance 6: " << distance[5] << endl;
cout << "Distance 7: " << distance[6] << endl;
cout << "Distance 8: " << distance[7] << endl;
return 0;
}
This would produce:
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
Distance 6: 2.64214e-308
Distance 7: 2.12414e-314
Distance 8: 1.00532e-307
Operations on Arrays
#include <iostream>
using namespace std;
int main()
{
// We know that we need a constant number of elements
const int max = 10;
int number[max];
// We will calculate their sum
int sum = 0;
cout << "Please type 10 integers.\n";
for( int i = 0; i < max; i++ )
{
cout << "Number " << i + 1 << ": ";
cin >> number[i];
sum += number[i];
}
cout << "\n\nThe sum of these numbers is " << Sum << "\n\n";
return 0;
}
This would produce:Please type 10 integers.
Number 1: 120
Number 2: 42
Number 3: 75
Number 4: 38
Number 5: 904
Number 6: 6
Number 7: 26
Number 8: 55
Number 9: 92
Number 10: 20
The sum of these numbers is 1378
// A 2-Dimensional array
double distance[][4] = {
{ 44.14, 720.52, 96.08, 468.78 },
{ 6.28, 68.04, 364.55, 6234.12 }
};
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;
}
This would produce:
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
Multidimensional Arrays
[0][0] [0][1] [0][2] [0][3] [0][4]
[1][0] [1][1] [1][2] [1][3] [1][4]
[2][0] [2][1] [2][2] [2][3] [2][4]
int anArray[3][5] ={
{ 1, 2, 3, 4, 5, }, // row 0
{ 6, 7, 8, 9, 10, }, // row 1
{ 11, 12, 13, 14, 15 } // row 2
};
Matrix addition code
#include <iostream>
void mult_matrices(int a[][3], int b[][3], int result[][3]);
void print_matrix(int a[][3]);
void main(void)
{
int p[3][3] = { {1, 3, -4}, {1, 1, -2}, {-1, -2, 5} };
int q[3][3] = { {8, 3, 0}, {3, 10, 2}, {0, 2, 6} };
int r[3][3];
mult_matrices(p, q, r);
cout<<_matrix(r);
}
void mult_matrices(int a[][3], int b[][3], int result[][3])
{
int i, j, k;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
for(k=0; k<3; k++)
{
result[i][j] = a[i][k] + b[k][j];
}
}
}
}
void print_matrix(int a[][3])
{
int i, j;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}}
#include <stdio.h>
void add_matrices(int a[][3], int b[][3], int result[][3]);
void print_matrix(int a[][3]);
void main(void)
{
int p[3][3] = { {1, 3, -4}, {1, 1, -2}, {-1, -2, 5} };
int q[3][3] = { {8, 3, 0}, {3, 10, 2}, {0, 2, 6} };
int r[3][3];
add_matrices(p, q, r);
printf("\nMatrix 1:\n");
print_matrix(p);
printf("\nMatrix 2:\n");
print_matrix(q);
printf("\nResult:\n");
print_matrix(r);
}
void add_matrices(int a[][3], int b[][3], int result[][3])
{
int i, j;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
result[i][j] = a[i][j] + b[i][j];
}
}
}
void print_matrix(int a[][3])
{
int i, j;
for (i=0; i<3; i++)
{
for (j=0; j<3; j++)
{
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
Matrix addition
initialization of Two-Dimensional Array
• An two-dimensional array can be initialized
along with declaration. For two-dimensional
array initialization, elements of each row are
enclosed within curly braces and separated
by commas. All rows are enclosed within curly
braces.
Referring to Array Elements
• To access the elements of a two-dimensional array, we need a
pair of indices: one for
the row position and one for the column position. The format
is as simple as:
name[rowIndex][columnIndex]
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;
system("pause");
return 0; }
Multidimensional arrays
• Multidimensional arrays can be described as
"arrays of arrays". For example, a
bidimensional array can be imagined as a
bidimensional table made of elements, all of
them of a same uniform data type.
• int jimmy [3][5];
#define WIDTH 5
#define HEIGHT 3
int jimmy [HEIGHT][WIDTH];
int n,m; int main () {
for (n=0;n<HEIGHT;n++) for (m=0;m<WIDTH;m++)
{ jimmy[n][m]=(n+1)*(m+1);
}
return 0;
}
• jimmy[1][3]
•
#define HEIGHT 3
• #define HEIGHT 4
// arrays as parameters 5 10 15 2 4 6 8 10
#include <iostream>
using namespace std;
void printarray (int arg[], int length)
{ for (int n=0; n<length; n++) cout << arg[n] << " ";
cout << "\n";
} int main () { int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0; }
• char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
/ null-terminated sequences of characters
#include <iostream>
using namespace std;
int main ()
{
char question[] = "Please, enter your first name: ";
char greeting[] = "Hello, ";
char yourname [80];
cout << question;
cin >> yourname;
cout << greeting << yourname << "!";
return 0;
}
declaring an initializing arrays:
•
Here are examples of declaring an initializing arrays:
•
•
•
•
int number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12};
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};
• int n, m; double x[5][6];
• FILE *inp; inp = fopen("IN.DAT","r");
• for (n = 0; n < 5; ++n) { for (m = 0; m < 6; ++m)
fscanf (inp, "%lf", &x[n][m]);
• } fclose (inp);
//adding Matrix
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a[10][10],b[10][10],c[10][10],m,n,i,j;
cout<<"Enter number of rows: ";
cin>>m;
cout<<"Enter number of coloumns: ";
cin>>n;
cout<<endl<<"Enter elements of matrix A: "<<endl;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<"Enter element a"<<i+1<<j+1<<": ";
cin>>a[i][j];
}
}
cout<<endl<<"Enter elements of matrix B: "<<endl;
//Coding by: Snehil Khanor
//http://WapCPP.blogspot.com
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<"Enter element b"<<i+1<<j+1<<": ";
cin>>b[i][j];
}
}
Diagonal Matrix
1000
0200
0030
0004
• x(i,j) is on diagonal iff i = j
• number of diagonal elements in
an n x n matrix is n
• non diagonal elements are zero
• store diagonal only vs n2 whole
Program 7-2
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include <iostream.h>
void main(void)
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
for (int count = 0; count < 6; count++)
cin >> hours[count];
cout << "The hours you entered are:";
for (count = 0; count < 6; count++)
cout << " " << hours[count];
cout << endl;
}
29
Program 7-6
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream.h>
void main(void)
{
int days[12] = {31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < 12; count++)
{
cout << "Month " << (count + 1) << " has ";
cout << days[count] << " days.\n";
}
}
30
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.
31
#include <iostream>
using namespace std;
void MultiplyWithOutAMP() {
int aMatrix[3][2] = {{1, 4}, {2, 5}, {3, 6}};
int bMatrix[2][3] = {{7, 8, 9}, {10, 11, 12}};
int product[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
// Multiply the row of A by the column of B to get the row, column of product.
for (int inner = 0; inner < 2; inner++) {
product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
}
cout << product[row][col] << " ";
}
cout << "\n";
}
}
int main() {
// cout << bMatrix[3][2] << "\t";
// cout << aMatrix[3][2] << "\t";
MultiplyWithOutAMP();
getchar();
system("pause");
return 0;
}
Using pointer(Multiplier)
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int **mat1;
int **mat2;
int **result;
int row,col;
cout<<"Please enter row/col"<<endl;
cin>>row>>col;
mat1 = new int *[row];
mat2 = new int *[row];
result = new int *[row];
int k,i,j;
for (k=0; i<row; k++)
mat1[k] = new int[col];
mat2[k] = new int[col];
result[k] = new int[col];
for (i=0; i<row; i++)
for (j=0; j<col; j++)
for (j=0; j<row; j++)
for(i=0; i<col; i++)
result[i][k] += (mat1 [i][k] * mat2[k][j]);
cout<<setw(4)<<result[i][k];
#include <iomanip> // pointer Multiplier
#include <iostream>
using namespace std;
int main()
{
int **mat1;
int **mat2;
int **result;
int row,col;
cout<<"Please enter row/col"<<endl;
cin>>row>>col;
mat1 = new int *[row];
mat2 = new int *[row];
result = new int *[row];
int k,i,j;
for (k=0; k<row; k++)
mat1[k] = new int[col];
mat2[k] = new int[col];
result[k] = new int[col];
for (i=0; i<row; i++)
for (j=0; j<col; j++)
mat1[k][i] = k + i;
for (j=0; j<row; j++)
mat2[i][k] = j + k;
for(i=0; i<col; i++)
result[i][k] += (mat1 [i][k] * mat2[k][j]);
cout<<setw(4)<<result[i][k];
cout<<endl<<"Displaying Matrix A: "<<endl<<endl;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl<<endl;
}
cout<<endl<<"Displaying Matrix B: "<<endl<<endl;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<b[i][j]<<" ";
}
cout<<endl<<endl;
}
cout<<endl<<"Matrix A + Matrix B = Matrix C: "<<endl<<endl;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cout<<a[i][j]+b[i][j]<<" ";
}
cout<<endl<<endl;
}
getch();
}
Adding matrix: c++ program to add two matrices
#include<iostream>
using namespace std;
main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
cout << "Enter the number of rows and columns of matrix ";
cin >> m >> n;
cout << "Enter the elements of first matrix\n";
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
cin >> first[c][d];
cout << "Enter the elements of second matrix\n";
for ( c = 0 ; c < m ;c++ )
for ( d = 0 ; d < n ; d++ )
cin >> second[c][d];
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d];
cout << "Sum of entered matrices:-\n";
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
cout << sum[c][d] << "\t";
cout << endl;
}
system("pause");
return 0;
}
A number is taken from the user number with reverse digits is displayed
#include<iostream>
using namespace std;
int main()
{
//clrscr();
long int n,rev=0,m;
cout<<"please enter a five digit no.: ";
cin>>n;
while(n>0)
//Coding by: Snehil Khanor
//http://WapCPP.blogspot.com
{
m=n%10;
rev=rev*10+m;
n=n/10;
}
cout<<rev;
//
system("pause");
return 0;
}
Address in memory
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: std::cout << age << std::endl;
12: return 0;
13: }
Character in Array
1: char letter[4];
2: letter[0]='M';
3: letter[1]='a';
4: letter[2]='r';
5: letter[3]='k';
6: ... *(letter+2) ...
• Question (4)
•
• Using the switch or if statement, write a C program that takes in an
integer numerical grade num_grade from the keyboard and
returns to the screen a letter_grade according to
• the following scale:
• letter_grade is A if num_grade ≥ 90
• letter_grade is B if 80 ≤ num_grade < 90
• letter_grade is C if 70 ≤ num_grade < 80
• letter_grade is D if 60 ≤ num_grade < 70
• letter_grade is F if num_grade < 60
• Check the correctness of your program and print down the outputs
of your program for a
• student with a score of 100 and another with a score of 65.
include <iostream>
using namespace std;
int main()
{
This would produce:
2nd member = 720.52
5th member = 6.28
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;
}
#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;
}
•
This would produce:
•
•
•
•
•
Distance 1: 44.14
Distance 2: 720.52
Distance 3: 96.08
Distance 4: 468.78
Distance 5: 6.28
#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 << "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;
}
#include <iostream>
using namespace std;
int main()
{
// We know that we need a constant number of elements
const int max = 10;
int number[max];
// We will calculate their sum
int sum = 0;
cout << "Please type 10 integers.\n";
for( int i = 0; i < max; i++ )
{
cout << "Number " << i + 1 << ": ";
cin >> number[i];
sum += number[i];
}
cout << "\n\nThe sum of these numbers is " << Sum << "\n\n";
return 0;
}
#include <iostream>
using namespace std;
void DisplayTheArray(double member[5]);
int main()
{
const int numberOfItems = 5;
double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
return 0;
}
void DisplayTheArray(double member[5])
{
for(int i = 0; i < 5; ++i)
cout << "\nDistance " << i + 1 << ": " << member[i];
cout << endl;
}
Declaring and Initializing a 2-Dimensional Array
#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;
}
2-Dimensional array
#include <iostream>
using namespace std;
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 }
};
// Scan the array from the 3rd to the 7th member
cout << "Members of the array";
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 4; ++j)
cout << "\nDistance [" << i << "][" << j << "]: " << distance[i][j];
cout << endl;
return 0;
}
Multidimensional Arrays
•
•
#include <iostream>
using namespace std;
•
void MultiplyWithOutAMP() {
•
•
•
int aMatrix[3][2] = {{1, 4}, {2, 5}, {3, 6}};
int bMatrix[2][3] = {{7, 8, 9}, {10, 11, 12}};
int product[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
•
•
•
•
•
•
•
•
•
•
•
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
// Multiply the row of A by the column of B to get the row, column of product.
for (int inner = 0; inner < 2; inner++) {
product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
}
std::cout << product[row][col] << " ";
}
std::cout << "\n";
}
}
•
•
•
•
•
main() {
MultiplyWithOutAMP();
getchar();
system("pause");
}
#include <iostream>
using namespace std;
#define MAX 50
void mulmatvec(int m, int n, double a[MAX][MAX], double x[MAX], double b[MAX]){
int i,j;
for(i = 0; i < m; i++){
b[i] = 0.;
for(j = 0; j < n; j++)
b[i] += a[i][j]*x[j];
}
return;
}
int main(){
int i,j,m,n;
double a[MAX][MAX], x[MAX], b[MAX];
cout << "Enter the number of rows in the matrix \n";
cin >> m;
cout << "Enter the number of columns in the matrix \n";
cin >> n;
cout << "Enter the matrix by rows\n";
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
cin >> a[i][j];
cout << "Enter the vector\n";
for(j = 0; j < n; j++)
cin >> x[j];
mulmatvec(m,n,a,x,b);
cout << "\nA*x = \n";
for(i = 0; i < m; i++)
cout << b[i] << "\n";
}
•
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int i,j;
int arr[6][6];
for(i=0;i<=5;i++){
for(j=5;j>=0;j--){
if(i+j==5) arr[i][j]=0; 'diagonal
else if(i+j>5) arr[i][j]=-1; 'lower-right side
else arr[i][j]=1; 'upper-left side
}
}
for(i=0;i<=5;i++){
for(j=0;j<=5;j++)
cout<<arr[i][j]<<"\t";
cout<<endl;
}
getch();
return 0;
}
• Initializing array
• To assign values to the array, you can write those
values as below.
•
int i[]= {1, 2, 3, 4, 5};//The array got values
or
•
int i[5];
•
i[0]=1;
•
i[1]=2;
•
i[2]=3;
•
i[3]=4;
•
i[4]=5;
Adding two Matrix
#include<iostream>
using namespace std;
main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
cout << "Enter the number of rows and columns of matrix ";
cin >> m >> n;
cout << "Enter the elements of first matrix\n";
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
cin >> first[c][d];
cout << "Enter the elements of second matrix\n";
for ( c = 0 ; c < m ;c++ )
for ( d = 0 ; d < n ; d++ )
cin >> second[c][d];
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d];
cout << "Sum of entered matrices:-\n";
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
cout << sum[c][d] << "\t";
cout << endl;
}
return 0;
}
Matrix multiplication in C++
• Matrices can be used to perform transformations. For example, in
2D and 3D space. Transformations include, but are not limited
to, rotating, scaling and translating. Transformations can be
combined by multiplying the matrices with each other.
• For example, you might want to:
• scale an object with a factor of 2
• rotate it 45 degrees around the Y-axis
• translate it to (5,5,5)
• Each of the above steps can be represented with a four by four
matrix (four rows and four columns). Multiplication of matrices is
done by multiplying each row of the first matrix with each column
of the second matrix and summing up the results. The number of
columns of the first matrix needs to be equal to the number of rows
of the second matrix. For example (4 x 4) x (4 x 4) is allowed.
However, (4 x 3) x (4 x 3) is not allowed.
Matrix multiplication
[[1x1 + 2x0 + 3x0 + 4x0] = 1, [1x0 + 2x1 + 3x0 + 4x0] = 2, [1x0 + 2x0 + 3x1 + 4x0] = 3,
[1x0 + 2x0 + 3x0 + 4x1] = 4]]
Code
#include <iostream>
void MultiplyWithOutAMP() {
int aMatrix[3][2] = {{1, 4}, {2, 5}, {3, 6}};
int bMatrix[2][3] = {{7, 8, 9}, {10, 11, 12}};
int product[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
// Multiply the row of A by the column of B to get the row, column of product.
for (int inner = 0; inner < 2; inner++) {
product[row][col] += aMatrix[row][inner] * bMatrix[inner][col];
}
std::cout << product[row][col] << " ";
}
std::cout << "\n";
}
}
void main() {
MultiplyWithOutAMP();
getchar();
}
// C++ multiplication of the matrix x and matrix y and stores the result in matrix z
#include <iostream>
using namespace std;
#define m 3
#define c 2
#define n 4
int main(void)
{
int i, j, k;
// first matrix
int x[m][c] = {{1,2},{3,4},{5,6}};
// second matrix
int y[c][n] = {{7,8,9,10},{11,12,13,14}};
// for storing the matrix product result
int z[m][n];
for(i=0; i<m; i++)
for(j=0; j<n; j++)
{
z[i][j] = 0;
for(k=0; k<c; k++)
// same as z[i][j] = z[i][j] + x[i][k] * y[k][j];
z[i][j] += x[i][k] * y[k][j];
}
cout<<"\nMultiply matrix x and matrix y,";
cout<<"\nThen store the result in matrix z.";
cout<<"\nMatrix x is 3x2, and matrix y is 2x4,";
cout<<"\nso, the result, z should be matrix 3x4\n";
cout<<"\nThe matrix product is: \n";
for (i=0; i<m; i++)
{
cout<<"\n";
for(j=0; j<n; j++)
// display the result...
cout<<" "<<z[i][j];
}
cout<<endl;
return 0;
}
Output example:
Multiply matrix x and matrix y,
Then store the result in matrix z.
Matrix x is 3x2, and matrix y is 2x4,
so, the result, z should be matrix 3x4
The matrix product is:
29 32 35 38
65 72 79 86
101 112 123 134
Press any key to continue . . .
Chapter 7 – Arrays
67
7.1 Arrays Hold Multiple values
• Unlike regular variables, arrays can hold
multiple values.
68
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
A
69
Figure 7-2
70
Table 7-1
Array Declaration
char letters[25];
short rings[100];
int miles[84];
float temp[12];
doubledDistance[1000];
Number of
Elements
25
100
84
12
1000
Size of
Each Element
Size of the
Array
1
2
4
4
8
25 bytes
200 bytes
336 bytes
48 bytes
8000 bytes
byte
bytes
bytes
bytes
bytes
71
7.2 Accessing Array elements
• The individual elements of an array are
assigned unique subscripts. These subscripts
are used to access the elements.
72
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.h>
void main(void)
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
cin >> hours[0];
cin >> hours[1];
cin >> hours[2];
cin >> hours[3];
73
Program continues
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;
}
74
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
75
Figure 7-7
76
Program 7-2
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include <iostream.h>
void main(void)
{
short hours[6];
cout << "Enter the hours worked by six employees: ";
for (int count = 0; count < 6; count++)
cin >> hours[count];
cout << "The hours you entered are:";
for (count = 0; count < 6; count++)
cout << " " << hours[count];
cout << endl;
}
77
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
78
Program 7-3
// This program asks the user for the number of hours worked
// by 6 employees. It uses a 6-element short array to store the
// values.
#include<iostream.h>
void main(void)
{
short hours[6];
cout << "Enter the hours worked by six employees.\n";
for (int count = 1; count <= 6; count++)
{
cout << "Employee " << count << ": ";
cin >> hours[count - 1];
}
cout << "The hours you entered are\n";
79
Program continues
for (count = 1; count <= 6; count++)
{
cout << "Employee " << count << ": ";
cout << hours[count - 1] << endl;
}
}
80
Program Output with Example Input
Enter the hours worked by six employees.
Employee 1: 20 [Enter]
Employee 2: 12 [Enter]
Employee 3: 40 [Enter]
Employee 4: 30 [Enter]
Employee 5: 30 [Enter]
Employee 6: 15 [Enter]
The hours you entered are
Employee 1: 20
Employee 2: 12
Employee 3: 40
Employee 4: 30
Employee 5: 30
Employee 6: 15
81
7.3 No Bounds Checking in C++
• C++ gives you the freedom to store data past
an array’s boundaries.
82
Program 7-4
// This program unsafely accesses an area of memory by writing
// values beyond an array's boundary.
// WARNING: If you compile and run this program, it could cause
// the computer to crash.
#include <iostream.h>
void main(void)
{
short values[3];
// An array of 3 short integers.
cout << "I will store 5 numbers in a 3 element array!\n";
for (int count = 0; count < 5; count++)
values[count] = 100;
cout << "If you see this message, it means the computer\n";
cout << "has not crashed! Here are the numbers:\n";
for (int count = 0; count < 5; count++)
cout << values[count] << endl;
}
83
Figure 7-8
84
7.4 Array Initialization
• Arrays may be initialized when they are
declared.
85
Program 7-5
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream.h>
void main(void)
{
int days[12];
days[0] = 31;
days[1] = 28;
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
//
//
//
//
//
//
//
January
February
March
April
May
June
July
86
Program continues
days[7] = 31; // August
days[8] = 30; // September
days[9] = 31; // October
days[10] = 30; // November
days[11] = 31; // December
for (int count = 0; count < 12; count++)
{
cout << "Month " << (count + 1) << " has ";
cout << days[count] << " days.\n";
}
}
87
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.
88
Program 7-6
// This program displays the number of days in each month.
// It uses a 12-element int array.
#include <iostream.h>
void main(void)
{
int days[12] = {31, 28, 31, 30,
31, 30, 31, 31,
30, 31, 30, 31};
for (int count = 0; count < 12; count++)
{
cout << "Month " << (count + 1) << " has ";
cout << days[count] << " days.\n";
}
}
89
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.
90
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.h>
void main(void)
{
char letters[10] = {'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J'};
cout << "Character" << "\t" << "ASCII Code\n";
cout << "--------" << "\t" << "----------\n";
for (int count = 0; count < 10; count++)
{
cout << letters[count] << "\t\t";
cout << int(letters[count]) << endl;
}
}
91
Program Output
Character
--------A
B
C
D
E
F
G
H
I
J
ASCII Code
---------65
66
67
68
69
70
71
72
73
74
92
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};
93
Program 7-8
// This program has a partially initialized array.
#include <iostream.h>
void main(void)
{
int numbers[7] = {1, 2, 4, 8}; // Initialize the
// first 4 elements.
cout << "Here are the contents of the array:\n";
for (int index = 0; index < 7; index++)
cout << numbers[index] << endl;
}
94
Program Output
Here are the contents of the array:
1
2
4
8
0
0
0
95
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};
96
Initializing With Strings
• When initializing a character array with a
string, simply enclose the string in quotation
marks:
char name[] = “Warren”;
97
Figure 7-11
98
Program 7-9
// This program displays the contents of two char arrays.
#include <iostream.h>
void main(void)
{
char name1[] = "Holly";
char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'};
cout << name1 << endl;
cout << name2 << endl;
}
99
Program Output
Holly
Warren
100
7.5 Processing Array Contents
• Individual array elements are processed like
any other type of variable.
101
Program 7-10
// This program stores, in an array, the hours worked by 5
// employees who all make the same hourly wage.
#include <iostream.h>
void main(void)
{
int hours[5];
float payRate;
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];
}
102
Program continues
cout << "Enter the hourly pay rate for all the employees: ";
cin >> payRate;
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < 5; index++)
{
float grossPay = hours[index] * payRate;
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
103
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
104
Program 7-11
// This program stores, in an array, the hours worked by 5
// employees who all make the same hourly wage. It then
// displays the gross pay, including any overtime.
#include <iostream.h>
// Constant for defining the array size
void main(void)
{
int hours[5];
float payRate;
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];
}
105
Program continues
cout << "Enter the hourly pay rate for all the employees: ";
cin >> payRate;
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < 5; index++)
{
float grossPay, overTime;
if (hours[index] > 40)
{
// Calculate pay for 40 hours.
grossPay = 40 * payRate;
// Calculate overtime pay.
overTime = (hours[index] - 40) * 1.5 * payRate;
// Add regular pay and overtime pay.
grossPay += overTime;
}
106
Program continues
else
grossPay = hours[index] * payRate;
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
107
Program Output with Example Input
Enter the hours worked by 5 employees who all
earn the same hourly rate.
Employee #1: 10 [Enter]
Employee #2: 20 [Enter]
Employee #3: 50 [Enter]
Employee #4: 40 [Enter]
Employee #5: 60 [Enter]
Enter the hourly pay rate for all the employees: 12.75 [Enter]
Here is the gross pay for each employee:
Employee #1: $127.50
Employee #2: $255.00
Employee #3: $701.25
Employee #4: $510.00
Employee #5: $892.50
108
7.6 Focus on Software Engineering:
Parallel Arrays
• By using he same subscript, you can build
relationships between data stored in two or
more arrays.
109
Program 7-12
// This program stores, in two arrays, the hours worked by 5
// employees, and their hourly pay rates.
#include <iostream.h>
// Constant for defining the array size
const int numEmps = 5;
void main(void)
{
int hours[numEmps];
float payRate[numEmps];
cout << "Enter the hours worked by “ << numEmps
<< “ employees and their\n";
cout << "hourly rates.\n";
for (int index = 0; index < numEmps; index++)
{
cout << "hours worked by employee #" << (index + 1);
cout << ": ";
110
Program continues
cin >> hours[index];
cout << "Hourly pay rate for employee #";
cout << (index + 1) << ": ";
cin >> payRate[index];
}
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < numEmps; index++)
{
float grossPay = hours[index] * payRate[index];
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
111
Program Output with Example Input
Enter the hours worked by 5 employees and their hourly rates.
hours worked by employee #1: 10 [Enter]
Hourly pay rate for employee #1: 9.75 [Enter]
hours worked by employee #2: 15 [Enter]
Hourly pay rate for employee #2: 8.62 [Enter]
hours worked by employee #3: 20 [Enter]
Hourly pay rate for employee #3: 10.50 [Enter]
hours worked by employee #4: 40 [Enter]
Hourly pay rate for employee #4: 18.75 [Enter]
hours worked by employee #5: 40 [Enter]
Hourly pay rate for employee #5: 15.65 [Enter]
Here is the gross pay for each employee:
Employee #1: $97.50
Employee #2: $129.30
Employee #3: $210.00
112
7.7 Thou Shalt Not Assign
• You cannot use the assignment operator to
copy one array’s contents to another.
for (int count=0; count < 4; count++)
newVal[count] = oldVal[count];
113
Table 7-2
Expression
Value
OldValues[0]
10 (Contents of Elem ent 0 of OldValues)
OldValues[1]
100 (Contents of Elem ent 1 of OldValues)
OldValues[2]
200 (Contents of Elem ent 2 of OldValues)
OldValues[3]
300 (Contents of Elem ent 3 of OldValues)
NewValues
8012 (Mem ory Address of NewValues)
OldValues
8024 (Mem ory Address of OldValues)
114
7.8 Printing the Contents of an
Array
• To display the contents of an array, you must
use a loop to display the contents of each
element.
int array[5] = { 10, 20, 30, 40, 50 };
for (int count = 0; count < 5; count++)
cout << array[count] << endl;
115
7.9 Arrays As Function Arguments
• To pass an array as an argument to a function,
pass the name of the array.
116
Program 7-13
// This program demonstrates that an array element is passed
// to a function like any other variable.
#include <iostream.h>
void ShowValue(int);
// Function prototype
void main(void)
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
for (int Cycle = 0; Cycle < 8; Cycle++)
ShowValue(collection[Cycle]);
}
117
Program continues
//************************************
// Definition of function showValue.
*
// This function accepts an integer argument. *
// The value of the argument is displayed.
*
//************************************
void ShowValue(int Num)
{
cout << Num << " ";
}
118
Program Output
5 10 15 20 25 30 35 40
119
Program 7-14
// This program demonstrates an array being passed to a function.
#include <iostream.h>
void showValues(int []);
// Function prototype
void main(void)
{
int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};
showValues(collection);
// Passing address of array collection
}
//***********************************************
// Definition of function showValues.
*
// This function accepts an array of 8 integers *
// as its argument. The contents of the array
*
// is displayed.
*
//***********************************************
void showValues(int nums[])
{
for (int index = 0; index < 8; index++)
cout << nums[index] << " ";
}
120
Program Output
5 10 15 20 25 30 35 40
121
Program 7-15
// This program demonstrates an array being passed to a function.
#include <iostream.h>
void showValues(int []);
// Function prototype
void main(void)
{
int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int set2[8] = {2, 4, 6, 8, 10, 12, 14, 16};
showValues(set1);
cout << endl;
showValues(set2);
}
//***********************************************
// Definition of function showValues.
*
// This function accepts an array of 8 integers *
// as its argument. The contents of the array
*
// is displayed.
*
//***********************************************
void showValues(int nums[])
{
for (int index = 0; index < 8; index++)
cout << nums[index] << " ";
}
122
Program Output
5 10 15 20 25 30 35 40
2 4 6 8 10 12 14 16
123
Program 7-16
// This program uses a function that can display the contents
// of an integer array of any size.
#include <iostream.h>
void showValues(int [], int); // Function prototype
void main(void)
{
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};
showValues(set1, 8);
cout << endl;
showValues(set2, 4);
cout << endl;
showValues(set3, 12);
}
124
Program continues
//***********************************************
// Definition of function showValues.
*
// This function displays the contents of the
*
// array passed into nums. The value passed
*
// into elements is the number of elements in
*
// the nums array.
*
//***********************************************
void showValues(int nums[], int elements)
{
for (int index = 0; index < elements; index++)
cout << nums[index] << " ";
}
125
Program Output
5 10 15 20 25 30 35 40
2468
1 2 3 4 5 6 7 8 9 10 11 12
126
Program 7-17
// This program uses a function that doubles the contents of
// the elements within an array.
#include <iostream.h>
void doubleArray(int [], int);
const int arraySize = 12;
// Function prototype
void main(void)
{
int set[arraySize] = {1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12};
cout << "The arrays values are:\n";
for (int index = 0; index < arraySize; index++)
cout << set[index] << " ";
cout << endl;
doubleArray(set, arraySize);
cout << "After calling doubleArray, the values are:\n";
127
Program continues
for (int index = 0; index < arraySize; index++)
cout << set[index] << " ";
cout << endl;
}
//**************************************************
// Definition of function doubleArray.
*
// This function doubles the value of each element *
// in the array passed into nums.
*
// The value passed into size is the number of
*
// elements in the nums array.
*
//**************************************************
void doubleArray(int nums[], int size)
{
for (int index = 0; index < size; index++)
nums[index] *= 2;
}
128
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
129
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.
130
Program 7-18
// This program demonstrates a two-dimensional array.
#include <iostream.h>
void main(void)
{
float sales[3][4]; // 2D array, 3 rows and 4 columns.
float totalSales = 0;
// To hold the total sales.
int dir, qtr;
// Loop counters.
131
Program continues
cout << "This program will calculate the total sales of\n";
cout << "all the company's divisions.\n";
cout << "Enter the following sales information:\n\n";
// 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.
}
132
Program continues
// Nested loops to add all the elements.
for (div = 0; div < 3; div++)
for (qtr = 0; qtr < 4; qtr++)
totalSales += sales[div][qtr];
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "The total sales for the company are: $";
cout << totalSales << endl;
}
133
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]
134
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
135
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.
136
7.11 Arrays of Strings
• A two-dimensional array of characters can be
used as an array of C-strings.
137
Program 7-20
// This program displays the number of days in each month.
// It uses a two-dimensional character array to hold the
// names of the months and an int array to hold the number
// of days.
#include <iostream.h>
void main(void)
{
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 count = 0; count < 12; count++)
{
cout << months[count] << " has ";
cout << days[count] << " days.\n";
}
}
138
Program 7-20 (continued)
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.
139
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];
140
7.14 Introduction to the STL
vector
• The Standard Template Library (or STL) is a
collection of data types and algorithms that
you may use in your programs. These data
types and algorithms are programmerdefined. They are not part of the C++
language, but were created in addition to the
built-in data types.
141
7.14 Introduction to the STL
vector
• The data types that are defined in the STL are
commonly called containers, because they
store and organize data.
• There are two types of containers in the STL:
sequence containers and associative
containers.
• The vector data type is a sequence
container.
142
7.14 Introduction to the STL
vector
• A vector is like an array in the following
ways:
– A vector holds a sequence of values, or
elements.
– A vector stores its elements in contiguous
memory locations.
– You can use the array subscript operator [] to
read the individual elements in the vector
143
7.14 Introduction to the STL
vector
• However, a vector offers several advantages
over arrays. Here are just a few:
– You do not have to declare the number of
elements that the vector will have.
– If you add a value to a vector that is already full,
the vector will automatically increase its size to
accommodate the new value.
– vectors can report the number of elements they
contain.
144
Declaring a vector
• To use vectors in your program, you must first
#include the vector header file with the
following statement:
#include <vector>
Note: There is no .h at the end of the file
name.
145
Declaring a vector
• The next step is to include the following
statement after your #include statements:
using namespace std;
The STL uses namespaces to organize the
names of its data types and algorithms.
146
Declaring a vector
• Now you are ready to declare an actual
vector object. Here is an example:
vector<int> numbers;
The statement above declares numbers as a
vector of ints.
147
Declaring a vector
• You can declare a starting size, if you prefer.
Here is an example:
vector<int> numbers(10);
The statement above declares numbers as a
vector of 10 ints.
148
Other examples of vector
Declarations
Declaration Format
Description
vector<float> amounts;
Declares amounts as an empty
vector of floats.
vector<int> scores(15);
Declares scores as a vector of 15
ints.
vector<char> letters(25, 'A');
Declares letters as a vector of
25 characters. Each element is
initialized with 'A'.
vector<double>
values2(values1);
Declares values2 as a vector of
doubles. All the elements of
values1, which also a vector of
doubles, are copied to value2.
149
Storing and Retrieving Values in a
vector
• To store a value in an element that already
exists in a vector, you may use the array
subscript operator [].
150
Program 7-23
// This program stores, in two vectors, the hours worked by 5
// employees, and their hourly pay rates.
#include <iostream.h>
#include <vector>
// Needed to declare vectors
using namespace std;
void main(void)
{
vector<int> hours(5);
vector<float> payRate(5);
// Declare a vector of 5 integers
// Declare a vector of 5 floats
cout << "Enter the hours worked by 5 employees and their\n";
cout << "hourly rates.\n";
for (int index = 0; index < 5; index++)
{
cout << "Hours worked by employee #" << (index + 1);
cout << ": ";
cin >> hours[index];
cout << "Hourly pay rate for employee #";
cout << (index + 1) << ": ";
cin >> payRate[index];
}
151
Program 7-23 (continued)
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < 5; index++)
{
float grossPay = hours[index] * payRate[index];
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
152
Program 7-23 (continued)
Program Output with Example Input Shown in Bold
Enter the hours worked by 5 employees and their
hourly rates.
Hours worked by employee #1: 10 [Enter]
Hourly pay rate for employee #1: 9.75 [Enter]
Hours worked by employee #2: 15 [Enter]
Hourly pay rate for employee #2: 8.62 [Enter]
Hours worked by employee #3: 20 [Enter]
Hourly pay rate for employee #3: 10.50 [Enter]
Hours worked by employee #4: 40 [Enter]
Hourly pay rate for employee #4: 18.75 [Enter]
Hours worked by employee #5: 40 [Enter]
Hourly pay rate for employee #5: 15.65 [Enter]
Here is the gross pay for each employee:
Employee #1: $97.50
Employee #2: $129.30
Employee #3: $210.00
Employee #4: $750.00
Employee #5: $626.00
153
Using the push_back Member
Function
• You cannot use the [] operator to access a
vector element that does not exist.
• To store a value in a vector that does not
have a starting size, or is already full, use the
push_back member function. Here is an
example:
numbers.push_back(25);
154
Program 7-24
// This program stores, in two vectors, the hours worked by a specified
// number of employees, and their hourly pay rates.
#include <iostream.h>
#include <vector>
// Needed to declare vectors
using namespace std;
void main(void)
{
vector<int> hours;
vector<float> payRate;
int numEmployees;
// hours is an empty vector
// payRate is an empty vector
// The number of employees
cout << "How many employees do you have? ";
cin >> numEmployees;
cout << "Enter the hours worked by " << numEmployees;
cout << " employees and their hourly rates.\n";
155
Program 7-24 (continued)
for (int index = 0; index < numEmployees; index++)
{
int tempHours;
// To hold the number of hours entered
float tempRate; // To hold the payrate entered
cout << "Hours worked by employee #" << (index + 1);
cout << ": ";
cin >> tempHours;
hours.push_back(tempHours); // Add an element to hours
cout << "Hourly pay rate for employee #";
cout << (index + 1) << ": ";
cin >> tempRate;
payRate.push_back(tempRate); // Add an element to payRate
}
cout << "Here is the gross pay for each employee:\n";
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
for (index = 0; index < numEmployees; index++)
{
float grossPay = hours[index] * payRate[index];
cout << "Employee #" << (index + 1);
cout << ": $" << grossPay << endl;
}
}
156
Program 7-24 (continued)
Program Output with Example Input Shown in Bold
How many employees do you have? 3 [Enter]
Enter the hours worked by 3 employees and their hourly rates.
Hours worked by employee #1: 40 [Enter]
Hourly pay rate for employee #1: 12.63 [Enter]
Hours worked by employee #2: 25 [Enter]
Hourly pay rate for employee #2: 10.35 [Enter]
Hours worked by employee #3: 45 [Enter]
Hourly pay rate for employee #3: 22.65 [Enter]
Here is the gross pay for each employee:
Employee #1: $505.20
Employee #2: $258.75
Employee #3: $1019.25
157
Determining the Size of a
vector
• Unlike arrays, vectors can report the number of elements
they contain. This is accomplished with the size member
function. Here is an example of a statement that uses the
size member function:
numValues = set.size();
• In the statement above, assume that numValues is an
int, and set is a vector. After the statement executes,
numValues will contain the number of elements in the
vector set.
158
Determining the Size of a
vector
• Example:
void showValues(vector<int> vect)
{
for (int count = 0; count < vect.size(); count++)
cout << vect[count] << endl;
}
159
Program 7-25
// This program demonstrates the vector size
// member function.
#include <iostream.h>
#include <vector>
using namespace std;
// Function prototype
void showValues(vector<int>);
void main(void)
{
vector<int> values;
for (int count = 0; count < 7; count++)
values.push_back(count * 2);
showValues(values);
}
160
Program 7-25 (continued)
//**************************************************
// Definition of function showValues.
*
// This function accepts an int vector as its
*
// argument. The value of each of the vector's
*
// elements is displayed.
*
//**************************************************
void showValues(vector<int> vect)
{
for (int count = 0; count < vect.size(); count++)
cout << vect[count] << endl;
}
161
Program 7-25 (continued)
Program Output
0
2
4
6
8
10
12
162
Removing Elements from a
vector
• Use the pop_back member function to
remove the last element from a vector.
collection.pop_back();
The statement above removes the last
element from the collection vector.
163
Program 7-26
// This program demosntrates the vector size member function.
#include <iostream.h>
#include <vector>
using namespace std;
void main(void)
{
vector<int> values;
// Store values in the vector
values.push_back(1);
values.push_back(2);
values.push_back(3);
cout << "The size of values is " << values.size() << endl;
// Remove a value from the vector
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
164
Program 7-26 (continued)
// Now remove another value from the vector
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
// Remove the last value from the vector
cout << "Popping a value from the vector...\n";
values.pop_back();
cout << "The size of values is now " << values.size() << endl;
}
Program Output
The size of values is 3
Popping a value from the vector...
The size of values is now 2
Popping a value from the vector...
The size of values is now 1
Popping a value from the vector...
The size of values is now 0
165
Clearing a vector
• To completely clear the contents of a
vector, use the clear member function.
Here is an example:
numbers.clear();
After the statement above executes, the
numbers vector will be cleared of all its
elements.
166
Program 7-27
// This program demosntrates the vector size member function.
#include <iostream.h>
#include <vector>
using namespace std;
void main(void)
{
vector<int> values(100);
cout << "The values vector has “
<< values.size() << " elements.\n";
cout << "I will call the clear member function...\n";
values.clear();
cout << "Now, the values vector has “
<< values.size() << " elements.\n";
}
167
Program 7-27 (continued)
Program Output
The values vector has 100 elements.
I will call the clear member function...
Now, the values vector has 0 elements.
168
Detecting an Empty vector
• To determine if a vector is empty, use the
empty member function. The function
returns true if the vector is empty, and
false if the vector has elements stored in
it. Here is an example of its use:
if (set.empty())
cout << "No values in set.\n";
169
Program 7-28
// This program demosntrates the vector's empty member function.
#include <iostream.h>
#include <vector>
using namespace std;
// Function prototype
float avgVector(vector<int>);
void main(void)
{
vector<int> values;
int numValues;
float average;
cout << "How many values do you wish to average? ";
cin >> numValues;
170
Program 7-28 (continued)
for (int count = 0; count < numValues; count++)
{
int tempValue;
cout << "Enter a value: ";
cin >> tempValue;
values.push_back(tempValue);
}
average = avgVector(values);
cout << "Average: " << average << endl;
}
//*************************************************************
// Definition of function avgVector.
*
// This function accepts an int vector as its argument. If
*
// the vector contains values, the function returns the
*
// average of those values. Otherwise, an error message is
*
// displayed and the function returns 0.0.
*
//*************************************************************
171
Program 7-28 (continued)
float avgVector(vector<int> vect)
{
int total = 0; // accumulator
float avg;
// average
if (vect.empty())
// Determine if the vector is empty
{
cout << "No values to average.\n";
avg = 0.0;
}
else
{
for (int count = 0; count < vect.size(); count++)
total += vect[count];
avg = total / vect.size();
}
return avg;
}
172
Program 7-28 (continued)
Program Output with Example Input Shown in Bold
How many values do you wish to average?
Enter a value: 12
Enter a value: 18
Enter a value: 3
Enter a value: 7
Enter a value: 9
Average: 9
Program Output with Example Input Shown in Bold
How many values do you wish to average? 0
No values to average.
Average: 0
173
Summary of vector Member
Functions
Member Function
Description
at(element)
Returns the value of the element located at element in
the vector.
Example:
x = vect.at(5);
The statement above assigns the value of the 5th
element of vect to x.
capacity()
Returns the maximum number of elements that may be
stored in the vector without additional memory being
allocated. (This is not the same value as returned by
the size member function).
Example:
x = vect.capacity();
The statement above assigns the capacity of vect to x.
174
Summary of vector Member
Functions
clear()
Clears a vector of all its elements.
Example:
vect.clear();
The statement above removes all the elements from
vect.
empty()
Returns true if the vector is empty. Otherwise, it returns
false.
Example:
if (vect.empty())
cout << "The vector is empty.";
The statement above displays the message if vect is
empty.
pop_back()
Removes the last element from the vector.
Example:
vect.pop_back();
The statement above removes the last element of
vect, thus reducing its size by 1.
175
Summary of vector Member
Functions
push_back(value)
Stores a value in the last element of the vector. If the
vector is full or empty, a new element is created.
Example:
vect.push_back(7);
The statement above stores 7 in the last element of
vect.
reverse()
Reverses the order of the elements in the vector (the
last element becomes the first element, and the first
element becomes the last element.)
Example:
vect.reverse();
The statement above reverses the order of the element
in vect.
resize(elements,
value)
Resizes a vector by elements elements. Each of the
new elements is initialized with the value in value.
Example:
vect.resize(5, 1);
The statement above increases the size of vect by 5
elements. The 5 new elements are initialized to the
value 1.
176
Summary of vector Member
Functions
swap(vector2)
Swaps the contents of the vector with the contents of
vector2.
Example:
vect1.swap(vect2);
The statement above swaps the contents of vect1 and
vect2.
177