C + + Learning Notes 2

1 function

A function is a set of statements that perform a task. Every C + + program has at least one function, the main function main(). Of which:

  • Function declarations tell the compiler the name, return type, and parameters of a function.
  • The function definition provides the actual body of the function.

1.1 defining functions

Functions can also be called methods or programs. The general form of function definition is:

return_type function_name(parameter list){
	body of the function
}

A function consists of a function header and a function body. All components of a function are listed below:

  • Return type: a function can return a value. return_type is the data type of the value returned by the function. Some functions perform the required operation without returning a value. In this case, return_type is the keyword void.
  • Function name: This is the actual name of the function.
  • Parameter: when the function is called, a value needs to be passed to the parameter, which is called the actual parameter. The parameter list includes the type, order and quantity of function parameters. Parameters are optional, that is, the function can contain no parameters.
  • Function body: the function body contains a set of statements that define the execution task of the function.

The following is an example code of a max() function. The function has two parameters num1 and num2, which will return the larger of the two numbers:

int max{ int num1,int num2 }{
	int result;
	if (num1 > num2)
		result = num1;
	else
		result = num2;
	return result;
}

1.2 function declaration

The function declaration tells the compiler the name of the function and how to call it. The actual body of a function can be defined separately. The function declaration includes the following parts:

return_type function_name(parameter list);

For the function max() defined above, the following is the function declaration:

int max{ int num1,int num2 };

In the function declaration, the name of the parameter is not important. Only the type of the parameter is required. Therefore, the following is also a valid declaration:

int max{ int,int};

When a function is defined in a source file and a function is called in another file, function declarations are required, and functions should be declared at the top of the calling function's file.

1.3 calling functions

When a program calls a function, program control is transferred to the called function. The called function executes the defined task. When the return statement of the function is executed or the end bracket of the function is reached, the program control will be returned to the main program.

The example code is as follows:

#include<iostream>
using namespace std;

int max(int, int); //Function declaration

int main() {
	int a = 100, b = 200, return_value;
	return_value = max(a, b);
	cout << "The maximum value is" << return_value << endl;
	return 0;
}

int max(int num1, int num2) {
	int result;
	if (num1 > num2)
		result = num1;
	else
		result = num2;
	return result;
}

The output is as follows:

200 max

If a function wants to use parameters, it must declare variables that accept parameter values. These variables are called formal parameters of the function - formal parameters, like other local variables in the function, are created when entering the function and destroyed when exiting the function.

1.4 function parameters

When calling a function, there are three ways to pass parameters to the function:

1. Call by value. The value passing method that passes the parameter to the function calls the method, and copies the actual value of the parameter to the formal parameter of the function. In this case, modifying the formal parameters in the function will not affect the actual parameters. By default, C + + uses value passing call methods to pass parameters. The example code is as follows:

#include<iostream>
using namespace std;

void swap(int x, int y);

int main() {
	int a = 100, b = 200;
	cout << "Before exchange a Is:" << a << endl;
	cout << "Before exchange b Is:" << b << endl;

	swap(a, b);

	cout << "Exchange exchange a Is:" << a << endl;
	cout << "Exchange exchange b Is:" << b << endl;

	return 0;
}

void swap(int x, int y) {
	int temp;
	temp = x;
	x = y;
	y = temp;
	return;
}

The output is as follows:

Before exchange a Is: 100
 Before exchange b Is: 200
 Exchange exchange a Is: 100
 Exchange exchange b Is: 200

The above example shows that although the values of a and b are changed in the function, in fact, the values of a and b are not changed.

2. Pointer call. Pass the pointer of the parameter to the function, call the method, and copy the address of the parameter to the formal parameter. Within the function, this address is used to access the actual parameters to be used in the call. This means that modifying the formal parameters will affect the actual parameters. Accordingly, the function parameter needs to be declared as a pointer type in the function. The example code is as follows. This function is used to exchange the values of two integer variables pointed to by parameters:

#include<iostream>
using namespace std;

void swap(int *x, int *y);

