1 / 27

Chapter 10 Arrays and Functions

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

alessa
Télécharger la présentation

Chapter 10 Arrays and Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10Arrays and Functions Prepared by: Lec. GhaderKurdi

  2. 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]

  3. Declaration Syntax DataTypeArrayName[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.

  4. Initializing Arrays • Declaring, creating, initializing in one step: inta[5]={1,5,7,9,10]; → a[0]=1, a[1]=5,…,a[4]=10 intb[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 inte[ ] = {1, 2, 3, 4, 5}; //this implies size of a is 5

  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

  6. Example #include <iostream> intmain() { 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:

  7. Example #include <iostream> intmain() { constintnumberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout<< "Members of the array\n"; for(inti = 0; i < numberOfItems; ++i) cout<< "Distance " << i + 1 << ": " << distance[i] << endl; return 0; } Outputs:

  8. 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:

  9. 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

  10. 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

  11. 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)

  12. Example #include <iostream.h> #include <math.h> intmain() { 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:

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

  14. 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: ReturnTypeFunctionName(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 ReturnTypefactor. • 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();

  15. 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.

  16. 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

  17. Example Write an example of a function that returns nothing Write an example of a function that returns some values intdo-nothing() { return 0; } intdo-nothing () { } /* Error because it musts return an integer value */ void do-nothing () { } void do-nothing () { return; } /* Can be written with or without retuen */

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

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

  20. Example // void function example #include <iostream> void printmessage(); //Prototype intmain () { printmessage (); //Call return 0; } void printmessage() //Header { cout << "I'm a function!"; } Outputs:

  21. Example #include<iostream.h> int addition(inta, int b); intmain() { intx,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(inta, int b) { int r; r = a + b; return (r); } Outputs:

  22. Example #include<iostream.h> int addition(inta, int b); intmain() { intx,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(inta, int b) { int r; r = a + b; return (r); } Outputs:

  23. Example #include<iostream.h> int addition(inta, int b); intmain() { intx,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(inta, int b) { int r; r = a + b; return (r); } Outputs:

  24. Example #include<iostream.h> int addition(inta, int b); intmain() { intx,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(inta, int b) { return (a+b); } Outputs:

  25. Example #include<iostream.h> int addition(inta, int b); intmain() { intx,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(inta, int b) { return (a+b); } Outputs:

  26. Example #include<iostream.h> boolIsEven(intnum); intmain() { 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'; } boolIsEven(intnum) { if (num%2 == 0) return true; else return false; } Outputs:

  27. 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

More Related