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

Array,structure and function (1) - Copy - Copy - Copy

c++ note

Uploaded by

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

Array,structure and function (1) - Copy - Copy - Copy

c++ note

Uploaded by

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

Chapter 3

Arrays, Functions and structure


What Is An Array?
• An array is a collection of values that have the same
data type, e.g.
– A collection of int data values or
– A collection of bool data values
• We refer to all stored values in an array by its name
• If we would like to access a particular value stored in
an array, we specify its index (i.e. its position relative
to the first array value)
– The first array index is always 0
– The second value is stored in index 1
– Etc.

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;

int index = start;


int min = x[index];
for (int i=index+1; i<size; i++)
if (min>x[i])
{
min = x[i];
index = i;
}
cout<< index; 12
Example: Searching for A Key/number in
Unsorted Array Using Sequential Search
int seqSearch (int x[ ], int size, int key)
{
for (int i=0; i<size; i++)
if (key == x[i])
Cout<<i;
else
Cout<<“number not available”;
}
13
Array Manipulation
II. Compute Something…
Example: Compute The Sum of Values
Stored in An Array
int sum;
const int x[10 ];
Cout<<“enter array elements”;
for(int i=o;i<10;i++)
{
Cin>>x[i];
}
int n;
int sum = 0;
for (int i=0; i<10; i++)
{ sum+=x[i];}
cout<< “sum=“<<sum;

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.

For example, a two-dimensional array consists of a certain number of rows and


columns:

const int NUMROWS = 3;


const int NUMCOLS = 7;
int Array[NUMROWS][NUMCOLS]; 0 1 2 3 4 5 6
0 4 18 9 3 -4 6 0
1 12 45 74 15 0 98 0
2 84 87 75 67 81 85 79

Array[2][5] 3rd value in 6th column


Array[0][4] 1st value in 5th column

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:

for (int Row = 0; Row < NUMROWS; Row++) {


for (int Col = 0; Col < NUMCOLS; Col++) {
Array[Row][Col] = 0;
}
}

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 } };

If we printed these arrays by rows, we would find the following initializations


had taken place:

Rows of Array1: for (int row = 0; row < 2; row++) {


1 2 3
for (int col = 0; col < 3; col++) {
4 5 6
cout << setw(3)
Rows of Array2: << Array1[row][col];
1 2 3
}
4 5 0
cout << endl;
Rows of Array3: }
1 2 0
4 0 0

19
Higher-Dimensional Arrays
An array can be declared with multiple dimensions.

2 Dimensional 3 Dimensional

double Coord[100][100][100];

Multiple dimensions get difficult to visualize graphically.

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

• A Structure is a collection of related data


items, possibly of different types.
• A structure type in C++ is called struct.
• A struct is heterogeneous in that it can be
composed of data of different types.
• In contrast, array is homogeneous since it can
contain only data of the same type.
23
Structures

• Structures hold data that belong together.


• Examples:
– Student record: student id, name, major, gender,
start year, …
– Bank account: account number, name, currency,
balance, …
– Address book: name, address, telephone number,

• In database applications, structures are called
records.
24
Structures
• Individual components of a struct type are
called members (or fields).
• Members can be of different types (simple,
array or struct).
• A struct is named as a whole while
individual members are named using field
identifiers.
• Complex data structures can be formed by
defining arrays of structs.
25
struct basics

• 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

• Declaration of a variable of struct type:


<struct-type> <identifier_list>;

• Example:
StudentRecord Student1, Student2;
Name Name
Student1 Id Gender Id Gender Student2
Dept Dept

Student1 and Student2 are variables of


StudentRecord type. 29
Ex. 1: struct basics
• The members of a struct type variable are
accessed with the dot (.) operator:
<struct-variable>.<member_name>;
Student1
• Example:
strcpy(Student1.Name, "Chan Tai Man"); Name
Student1.Id = 12345; Id Gender
strcpy(Student1.Dept, "COMP");
Dept
Student1.gender = 'M';
cout << "The student is ";
switch (Student1.gender){
case 'F': cout << "Ms. "; break; Chan Tai Man
case 'M': cout << "Mr. "; break; 12345 M
}
COMP
cout << Student1.Name << endl;
• strcpy() is used to copy one string to another.
30
31
Ex. 2: struct-to-struct assignment
• The values contained in one struct type
variable can be assigned to another Student1
variable of the same struct type.
Chan Tai Man

• 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

• An array of structs: Multiple types of data in


each array element.

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

double computeTax(double income)


{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}

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

• Arguments can be passed


–By value
–By Reference

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

You might also like