int main() {
	int a = 100, b = 200;
	cout << "Before exchange a Is:" << a << endl;
	cout << "Before exchange b Is:" << b << endl;

	swap(&a, &b);

	cout << "Exchange exchange a Is:" << a << endl;
	cout << "Exchange exchange b Is:" << b << endl;

	return 0;
}

void swap(int *x, int *y) {
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
	return;
}

The output is as follows:

Before exchange a Is: 100
 Before exchange b Is: 200
 Exchange exchange a Is: 200
 Exchange exchange b Is: 100

3. Reference call. The reference that passes parameters to the function calls the method, and copies the address of the reference to the formal parameter. Within the function, the reference is used to access the actual parameters to be used in the call. This means that modifying the formal parameters will affect the actual parameters. Accordingly, you need to declare the function parameter as a reference type in the function. The example code is as follows:

#include<iostream>
using namespace std;

void swap(int &x, int &y);

int main() {
	int a = 100, b = 200;
	cout << "Before exchange a Is:" << a << endl;
	cout << "Before exchange b Is:" << b << endl;

	swap(a, b);

	cout << "Exchange exchange a Is:" << a << endl;
	cout << "Exchange exchange b Is:" << b << endl;

	return 0;
}

void swap(int &x, int &y) {
	int temp;
	temp = x;
	x = y;
	y = temp;
	return;
}

The output is as follows:

Before exchange a Is: 100
 Before exchange b Is: 200
 Exchange exchange a Is: 200
 Exchange exchange b Is: 100

By default, C + + uses value passing calls to pass parameters. In general, this means that the code in the function cannot change the parameters used to call the function.

1.5 default values of parameters

After defining a function, you can specify a default value for each subsequent parameter in the parameter list. When calling a function, if the value of the parameter is not passed, the default value will be used. If a value is specified, the default value will be ignored and the passed value will be used. The example code is as follows:

#include<iostream>
using namespace std;

int sum(int a, int b = 20) {
	int result;
	result = a + b;
	return(result);
}

int main() {
	int a = 100, b = 200, reuslt;
	
	int result;

	result = sum(a, b);
	cout << "And are:" << result << endl;

	result = sum(a);
	cout << "And are:" << result << endl;

	return 0;
}

The output is as follows:

Sum: 300
 Sum: 120

2 numbers

C + + numeric types include int, short, long, float, double, and so on.

2.1 defining numbers

The following is a comprehensive example of defining various types of numbers in C + +:

#include<iostream>
using namespace std;

int main() {
	short s;
	int i;
	long l;
	float f;
	double d;

	s = 10;
	i = 1000;
	l = 100000;
	f = 230.48;
	d = 2342.234;

	cout << "short s: " << s << endl;
	cout << "int i: " << i << endl;
	cout << "long l: " << l << endl;
	cout << "float f: " << f << endl;
	cout << "double d: " << d << endl;

	return 0;
}

The output is as follows:

short s: 10
int i: 1000
long l: 100000
float f: 230.48
double d: 2342.23

2.2 mathematical operation

C + + has built-in rich mathematical functions, which can calculate various numbers. Some useful built-in mathematical functions in C + + are listed below (the header file < cmath > needs to be referenced in the code).

1. double cos(double). This function returns the cosine of the arc angle (double type).

2. double sin(double). This function returns the sine of an arc angle (double type).

3. double tan(double). This function returns the tangent of the arc angle (double type).

4. double log(double). This function returns the natural logarithm of the parameter.

5. double pow(double, double). Assuming that the first parameter is x and the second parameter is y, the function returns the Y power of X.

6. double hypot(double, double). This function returns the square root of the sum of the squares of two parameters, that is, if the parameter is the two right angles of a right triangle, the function will return the length of the hypotenuse.

7. double sqrt(double). This function returns the square root of the argument.

8. int abs(int). This function returns the absolute value of an integer.

9. double fabs(double). This function returns the absolute value of any floating-point number.

10. double floor(double). This function returns a maximum integer less than or equal to the passed in parameter, that is, rounding down.

The example code is as follows:

#include<iostream>
#include<cmath>
using namespace std;

