chapter 10 arrays and functions prepared by: lec. ghader kurdi

27
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Upload: linda-mabel-richard

Post on 18-Jan-2016

217 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

CHAPTER 10ARRAYS AND FUNCTIONSPrepared by: Lec. Ghader Kurdi

Page 2: 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]

Page 3: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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.

Page 4: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Initializing Arrays • Declaring, creating, initializing in one step:

int a[5]={1,5,7,9,10]; → a[0]=1, a[1]=5,…,a[4]=10int b[3] ={1};→ b[0]=1,b[1]=0,b[2]=0int c[2] = {1,2,3,4};→ ERROR

• To set every element to same value:int d[5] = {0};

• If array size omitted, initializers determine sizeint e[ ] = {1, 2, 3, 4, 5}; //this implies size of a is 5

Page 5: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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

Page 6: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example

#include <iostream>int main(){ double distance[5] = {44.14, 720.52, 96.08, 468.78, 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:

Page 7: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example

#include <iostream>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;}

Outputs:

Page 8: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example// Read a set of integers and find the sum and averagevoid 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:

Page 9: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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

Page 10: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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

Page 11: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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)

Page 12: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example

#include <iostream.h>#include <math.h>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:

Page 13: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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 { }.

Page 14: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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;)(

Page 15: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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.

Page 16: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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 valuereturn result; // Returns the value of resultreturn 1; // Returns the value 1return (x * x); // Returns the value of x * x

Page 17: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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 */

Page 18: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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

Page 19: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Structure of a program#preprocessor directivesprototypesvoid main(){ statements; }DataType function1(Parameters if any){ statements;}DataType function2(Parameters if any){ statements;}...

Page 20: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example

// void function example#include <iostream>void printmessage (); //Prototypeint main (){ printmessage (); //Call return 0;}void printmessage () //Header{ cout << "I'm a function!";}

Outputs:

Page 21: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example#include<iostream.h>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:

Page 22: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example#include<iostream.h>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:

Page 23: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example#include<iostream.h>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:

Page 24: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example#include<iostream.h>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:

Page 25: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example#include<iostream.h>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:

Page 26: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

Example#include<iostream.h>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:

Page 27: CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi

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: 12 15 Result: 27