• No results found

Functions.pdf

N/A
N/A
Protected

Academic year: 2020

Share "Functions.pdf"

Copied!
22
0
0

Loading.... (view fulltext now)

Full text

(1)

1

Functions

A computer program (except for a very simple one)

cannot handle every task alone. Instead it calls on

other programs like entities called

Functions,

to carry

out specific tasks.

Functions can be:

Pre-defined (printf(), scanf())

User defined

2

Advantages of Functions

Avoiding unnecessary repetition of code:

original reason functions (or sub-routines) were

invented was to avoid having to write the same code

over and over.

(2)

3

Instead, in effect you want to jump to that section of

code that calculates sq. root and then jump back again

to normal program flow, when you are done.

In this way a single section of code can be used many

times in the same program.

Program Organization:

Functions made it easier to organize programs and

keep track of what they are doing.

if operation of program could be divided into separate

activities and each activity placed in a separate

sub-routine, then each sub-routine could be written and

checked out more or less independently.

4

Separating the code into modular functions also made

programs easier to design and understand.

Independence:

Sub-routines were invented that had their own private

variables that is variables that could be accesses from

the main program, or other functions. This means that

the programmer didn't need to worry about

accidentally using the same variable names in

different sub routines.

(3)

5

Simple Functions

void name (void);

Function Declaration

void main()

{

name();

Function call

}

void name()

Function Definition

{

for (int count=1; count<=5; count++)

printf(“Hello\n”);

}

6

Structure of Function

There are 3 program elements involved in

using a function.

1.

Function Definition

2.

Calling the Function (Call to Function)

(4)

7

Function Definition

 The function definition is the function itself. The definition starts with a line that includes the function name, among other elements are the arguments and function body which are enclosed in opening and closing brace.

 In the example the first void means that name() doesn't return anything and second means that it takes no arguments.

 Also note that the declarator doesn't end with a semicolon. It is not a program statement, whose execution causes something to happen. Rather it tells the compiler that a function is being defined.

 The function definition continues with body of function; the program statements that do the work.

type function_name() {

statements; }

8

Calling the Function

The function call executes the function.

As with the C library functions such as printf(), scanf(),

getch() etc, user-written function name() is called from main().

Simply by using its function name, including the parenthesis

following the name i.e. name();

The parenthesis lets the compiler know that you are referring

to a function and to a variable name or something else.

Calling the function like this is a C statement, so it ends with a

semicolon.

(5)

9

Function Prototype or Declaration

 A prototype declares the function.

void name(void);

 Looks much like the first line at start of function definition , except that it ends with a semicolon.

 Like all the variables in C programs must be defined by a name and data type before they can be used, a function is declared in a similar way at the beginning of program before it is called.

 It tells the compiler the name of function, the number and data types of the function’s arguments (if any). The data types of the function returns (if any).

 In our example, function returns nothing and takes no arguments hence 2 voids.

 The prototype is written before the main() function this causes the prototype to be visible to all the functions in the file.

10

Types of Variables

 There are 4 types of variables: 1. Local

2. Global 3. External 4. Static

Global variables:

All those variables which are declared in main() module are called global variables.

Local variables:

A local variable is visible to the function it is defined in, but not to others. All those variables which are declared in user-defined functions are local variables. Variables used in a function are unknown outside the function. Also calledautomatic variable, because it is automatically created when a

(6)

11

Types of Variables

External variables:

Variables known to all functions in a program rather than just one. This is true when many different functions must read or modify a variable, making it clumsy or impractical to communicate the value of variable from function to function using arguments and return values. In this case we use an “external variable” (sometimes called a global variable).

Static variables:

Another class of local variable is static type. They can only be accessed from the function in which it was declared, like local variable. It is not destroyed on exit from the function, instead its value is preserved and becomes available again when the function is again called. Declared as local variables but the declaration is preceded by the word “static”

static int counter;

12

Visibility of a Variables