int main() {
	short s;
	int i;
	long l;
	float f;
	double d;

	s = 10;
	i = -1000;
	l = 100000;
	f = 230.47;
	d = 200.374;

	cout << "sin(d): " << sin(d) << endl;
	cout << "abs(i): " << abs(i) << endl;
	cout << "floor(d): " << floor(d) << endl;
	cout << "sqrt(f): " << sqrt(f) << endl;
	cout << "pow(d,2): " << pow(d, 2) << endl;

	return 0;
}

The output is as follows:

sin(d): -0.634939
abs(i): 1000
floor(d): 200
sqrt(f): 15.1812
pow(d,2): 40149.7

2.3 random number

There are two related functions for random number generator. One is rand(), which only returns a pseudo-random number. The other is srand() function, which must be called before generating a random number.

The following is a simple example of generating random numbers. In the instance, the time() function is used to obtain the seconds of the system time, and the random number is generated by calling the rand() function:

#include<iostream>
#include<ctime>
#include<cstdlib>

using namespace std;

int main() {
	int i, j;

	srand((unsigned)time(NULL)); //Set seed

	//Generate 10 random numbers
	for (i = 0; i < 10; i++) {
		j = rand(); //Generate random number
		cout << "Random number:" << j << endl;
	}

	return 0;
}

The output is as follows:

Random number: 6480
 Random number: 15454
 Random number: 4897
 Random number: 12482
 Random number: 3346
 Random number: 18364
 Random number: 7009
 Random number: 32314
 Random number: 16963
 Random number: 24216

3 array

An array is an ordered collection of elements of the same type used to store a fixed size. Before using, you need to declare an array variable, such as numbers, and then use numbers[0], [1],..., and numbers[99] to represent individual variables. Specific elements in the array can be accessed by index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address corresponds to the last element.

3.1 declaration array

To declare an array, you need to specify the type and number of elements, as shown below:

type arrayName[arraySize];

The above is the form of one-dimensional array, where arraySize must be an integer constant greater than zero, and type can be any valid C + + data type. The example code is as follows:

double balance[10];

Now balance is an available array that can hold 10 numbers of type double.

3.2 initialization array

You can initialize arrays one by one or use an initialization statement, as shown below:

double balance[5] = { 1000.0,2.0,3.4,7.0,50.0 };

The number of values between braces {} cannot be greater than the number of elements specified in square brackets [] when the array is declared. If the size of the array is omitted, the size of the array is the number of elements at the time of initialization. Therefore:

double balance[] = { 1000.0,2.0,3.4,7.0,50.0 };

An array will be created that is identical to the array created in the previous instance. The following is an example of assigning a value to an element in an array:

balance[4]=50.0

The above statement sets the value of the fifth element in the array to 50.0. All arrays take 0 as the index of their first element, also known as the base index. The last index of the array is the total size of the array minus 1. The following is a graphical representation of the array discussed above:

3.3 accessing array elements

Array elements can be accessed by adding an index to the array name. The index of the element is placed in square brackets, following the array name. For example:

double salary = balance[9];

The above statement will assign the value of the 10th element in the array to the salary variable.

The complete example C + + code is as follows:

#include<iostream>
using namespace std;

int main() {
	int i,n[10];

	for (i = 0; i < 10; i++) {
		n[i] = i + 10;
	}
	
	for (i = 0; i < 10; i++) {
		cout << "Indexes" << i << "The corresponding value is" << n[i] << endl;
	}
	return 0;
}

The output is as follows:

Index 0 corresponds to a value of 10
 The value corresponding to index 1 is 11
 The value corresponding to index 2 is 12
 The value corresponding to index 3 is 13
 The value corresponding to index 4 is 14
 Index 5 corresponds to a value of 15
 The value corresponding to index 6 is 16
 The value corresponding to index 7 is 17
 The value corresponding to index 8 is 18
 The value corresponding to index 9 is 19

3.4 array explanation

3.4.1 multidimensional array

The general form of multidimensional array declaration is as follows:

type name[size1][size2]...[sizeN];

The example code is as follows:

int threedim[3][4][5];

The simplest form of multidimensional array is two-dimensional array. Declare a two-dimensional array as follows:

