Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
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
int anArray[][5] =
{ { 1, 2, 3, 4, 5,
},{ 6, 7, 8, 9, 10, },{ 11, 12, 13, 14, 15 } };
• int anArray[][5] =
• 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
};
• int anArray[][] =
• { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
• int anArray[3][5] = { 0 }; all element=0
// Declare a 10x10 array
const int nNumRows = 10;
const int nNumCols = 10;
int nProduct[nNumRows ][nNumCols ] = { 0 };
// Calculate a multiplication table
for (int nRow = 0; nRow < nNumRows; nRow++)
for (int nCol = 0; nCol < nNumCols; nCol++)
nProduct[nRow][nCol] = nRow * nCol;
// Print the table
for (int nRow = 1; nRow < nNumRows; nRow++)
{
for (int nCol = 1; nCol < nNumCols; nCol++)
cout << nProduct[nRow][nCol] << "\t";
cout << endl;
}
• This program calculates and prints a
multiplication table for all values between 1
and 9 (inclusive). Note that when printing the
table, the for loops start from 1 instead of 0.
This is to omit printing the 0 column and 0
row, which would just be a bunch of 0s! Here
is the output:
Array basics
• Let's start by looking at a single variable used to store a
person's age.
#include <iostream>
int main()
{
short age;
age=23;
std::cout << age << std::endl;
return 0;
}
#include <iostream>
int main()
{
short age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
return 0;
}
Printing arrays
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: }
#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: std::cout << age[0] << std::endl;
11: std::cout << age[1] << std::endl;
12: std::cout << age[2] << std::endl;
13: std::cout << age[3] << std::endl;
14: return 0;
15: }
Copying arrays
1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7: age[0]=23;
8: age[1]=34;
9: age[2]=65;
10: age[3]=74;
11:
12: same_age=age;
13:
14: std::cout << same_age[0] << std::endl;
15: std::cout << same_age[1] << std::endl;
16: std::cout << same_age[2] << std::endl;
17: std::cout << same_age[3] << std::endl;
18: return 0;
19: }
1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7:
8: age[0]=23;
9: age[1]=34;
10: age[2]=65;
11: age[3]=74;
12:
13: same_age[0]=age[0];
14: same_age[1]=age[1];
15: same_age[2]=age[2];
16: same_age[3]=age[3];
17:
18: std::cout << same_age[0] << std::endl;
19: std::cout << same_age[1] << std::endl;
20: std::cout << same_age[2] << std::endl;
21: std::cout << same_age[3] << std::endl;
23: return 0;
23: }
1: #include <iostream>
2:
3: int main()
4: {
5: short age[4];
6: short same_age[4];
7: int i, j;
8: age[0]=23;
9: age[1]=34;
10: age[2]=65;
11: age[3]=74;
12:
13: for(i=0; i<4; i++)
14: same_age[i]=age[i];
15:
16: for(j=0; j<4; j++)
17: std::cout << same_age[j] << std::endl;
18: return 0;
19: }
1: #include <iostream>
2: int main()
3: {
4: float fl=3.14;
5: std::cout << fl << std::endl;
6: return 0;
7: }
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.
Example
• Write function to take coefficients of quadratic
equation a, b and c as input parameter and
return two roots of quadratic equation as
output parameters (using pointers). If the
discriminant is negative, it should print “no
real roots” and terminates the program
execution. Write main program to call this
function.
Answer:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
void quadratic(double a,double b, double c, dooble *root1, double *root2) // user-defined function
{
double d;
d=b*b-4*a*c;
if(d < 0)
{
printf("No real roots\n");
exit(0);
}
else
{
*root1=(-b+sqrt(d))/(2*a);
*root2=(-b-sqrt(d))/(2*a);
}
}
void main()
{
double a,b,c,r1,r2;
printf("Please input a, b, c :");
scanf("%lf %lf %lf",&a,&b,&c);
quadratic(a,b,c,&r1,&r2); // function call
printf("\nThe first root is : %f\n",r1);
printf("The second root is : %f\n", r2);
}
Matrix
•
•
•
•
•
•
•
•
•
#include <stdio.h>
int main()
{
int Grade[5];
Grade[0]=...
Grade[1]=...
Grade[2]=...
Grade[3]=...
Grade[4]=...
• }
#include <stdio.h>
int main()
{
int Grade[5]={20,30,52,40,77};
Grade[0]=20
Grade[1]=30
Grade[2]=...
Grade[3]=...
Grade[4]=...
}
Int Grade[5];
Int index;
For (index=0;index<5;++index){
printf( “Enter the Grade of Student No. %d: " );
scanf( "%d", &tGrade{index]); } }
Matrix
#include <stdio.h>
int main()
{
/* int Grade[5]={20,30,52,40,77};
Grade[0]=20
Grade[1]=30
Grade[2]=...
Grade[3]=...
Grade[4]=...*/
}
Int Grade[5];
Int index;
For (index=0;index<5;++index){
printf( “Enter the Grade of Student No. %d: " );
scanf( "%d", &tGrade{index]); } }
#include <stdio.h>
int main()
{
int Grade[5];
int index;
float Total=0.0;
for (index=0; index<5; ++index)
{
printf( “Enter the Grade No. %d: " ,index);
scanf( "%d", &Grade[index] );
Total=Total + Grade[index];
}
printf( “Student Grade \n");
printf( “= = = = = = \n");
for (index=0; index<5; ++ index)
{
printf( "%d \n", Grade[index] ); }
printf( " Avarege of Student Grades is %5.2f \n", Total/5.0 );
}
#include <stdio.h>
void main()
{
int Grade[5];
int index;
int Fail =0 ,Success =0;
for (index=0; index<5; ++index)
{
printf( “Enter the Grade No. %d: " ,index);
scanf( "%d", &Grade[index] );
}
printf( “Student Grade \n");
printf( “= = = = = = \n");
for (index=0; index<5; ++ index) {
if (Grade[index]>50)
{
printf( "%d \t", Success \n ,Grade[index] );
Success =Success +1;
}
else{
printf( "%d \t", Fail \n ,Grade[index] );
Fail=Fail+1;
}
printf( " No of Success is %d \n", Success );
printf( " No of Failis %d \n", Fail ); }
}
A matrix is just a rectangular array ("grid") of
numbers.
Matrix defenation
• To specify the size of a matrix, we need to talk
about rows and columns:
Matrix, Dimension,
• Entries An mn matrix A is a rectangular array of real
numbers with m rows and n columns. We refer to m
and n as the dimensions of the matrix A. The
numbers that appear in the matrix are called its
entries. We customarily use upper case letters A, B,
C, ... for the names of matrices.
• Example (2 * 3) matrix
Matrix Addition and Subtraction
• Two matrices can be added (or subtracted) if, and only if, they have the
same dimensions. (That is, both matrices have matching numbers of
rows and columns. For instance, you can't add, say, a 34 matrix to a 44
matrix, but you can add two 34 matrices.)
• To add (or subtract) two matrices of the same dimensions, just add (or
subtract) the corresponding entries. In other words, if A and B are mn
matrices, then A+B and A-B are the mn matrices whose entries are
given by
• (A + B)ij = Aij + Bij ijth entry of the sum = sum of the ijth entries (A - B)ij
= Aij - Bij ijth entry of the difference = difference of the ijth entries
• The product AB has as many rows as A and as many columns
as B
Matrix Inversion
• In general, the Inverse of an invertible n x n
matrix A = (Aij) is the matrix with elements
where Mij is the determinant of the matrix formed by deleting the ith row and jth column of A. (Note that the
formula refers to Mji and not Mij.) The above rule is not a practical method for the evaluation of inverses. There
are much faster methods based on row reduction techniques.
Matrix multiplier code
#include <stdio.h>
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);
print_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");
}}
Array in C++
#include <iostream>
using namespace std;
int main ()
{
int array[14];
for (int i=0; i<=13; i++)
{
array[i]=i+2;
cout<<array[i]<<" ";
//system("pause");
//return 0;
}
}
Array in c
Temperature changes
#include <iostream>
using namespace std;
int main()
{
int a;
a = 0;
while (a <= 100)
{
Cout << degrees = degrees C\n",
a, (a -32) * 5 / 9);
a = a + 10;
}
return 0;
}
•
•
•
•
billy[0] = a;
billy[a] = 75;
b = billy [a+2];
billy[billy[a]] = billy[2] + 5;
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;
}
12206
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.
Multidimensional arrays
• int jimmy [3][5];
• int jimmy [3][5];
• is equivalent to int jimmy [15]; // (3 * 5 = 15)
• #define HEIGHT 3
to:
#define HEIGHT 4
Arrays as parameters
#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;
}
#include <stdio.h>
#include <math.h>
void unit_norm(double *vec, int cols);
void matrix_mult(double a[3][3], double *b, double *c, int rows);
main()
{
int row, i, j;
double k[3][3] = {{1.2, -3.0, 1.1},
{-4.1, 6.2, -2.2},
{3.4, -2.5, -3.3}};
double y[3], x[3] = { 1./sqrt(2.), 0., -1./sqrt(2.) };
double w[3], z[3] = { 1./sqrt(3.), -1/sqrt(3.), 1./sqrt(3.) };
printf("\nInitial vector:\n\n");
printf("x[0] = [");
for(row=0; row<3; row++)
printf(" %.6f ", x[row]);
printf("]\n\n");
for(i=0; i<=4; i++)
{
matrix_mult(k,x,y,3);
printf("New Vector:\ny[%d] = [", i+1);
for(j=0; j<=2; j++)
printf(" %.6f ", y[j]);
printf("]\n");
unit_norm(y,3);
printf("Normalized new vector:\nx[%d] = [", i+1);
for(j=0; j<=2; j++)
printf(" %.6f ", y[j]);
printf("]\n");
for(j=0; j<=2; j++)
x[j] = y[j];
printf("\n");
}
return(0); }
void matrix_mult(double a[3][3], double *b, double *c, int rows)
{
int k, s;
double dot_p;
for(s=0; s<rows; s++)
{
for(k=0, dot_p=0.; k<3; k++)
dot_p += a[s][k]*b[k];
c[s] = dot_p;
}
return; }
void unit_norm(double *vec, int cols)
{
double norm;
double sum=0.;
int n;
for(n=0; n<cols; n++)
sum += vec[n] * vec[n];
sum = sqrt(sum);
for(n=0; n<cols; n++)
vec[n] = vec[n]/sum;
return;
}