Visibility or scope of a variable refers to which part of a program will be able to recognize it. A variable may be visible in a block, a function, a file or group of files or an entire program.

E.g.. Automatic is only visible within function in which it is defined.

Lifetime of a variable:

(7)

13

Example of local variable

void calculatesum(void); void main()

{calculatesum(); printf(“End of main”); getch();

}

void calculatesum() {

int mark1, mark2, total; //local variables mark1=7; mark2=5;

total = mark1+mark2;

printf(“Total marks are %d”,total);

}

14

Example

# include <dos.h> void beep(void); void main() {

beep(); getch(); }

void beep() {

printf(“\x7”); \\for beep delay(10000);

printf(“\x7”); }

This program calls the subroutine beep(), which does just what its name says, it sounds 2 beeps separated by a short silent interval.

delay(unsigned ms)

(8)

15

Functions that return a value

An analogy can be made here with hiring someone to find out

something for you. In a way you do this when you dial your telephone service to find out what time it is.

You make the call, the person (or computer) on other end of line gives you the time and that’s it. You don’t need to tell them what you want. That’s understood when you call that number. No information flows from you to phone company, but some flows from it back to you.

A function that uses no arguments but returns a value performs a similar role. You call the function, it gets a certain piece of information and returns it to you. E.g. getche() operates in the same way, you call it without giving it any information and it returns the value of first character typed on the keyboard.

16

Examples

int func (void);

\\ function that returns an integer value

void main() {

int num; num = func(); printf(“%d”,num); } int func() { return(10); }

void func (void); void main() { func(); } void func() {

printf(“this is printed”); return;

printf(“never printed”); }

Return statement can also be used without parenthesis when this is the case no value is returned to calling program. Function may return any type of data/

General form: Type