type arrayName[x][y];

A two-dimensional array can be considered a table with x rows and y columns. The following is a two-dimensional array with 3 rows and 4 columns:

Therefore, each element in the array is identified by the element name of the form a [i, J], where a is the array name and i and j are the subscripts that uniquely identify each element in a.

Multidimensional arrays can be initialized by specifying values for each row in parentheses. Here is an array with 3 rows and 4 columns.

int a[3][4] = {
	{0,1,2,3}, //Row with index number 0
	{4,5,6,7}, //Line with index number 1
	{8,9,10,11} //Line with index number 2
};

Internally nested parentheses are optional. The following initialization is the same as the above:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

The elements in a two-dimensional array are accessed by using subscripts, that is, the row index and column index of the array. For example:

int value=a[2][3];

The above statement will get the 4th element in line 3 of the array.

The complete example C + + code is as follows:

#include<iostream>
using namespace std;

int main() {
	int a[5][2] = { {0,0},{1,2},{2,4},{3,6},{4,8} };

	//Outputs the value of each element in the array
	for (int i = 0; i < 5; i++)
		for (int j = 0; j < 2; j++) {
			cout << "a[" << i << "][" << j << "];" << a[i][j] << endl;
		}
	return 0;
}

The output is as follows:

a[0][0];0
a[0][1];0
a[1][0];1
a[1][1];2
a[2][0];2
a[2][1];4
a[3][0];3
a[3][1];6
a[4][0];4
a[4][1];8

3.4.2 pointer to array

Pointer to array

3.4.3 passing arrays to functions

You can pass a pointer to an array by specifying an array name without an index. When an array is passed to a function, the array type is automatically converted to the pointer type, so the actual address is passed.

If you want to pass a one-dimensional array as a parameter in a function, you must declare the function form parameter in the following three ways. The results of these three declaration methods are the same, because each method will tell the compiler that it will receive an integer pointer.

1. The formal parameter is a pointer:

void myFunction(int* param) {

}

2. The formal parameter is an array of defined sizes:

void myFunction(int param[10]) {

}

3. The formal parameter is an array of undefined size:

void myFunction(int param[]) {

}

The sample C + + code is as follows:

#include<iostream>
using namespace std;

double getAverage(int arr[], int size) {
	int i, sum = 0;
	double avg;

	for (i = 0; i < size; ++i) {
		sum += arr[i];
	}

	avg = double(sum) / size;
	return avg;
}

int main() {
	int balance[5] = { 1000,2,3,17,50 };
	double avg;

	avg = getAverage(balance, 5); //Pass a pointer to an array as an argument

	cout << "The average value is:" << avg << endl;
	return 0;
}

The output is as follows:

The average value is 214.4

3.4.4 return array from function

C + + does not allow to return a complete array as a function parameter, but you can return a pointer to the array by specifying the array name without index. To return a one-dimensional array from a function, you must first declare a function that returns a pointer, as follows:

int* myFunction(){

}

C + + does not support returning the address of a local variable outside a function unless the local variable is defined as a static variable. The example code is as follows. The function generates 10 random numbers and uses an array to return them:

#include<iostream>
#include<cstdlib>
#include<ctime>

using namespace std;

int* getRandom() { //The function generates and returns a random number
	static int r[10];

	srand((unsigned)time(NULL)); //Set seed

	for (int i = 0; i < 10; i++) {
		r[i] = rand();
		cout << r[i] << endl;
	}
	return r;
}

int main() {
	int* p;

	p = getRandom();
	for (int i = 0; i < 10; i++) {
		cout << "*(p+" << i << ")L" << *(p + i) << endl;
	}
	return 0;
}

The output is as follows:

3304
8270
24235
19857
2011
30013
1221
2513
28595
28458
*(p+0)L3304
*(p+1)L8270
*(p+2)L24235
*(p+3)L19857
*(p+4)L2011
*(p+5)L30013
*(p+6)L1221
*(p+7)L2513
*(p+8)L28595
*(p+9)L28458

END

Tags: C++ array function

Posted on Mon, 01 Nov 2021 11:46:17 -0400 by hussain