Download presentation
Presentation is loading. Please wait.
1
Introduction to Functions
Addis Ababa Institute of Technology Yared Semu May 2012
2
Recap Program Flow Control while loop do…while loop for Loop break
continue
3
Revision #include <iostream> using namespace std; int main () {
int n; cout << "Enter the starting number :> "; cin >> n; while (n>0) cout << n << ", "; n--; } cout << "FIRE!\n"; return 0; Enter the starting number > 8 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
4
The for Loop Statement The for loop is ideal for working with counters because it provides built-in expressions that initialize and update variables. It’s a pretest loop.
5
Contd… How it Works: 1) INITIALIZATION is executed. Generally it is an initial value setting for a counter variable. This is executed only once. 2) CONDITION is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped (not executed). 3) STATEMENT(S) is executed. As usual, it can be either a single statement or a block enclosed in braces { }. 4) Finally, whatever is specified in the UPDATE field is executed and the loop gets back to step 2.
6
Omitted Expressions This for loop produces the result:
The initialization and update fields are optional. They can remain empty, but in all cases the semicolon signs between them must be written. int i=0; for ( ; i < 10; ) { cout << i << " "; i++; } This for loop produces the result:
7
Contd… Although you do not see it very often, it is worth noting that the following example produces an infinite loop: for (;;) statement(s) When condition is not specified it defaults to true .
8
Null statements It is also possible to omit the statement part of a for loop. This is called a null statement, and it is declared by using a single semicolon. for(int i = 0; i< 10; i++) ; This loop increments i using the ++ operator 10 times. When the statement is executed, the null statement evaluates to nothing, and consequently, doesn't do anything.
9
Multiple Declarations
Optionally, using the comma operator (,) we can specify more than one expression in any of the fields included in a for loop, like in initialization, for example. for (int i=0, j=9; i < 10; i++, j--) cout << i << " " << j << endl;
10
Multiple Declarations
The previous program produces the result
11
The break statement It can be used to end an infinite loop, or to force it to end before its natural end. For example, we can stop the count down to launching a space shuttle before its natural end (maybe because of an engine check failure?):
12
Example 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
// break loop example #include <iostream> using namespace std; int main () { int n; for (n=10; n>0; n--) cout << n << ", "; if (n==3) cout << "countdown aborted!"; break; } return 0; 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
13
The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to jump to the start of the following iteration.
14
Contd… In a while loop, this means the program jumps to the test expression at the top of the loop. 2) In a do-while loop, the program jumps to the test expression at the bottom of the loop, which determines if the next iteration will begin. 3) In a for loop, continue causes the update expression to be executed, and then the test expression to be evaluated.
15
Example // continue loop example #include <iostream>
using namespace std; int main () { for (int n=10; n>0; n--) if (n==5) continue; cout << n << ", "; } cout << "FIRE!\n"; return 0; 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
16
Introduction to Functions
17
Modular Programming A function is a collection of statements that performs a specific task. (also called a module) and is executed when it is called from some point of the program. A function performs some computation and usually yields a result. Modular Programming: breaking down a program into a set of manageable functions, or modules.
18
Function Definition type name ( parameter1, parameter2, ...) {
statements } Where: TYPE : is the data type specifier of the data or value returned by the function. NAME : is the identifier by which it will be possible to call the function. Naming rules are the same as those for variables PARAMETER LIST : (as many as needed): a list of variables that hold values being passed into the function. The different parameters are separated by commas. STATEMENT(S) : is the function's body. It is a block of statements surrounded by braces { }.
19
The main Function Line 1 is known as the function header
Name Parameter List goes here Return Type Body Line 1 is known as the function header Every statement within the curly braces is regarded as the function body. The last statement within the function is usually a special statement (return statement) that returns the value computed by the function
20
Example float cube(float num) { float r = num*num*num; return r; }
Identify the parts of this function.
21
Function Call Statements
The main function starts executing automatically when the program starts. All other functions have to be called explicitly to start executing. This is done by using function call statements.
22
Program Flow With Functions
At the point at which the function is called from within main, the control is lost by main and passed to function (addition). When the called function finishes execution, it returns the control back to the function that called it in the first place (in this case, main).
23
Program Flow with Function(2)
void printString() { cout<<“In Function Call…”<<endl; cout<<“Hello World!”<<endl; } int main () cout<<“Before function call…”<<endl; printString(); cout<<“After function call…”<<endl; return 0; Predict the output!
24
Example The result is 8 #include <iostream> using namespace std;
// 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; return 0; The result is 8
25
Contd… We can see the similarity between the structure of the call to the function and the declaration of the function itself some code lines above: The parameters and arguments have a clear correspondence. Values that are passed into a function are called arguments and the variables that accept these values are called parameters.
26
Contd… The following line of code return (r);
finalizes function addition, and returns the control back to the function that called it in the first place (in this case, main).
27
Another example int subtraction (int a, int b) { int r = a-b;
return (r); } int main () int x=5, y=3, z; z = subtraction (7,2); cout << "The first result is " << z << '\n'; cout << "The second result is " << subtraction (7,2) <<'\n'; cout << "The third result is " << subtraction (x,y) << '\n'; z= 4 + subtraction (x,y); cout << "The fourth result is " << z << '\n'; return 0; Note: we have made several calls to function subtraction. The first result is 5 The second result is 5 The third result is 2 The fourth result is 6
28
Functions with no type. The use of void.
If you remember the syntax of a function declaration: type name ( argument1, argument2 ...) statement you will see that the declaration begins with a type (i.e., the type of the datum that will be returned by the function with the return statement). But what if we want to return no value? Imagine that we want to make a function just to show a message on the screen. We do not need it to return any value. In this case we should use the void type specifier for the function. This is a special specifier that indicates absence of type.
29
Example I'm a function //void function example
#include <iostream> using namespace std; void printmessage () { cout << "I'm a function!"; } int main () printmessage (); return 0; I'm a function
30
Points to Remember You must define the function before calling it.
When writing a parameter list, each variable must have a data type associated with it. You can't leave out the data type of a variable even if it has the same type as the variable declared before it. A function call, when used as an expression, evaluates to the value returned by the function.
31
Quiz (5pts) Write a menu driven program that does addition, subtraction, multiplication, and division of two numbers. Define each operation in its own function. The program should end only when the user asks it to.
32
Course Project Group yourselves into groups of 4. Write the names of each group member and submit it to me tomorrow.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.