functio_name(parameter_list) {statements;

(9)

17

Example to depict getch

char getlc(void); void main() {char chlc;

printf(“Type a for first selection, b for second”); chlc = getclc();

switch(chlc) {

case ‘a’:

printf(“you typed a); break; case ‘b’:

printf(“you typed b); break; default;:

printf(“you typed a non-existent selection); }

}

18

Example to depict getch

char getlc(void) {

char ch; ch = getche();

if(ch > 64 && ch <91) ch = ch+32; return(ch); }

(10)

19

return statement

 In the earlier beep program, function returned back to the calling program when it encountered the final closing brace which defined the end of function. No separate return statement was necessary. This approach is fine if function is not going to return a value to the calling program.

 But in the above we want to return the value of the character read from the keyboard. In fact we want to return one of 2 possible values.

 The character itself if it is in lower case already or  A modified version of character if it is in upper case.

 So we use if to check if ch is in upper case if so we add 32 to ch (diff between ASCII ‘A’ and ‘a’)

 Finally return to calling program with the new value of character by placing the variable name b/w the parenthesis following return.

20

Purpose of return statement

 It has 2 purposes:

1. First, executing it immediately transfers the control from the function back to the calling program

2. Whatever is inside the parenthesis following return() is returned as a value to calling program.

It can also be used without parenthesis. When this is the case, no value is returned to calling program.

Limitation of return

 Using a return statement only one value can be returned by a function,

(11)

21

Returning type int

 Following example gets time in hrs and mins from user, and calculates the difference in seconds b/w 2 times.

Example

int getmins(void); void main() {int min1, min2;

printf(“Type in first time”); min1=getmins();

printf(“Type in second time”); min2=getmins();

printf(“Difference is %d minutes”,min2-min1); }

22

Returning type int

int getmins() {

int hours, minutes;

scanf(“%d : %d”,&hours, &minutes); return(hours*60 + minutes);

}

New wrinkle in scanf()

 There is a colon b/w 2 format specifiers rather than space

 This has the effect of requiring user to type a colon between 2 numbers

(12)

23

Returning type float

 In the following example function returns type float. Main() asks user for radius of sphere then calls a function named area() to calculate area of sphere which returns area of sphere in form of floating point value.

Example

Float area (float); void main() {float radius;

printf(“Enter radius of sphere”); scan(“%f”,&radius);

printf(“area of sphere is %.2f ”,area(radius)); }

24

Returning type float

float area (float radius) or float area (float rad) {

(13)

25

Arguments

 Mechanism used to convey information to a function in the argument.

 printf() and scanf() uses arguments; format strings and values inside the parenthesis in these functions are the arguments

Actual Arguments

Arguments in the calling program is referred to as the actual arguments. The variable radius in the calling program is the actual argument Formal Arguments

Arguments in the called function is referred to as the formal arguments. The variable rad in the called function is the formal argument

We can use same names for both variables; since they are in different functions the compiler would still consider them separate variables

26

Using arguments to pass data to functions.

Example: Single argument passed to a user defined function

void bar (int); void main() {

printf(“Ali\t”); bar(27);

printf(“Ahmed\t”); bar(41);

printf(“Hamid\t”); bar(34);

getch(); }

For each person, main() prints name and then calls function using as an argument the score received by that person on a test to draw a horizontal bar, ‘score’ chars long.

(14)

27

Using arguments to pass data to functions.

void bar (int score);

{

for(int j=1; j<=score; j++)

printf(“\xCD”); //xCD = double lines graphic character printf(“\n”); // new line at end of bar

}

In the function definition a variable name “score” is placed in parenthesis following bar;

void bar (int score)

This ensures that value included b/w parenthesis in main program is assigned to variable b/w parenthesis in function definition.

Data type of score is also specifies in function definition this constitutes definition of argument variables setting aside memory space for it in function.

28

Passing variables as Arguments

void bar (int inscore); void main()

{ int inscore =1;

while(inscore != 0 ) //exit on zero score { printf(“Score = ”);

scanf(“%d”,&inscore);

bar(inscore); //actual argument }

}

void bar (int score) //formal argument {

for(int j=1; j<=score; j++) printf(“\xCD”); printf(“\n”);

(15)

29

Passing variables as Arguments

 In the previous example , We passed constants (such as number 27) as an arguments to function bar(). We can also use a variable in calling program.

 Function bar() is same as before however main() has been modified to accept some scores from keyboard, since the scores passed to bar() are no longer known in advance, we must use a variable to pass them to the bar() function.

 Whatever value the user types in is recorded by scanf() assigned to variable “inscore” and when bar() is called, this value is passed to it as an argument.

30

Passing Multiple Arguments

int calsum (int, int , int); void main()

{ int a,b,c, sum;

printf(“Enter any 3 numbers ”); scanf(“%d %d %d”,&a, &b, &c); sum = calsum(a,b,c);

printf(“Sum = %d”,sum); }

int calsum (intx, int y, int z) //formal argument {

(16)

31

Passing Multiple Arguments

double volume (double s1, double s2 , double s3); void main()

{ double vol;

vol = volume(12.2,5.76,9.03); printf(“Volume = %f”, vol); }

double volume (double s1, double s2 , double s3) {

return(s1*s2*s3); }

32

Using more than one function

 C allows the use of as many functions as a programmer likes and any of the function can call any of other.

 In C, all functions including main() have equal status and are visible to all other functions.

 The example below calculates the sum of squared of integers typed in by user.

 Program actually uses 3 functions as well as main()

 First function does the actual calculation, while main() simply gets the number from the user and prints the result.

 Second function returns the square of a number

(17)

33

Using more than one function

int sumsqr(int, int); int sqr(int);

int sum(int, int); void main() { int num1, num2;

printf(“Enter any 2 numbers ”); scanf(“%d %d”,&num1, &num2); printf(“Sum of squares = %d”,sumsqr(num1,num2)); }

//returns sum of squares of 2 arguments int sumsqr(int j, int k)

{

return ( sum( sqr(j), sqr (k) ) ); }

//returns squares of argument int sqr(int z)

{

return ( z*z ); }

//returns sum of 2 arguments int sum(int x, int y)

{

return ( x+y ); }

34

Using more than one function

//returns squares of argument int sqr(int z)

{

return ( z*z ); }

//returns sum of 2 arguments int sum(int x, int y)

{

(18)

35

Using more than one function

 None of the functions is nested inside any other

 In C, all the functions visible to all other functions

 The main() program for instance could call sum() or sqr() directly if it needed to.

 Functions can appear in any order in the program listing. They can be arranged alphabetically in the order in which they are called, by functional group, or any other way the programmer wishes.

 Arranging the functions in an order makes them easier to use, which can be a real advantage for programmer, especially in larger programs with many functions.

36

External Variables

void oddeven(void); void negative(void);

int keynumb; //External variable void main()

{

printf(“type a number ”); scanf(“%d” ,&keynumb); oddeven(); negative(); }

void oddeven(void) { if(keynumb %2)

printf(“ even number ”); else

(19)

37

External Variables

void negative(void) { if(keynumb < 0)

printf(“ negative number ”); else

printf(“ Positive number ”); }

In this program main() and 2 other functions all have access to the variable keynumb.

To achieve this global status it is necessary to declare it outside of all the functions including main()

38

Drawbacks of using External Variables

 They are not protected from accidental alteration by functions that have no business modifying them

(20)

39

Pre-Processor Directives

Preprocessor directives are actually the instructions to the

compiler itself. They are not translated but are operated

directly by the compiler. Always start with the number sign

(#). The most common preprocessor directives are:

i. # include directive

ii. # define directive

iii. Macros

40

Pre-Processor Directives

i.

define directive:

It is used to assign names to different constants or

statements which are to be used repeatedly in a program.

These defined values or statement can be used by main or

in the user defined functions as well. They are used for:

a. defining a constant

b. defining a statement

(21)

41

Pre-Processor Directives

Example

#define PI 3.142

float area (float)

void main()

{

float radius;

printf(“Enter radius:);

scanf(“%f”,&radius);

printf(“Area of sphere is %f”, area(radius));

}

float area(float rad)

{

return(4 * PI * rad * rad);

}

42

Pre-Processor Directives

ii. Macros

A # define directive can take arguments like functions.

Example

# define PR(n) printf(“%.2f\n”,n):

void main()

{

float num1, num2;

num2 = 1.0/3.0;

PR(num1);

PR(num2);

}

(22)

43

Pre-Processor Directives

ii. Macros

A # define directive can take arguments like functions.

Example

# define AREA_SPHERE(rad) (4*3.15*rad*rad)

void main()

{

float radius;

printf(“Enter radius of sphere”);

scan(“%f”,&radius);

printf(“area of sphere is %.2f ”, AREA_SPHERE (radius));

}

44

Pre-Processor Directives

iii. # include directive:

Causes one source file to be included into another. The #

include directive is used to include files like we include

header files in the beginning of the C program using

#include directive.

Example

Source file might look like this:

# define PI 3.14159

References

Related documents

Regarding the second research question, the findings revealed that among the 3 components of pre-service teachers’ self-efficacy, efficacy in student engagement, efficacy

     •  Location of event      •  Date(s) of event  Webcasting

The paper argues that there is a breakup of community social structures as evident from changes in family relations in critical domains such as extra-marital relations, sexual

Speaking a Java idiom, methods are synchronized, that is each method of the same object is executed in mutual exclusion, and method invocations are asynchronous, that is the

3. WILSON has been an Arizona resident at all relevant times.. WILSON was not registered by the Commission as a securities dealer or salesman. WILSON incorporated TNBV as a

India stands out for its comprehensive rural water database known as Integrated Management Information System (IMIS), which conducts annual monitoring of drinking water coverage,

Uniting theoretical approaches to fairness to an overview of the empirical literature, we illuminate the salient features of fairness relations in complex

Your Maximum Total Housing Payment (Rule of 32): The next rule stipulates that your total housing payments (including the mortgage, homeowner’s insurance and private mortgage