CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi
Arrays Arrays are data structures which hold multiple variables of the same data type. Consecutive group of memory locations having same name and type (int, char, float, double etc.). To refer to an element, specify array name and position number (index) e.g. myList[5]
Declaration Syntax DataType ArrayName[size]; int a[20]; float grades[50]; Means a is an integers array with size 20. Each element in the array is accessed with a subscript i.e. a[0], a[1] ….. a[19]. Each memory element can hold an integer only. First element at position 0 and the maximum position at size ‐1 Memory requirements depend on the size of array. Array declaration is static i.e. the size must be specified at the time of declaration.
Initializing Arrays Declaring, creating, initializing in one step: int a[5]={1,5,7,9,10]; → a[0]=1, a[1]=5,…,a[4]=10 int b[3] ={1};→ b[0]=1,b[1]=0,b[2]=0 int c[2] = {1,2,3,4};→ ERROR To set every element to same value: int d[5] = {0}; If array size omitted, initializers determine size int e[ ] = {1, 2, 3, 4, 5}; //this implies size of a is 5
Initializing Arrays (cont.) If A is an array and B is an array of same dimension (size) we can assign A = B The contents of B will be copied to array A Example: int A[4]={11,33,55,66}, B[4]; B = A;//B[0]= 11,…,B[3] =66
Example #include int main() { double distance[5] = {44.14, , 96.08, , 6.28}; cout << "Members of the array\n"; 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; } Outputs:
Example #include int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, , 96.08, , 6.28}; cout << "Members of the array\n"; for(int i = 0; i < numberOfItems; ++i) cout << "Distance " << i + 1 << ": " << distance[i] << endl; return 0; } Outputs:
Example // Read a set of integers and find the sum and average void main( ) { int a[20], i, sum=0, n; float average; cout<< "How many integers to be taken: " ; cin>> n; for(i=0; i<n; i++) //Read and add to sum { cout<<"Enter an integer:"; cin>> a[i]; sum = sum + a[i]; } average = sum / (float)n; cout<< “Sum= " << sum << endl << “Average= " << average << endl; } Outputs:
Functions A function is a group of statements that together perform a task. Every C++ program has at least one function which is main(). Using functions facilitates the construction of the programs in a more modular way. There are two kinds of functions: Built-in functions: those supplied to you User-defined functions: those which you are going to write
Advantages of writing functions Reduces the complexity of main Work can be divided Function can be reused many times Easier to read and understand Easier to find-out errors and modify the program
Built-in functions Examples of pre-defined functions: Mathematical Functions pow(x,y), sqrt(x), sin(x), cos(x) String and Character Functions tolower(x), toupper(x), strlen(x), strncmp(x,y) Time, Date and Localization Functions time(&x), difftime (x,y)
Example #include int main() { cout << "2 to the power of 2 is: " << pow(2,2) << endl; cout << "4 to the power of 2 is: " << pow(4,2) << endl; return 0; } Outputs:
User-defined functions - Syntax type name ( parameter1, parameter2,...)// function header { statements } //function body type: is the data type specifier of the data returned by the function. name: is the identifier by which it will be possible to call the function. parameters: Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow passing arguments to the function when it is called. The different parameters are separated by commas. Statements: is the function's body. It is a block of statements surrounded by braces { }.
Function Declaration In order to create and use a function, you must send an acknowledgement to the compiler to know. The syntax of declaring a function is: ReturnType FunctionName(Parameters); An assignment, considered as a function, is made of three parts: its purpose, its needs, and the expectation. Based on this formula, the expectation you have from a function is the ReturnType factor. The simplest return type you can use is called, and represented as, void. Using this keyword, the simplest formula we can use is: void FunctionName();
Function Names A function name follows the same rules we have applied to our variables. In addition, use a name that specifies what the function is expected to do. Usually, a verb is appropriate for a function that performs an action. Examples of names of functions are Add, Start, Assign, Play, etc.
The return statement A return statement ends the processing of the current function and returns control to the caller of the function. The following are examples of return statements: return; // Returns no value return result;// Returns the value of result return 1; // Returns the value 1 return (x * x);// Returns the value of x * x
Example Write an example of a function that returns nothing void do-nothing () { } void do-nothing () { return; } /* Can be written with or without retuen */ Write an example of a function that returns some values int do-nothing() { return 0; } int do-nothing () { } /* Error because it musts return an integer value */
Function call a C++ program always starts by calling main. In fact, main is the only function called automatically. The code in any other function is only executed if its function is called from main. A function is called by writing its name, followed by (). If the function takes arguments, the arguments are passed, in the order listed in the function declaration, in the parentheses. Function call syntax: FunctionName (Arguments if any);
Structure of a program #preprocessor directives prototypes void main() { statements; } DataType function1(Parameters if any) { statements; } DataType function2(Parameters if any) { statements; }.
Example // void function example #include void printmessage (); //Prototype int main () { printmessage (); //Call return 0; } void printmessage () //Header { cout << "I'm a function!"; } Outputs:
Example #include int addition(int a, int b); int main() { int x,y,z; cout << "Enter the first integer: "; cin >> x; cout << "Enter the second integer: "; cin >> y; addition(x,y); cout << "Sum of X and Y is:" << z << '\n'; } int addition(int a, int b) { int r; r = a + b; return (r); } Outputs:
Example #include int addition(int a, int b); int main() { int x,y,z; cout << "Enter the first integer: "; cin >> x; cout << "Enter the second integer: "; cin >> y; z = addition(x,y); cout << "Sum of X and Y is:" << z << '\n'; } int addition(int a, int b) { int r; r = a + b; return (r); } Outputs:
Example #include int addition(int a, int b); int main() { int x,y,z; cout << "Enter the first integer: "; cin >> x; cout << "Enter the second integer: "; cin >> y; cout << "Sum of X and Y is:“; cout << addition(x,y); } int addition(int a, int b) { int r; r = a + b; return (r); } Outputs:
Example #include int addition(int a, int b); int main() { int x,y,z; cout << "Enter the first integer: "; cin >> x; cout << "Enter the second integer: "; cin >> y; z = addition(x,y); cout << "Sum of X and Y is:" << z << '\n'; } int addition(int a, int b) { return (a+b); } Outputs:
Example #include int addition(int a, int b); int main() { int x,y,z; cout << "Enter the first integer: "; cin >> x; cout << "Enter the second integer: "; cin >> y; z = addition(x);//Error z = addition(1,2,3); //Error cout << "Sum of X and Y is:" << z << '\n'; } int addition(int a, int b) { return (a+b); } Outputs:
Example #include bool IsEven (int num); int main() { int x; bool z; cout << "Enter an integer number: "; cin >> x; z = IsEven(x); cout << “Result is: " << z << '\n'; z = IsEven(3); cout << “Result is: " << z << '\n'; z = IsEven(x+3); cout << “Result is: " << z << '\n'; } bool IsEven (int num) { if (num%2 == 0) return true; else return false; } Outputs:
Exercise Write a C++ program that will display the calculator menu. The program will prompt the user to choose the operation choice (from 1 to 5). Then it asks the user to input two integer vales for the calculation. See the sample below. MENU 1. Add 2. Subtract 3. Multiply 4. Divide 5. Modulus Enter your choice: 1 Enter your two numbers: Result: 27