Array,structure and function (1) - Copy - Copy - Copy
Array,structure and function (1) - Copy - Copy - Copy
2
How To Declare Arrays
• To declare an array in C++, you should specify the following
things
– The data type of the values which will be stored in the array
– The name of the array (i.e. a C++ identifier that will be used to access
and update the array values)
– The dimensionality of the array:
• One dimensional (i.e. list of values ),
• Two-dimension array (a matrix or a table), etc.
– The size of each dimension
• Examples
– int x[10]; // An integer array named x with size 10
– float GPA[30]; // An array to store the GPA for 30 students
– int studentScores[30][5]; // A two-dimensional array to store the
scores of 5 exams for 30 students
3
One-dimensional Arrays
• Access list of data values in an easy way by giving
these values a common name, e.g.
int x[4]; // all values are named x
x[0] = 10; // the 1st value is 10 10 x[0]
x[1] = 5; // the 2nd value is 5
5 x[1]
x[2] = 20; // the 3rd value is 20
20 x[2]
x[3] = 30; // the 4th value is 30
30 x[3]
4
Array Indices and
Out-of-bound Run-time Error
• All C++ one-dimensional arrays with N entries
start at index 0 and ended at index N-1
const int N=5;
int v[N]; // this array contains 5 entries
• It is a common error to try to access the Nth
entry, e.g. v[5] or V[N], since the index of the
last array entry is N-1, not N
5
Initializing One-dimensional Arrays
• There are two common ways to initialize one-dimensional arrays
– Using for loop, e.g.
int x[10];
for( int index=0; index<10; index++)
x [index] = index+1 ;
– Specifying list of values while declaring the 1D array, e.g.
int x[10] = {1,2,3,4,5,6,7,8,9,10};
int y[ ] = {0,0,0}; // this array contains 3 entries with 0 values
double z[100] = {0}; // this array contains 100
// entries, all of which are initialized by 0
double w[20] = {5,3,1}; // this array contains 20 entries,
// the first three entries are initialized by 5, 3, and1 respectively
// while the remaining 17 entries are automatically initialized by 0
bool pass[10] = {true, true}; // this array contains 10 entries.
// The first two entries are initialized to true, while the remaining 8
// entries are automatically initialized to false
6
Storing Values in 1D Arrays
• Wrong way:
Int x[10];
cin >> x; // you cannot do that unless you
• Correct way:
int x[10];
// Reading one value at a time from the user:
for (int index=0; index<10; index++)
cin >> x[index];
7
Displaying Values Stored
in 1D Arrays
• Wrong way:
Int x[10];
cout << x; // you cannot do that unless you
• Correct way:
int x[10];
// Displaying one value per line to the user:
for (int index=0; index<10; index++)
cout << x[index] << endl;
8
Example: Read Values and Print them in
Reverse Order
#include <iostream.h>
void main()
{
int x[5], index;
cout << “Please enter five integer values: “;
for( index=0; index<5; index++)
cin >> x[index];
cout << “The values in reverse order are: “;
for (index=4; index>=0; index--)
cout << setw(3) << x[index];
cout << endl;
}
9
Array Manipulation
I. Searching for Something…
Example: Searching for the smallest value
in an array
const int x[10 ], int n=10;
int min = x[0];
for (int i=1; i<(n-1); i++)
if (min>x[i]) min = x[i];
return min;
}
11
Example: Searching for The Index of The
Smallest Value in An Array
int min_index ;
int x[ 10];
int size;
int start=0;
15
Exercise :
1. Compute The Mean Value of An Array
to find mean value of an array
2. Multiplying An Array with A Constant
Value
3. Search for the Largest Value in 1D
Array
4. Write a code to perform Array sorting
16
Multidimensional Arrays
C++ also allows an array to have more than one dimension.
The declaration must specify the number of rows and the number of columns,
and both must be constants.
17
Processing a 2-D Array
A one-dimensional array is usually processed via a for loop. Similarly, a two-
dimensional array may be processed with a nested for loop:
Each pass through the inner for loop will initialize all the elements of the current
row to 0.
The outer for loop drives the inner loop to process each of the array's rows.
18
Initializing in Declarations
int Array1[2][3] = { {1, 2, 3} , {4, 5, 6} };
int Array2[2][3] = { 1, 2, 3, 4, 5 };
int Array3[2][3] = { {1, 2} , {4 } };
19
Higher-Dimensional Arrays
An array can be declared with multiple dimensions.
2 Dimensional 3 Dimensional
double Coord[100][100][100];
20
Example
• Write a C++ code for two dimensional array Addition, subtraction,
multiplication and division .
• Hint
– Addition
for(int R=0;R<N;R++)
for(int C=0;C<M;C++)
C[R][C]=A[R][C]+B[R][C];
– Multiplication example
for(int R=0;R<N;R++)
for(int C=0;C<M;C++)
{
C[R][C]=0;
for(int T=0;T<L;T++)
C[R][C]+=A[R][T]*B[T][C];
}
21
Structure
22
Structures
• Definition of a structure:
struct <struct-type>{
Each identifier
<type> <identifier_list>;
<type> <identifier_list>;
defines a member
... of the structure.
} ;
• Example:
The “Date” structure
struct Date {
int day; has 3 members,
int month; day, month & year.
int year;
} ; 26
struct examples
• Example:
struct StudentInfo{
int Id; The “StudentInfo”
int age; structure has 4 members
char Gender; of different types.
double CGA;
};
• Example:
struct StudentGrade{ The “StudentGrade”
char Name[15];
char Course[9];
structure has 5
int Lab[5]; members of
int Homework[3]; different array types.
int Exam[2];
27
};
struct examples
• Example:
struct BankAccount{
char Name[15];
The “BankAcount”
int AcountNo[10]; structure has simple,
double balance; array and structure
Date Birthday; types as members.
};
• Example:
struct StudentRecord{ The “StudentRecord”
char Name[15];
int Id; structure has 4
char Dept[5]; members.
char Gender;
};
28
struct basics
• Example:
StudentRecord Student1, Student2;
Name Name
Student1 Id Gender Id Gender Student2
Dept Dept
• Example: 12345 M
strcpy(Student1.Name, COMP
"Chan Tai Man");
Student1.Id = 12345;
strcpy(Student1.Dept, "COMP");
Student1.gender = 'M';
Chan Tai Man
Student2 = Student1;
12345 M
COMP
Student2
32
33
Arrays of structures
• An ordinary array: One type of data
0 1 2 … 98 99
0 1 2 …
34
98 99
Arrays of structures
• We often use arrays of structures.
• Example:
StudentRecord Class[100];
strcpy(Class[98].Name, "Chan Tai Man");
Class[98].Id = 12345;
strcpy(Class[98].Dept, "COMP"); Chan Tai Man
Class[98].gender = 'M'; 12345 M
Class[0] = Class[98]; COMP
...
0 1 2 …35 98 99
Exercise
• Write structural array code to store and
display 20 students record.
– Your code should store name, id-no, department,
year, gender and Gpa
– Should return or display individuals record when
ID-no or department is used as search key.
36
Function
37
Introduction
• A C++ function or a subprogram is simply a chunk of C++ code
that has
– A descriptive function name, e.g.
• computeTaxes to compute the taxes for an employee
• isPrime to check whether or not a number is a prime number
– A returning value
• The computeTaxes function may return with a double number
representing the amount of taxes
• The isPrime function may return with a Boolean value (true or false)
38
How to define a C++ Function?
• Generally speaking, we define a C++ function
in two steps (preferably but not mandatory)
– Step #1 – declare the function signature in either a
header file (.h file) or before the main function of
the program
– Step #2 – Implement the function in either an
implementation file (.cpp) or after the main
function
39
What is The Syntactic Structure of a
C++ Function?
• A C++ function consists of two parts
– The function header, and
– The function body
• The function header has the following syntax
<return value> <name> (<parameter list>)
• The function body is simply a C++ code
enclosed between { }
40
Example of User-defined
C++ Function
41
Example
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return r;
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
} 42
Argument passing
43
Passing by value
• This means that, when calling a function, what
is passed to the function are the values of
these arguments on the moment of the call,
which are copied into the variables
represented by the function parameters.
int x=5, y=3, z;
z = addition ( x, y );
• modification of these variables within the
function has no effect on the values of the
variables x and y outside it,
44
Passing by Reference
• References are indicated with an ampersand (&) following the
parameter type
• When a variable is passed by reference, what is passed is no
longer a copy, but the variable itself,
// passing parameters by reference
#include <iostream>
using namespace std;
void duplicate (int& a, int& b, int& c)
{ a*=2; b*=2; c*=2; }
int main ()
{ int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
45
}
Inline Functions
• Sometimes, we use the keyword inline to define user-
defined functions
– Inline functions are very small functions, generally, one or two
lines of code
– Inline functions are very fast functions compared to the
functions declared without the inline keyword
– more efficient to simply insert the code of the function where it
is called, instead of performing the process of formally calling a
function.
• Example
inline double degrees( double radian)
{
return radian * 180.0 / 3.1415;
}
46
Exercise
• Write c++ code using functions to
calculate the area of circle, rectangle
and triangle based on choice and
input from user.
47
Thanks!
48