• No results found

• A function is a named, independent section of C code that performs a specific task and optionally returns a value to the calling program.

N/A
N/A
Protected

Academic year: 2022

Share "• A function is a named, independent section of C code that performs a specific task and optionally returns a value to the calling program. "

Copied!
50
0
0

Loading.... (view fulltext now)

Full text

(1)

Functions

(2)

What is Function in C?

• Functions are central to C programming and to the philosophy of C program design.

• A C program consists of one or more function definitions, including exactly one that must be called main().

• A function is a named, independent section of C code that performs a specific task and optionally returns a value to the calling program.

• All functions are stand-alone, which means that they are not nested in any other construct.

2

(3)

What is Function in C?

∙A function is named: Each function has a unique name. By using that name in another part of the program, one can execute the statements contained in the function. This is known as calling the function. A function can be called from within another function.

∙A function is independent: A function can perform its task

without interference from or interfering with other parts of the

program.

(4)

What is Function in C?

∙A function performs a specific task: Such as sending a line of text to a printer, sorting an array into numerical order or calculating a cube root.

∙A function can return a value to the calling program: When a program calls a function, the statements it contains are executed. If you want them to, these statements can pass information back to the calling program.

4

(5)
(6)

6

(7)

Types of Function

•Library Function

•User-Defined Functions

• Declaration and Definition

• Function Documentation

• Function Parameters

• Examples

(8)

Function Declaration and Definition

A declaration merely provides a function prototype.

Function header :

Includes the return type and the list of parameters Syntax:

return_type function_name( arg-typ name-1,...,arg-typ name-n);

Example:

int hex(int val);

8

(9)

Function Declaration and Definition

The definition of a function includes both the function prototype and the function body, i.e. its implementation.

Syntax:

return_typ function_name(arg-typ name-1,...,arg-typ name-n) {

/* statements; */

}

Example:

int hex(int value) {

statements;

}

(10)

Function Parameters

There are two types of function parameters:

Formal parameters:

Appear in a declaration or a definition of a function.

Actual parameters:

Appear in a call to the function.

Examples:

int f(int x); here x is a formal parameter i = f(3); here 3 is the actual parameter

corresponding to the formal parameter. 10

(11)

/* Function: max

* Purpose : Find the maximum of its integer * arguments

* Inputs : Two parameters

* Returns : The maximum of parameters * Modifies: Nothing

* Error checking: None

* Sample call: i = max(k, 3)

*/

int max(int, int);

int max(int i, int j) {

return i > j ? i : j;

}

(12)

Passing Arguments to a Function(1)

There are two ways of passing argument to a function”

Pass by value

Pass by reference

12

(13)

Passing Arguments to a Function(1)

Pass by value :

Single value is passed to a function via an actual argument.

The value of actual argument is copied into a function.

The value of corresponding argument can be altered within the function.

The value of the actual argument within the calling routine will

not be changed.

(14)

Passing Arguments to a Function: Pass by value

void main() {

int a = 7, b = 4;

swap(a, b);

printf("Original values are a = %d and b = %d", a, b);

printf("The values after swap are a = %d and b = %d", a, b);

}

void swap(int x, int y) {

int temp;

temp = x;

x = y;

y = temp;

printf("Swapped values are a = %d and b = %d", x, y);

}

Output: Original Values are a = 7 and b = 4 Swapped values are a = 4 and b = 7 14

(15)

Passing Arguments to a Function: Pass by value

The values after swap are a = 7 and b = 4

This happens because when function swap() is invoked, the values of a and b gets copied on to x and y.

The function actually swaps x and y while the original variables a and b remains

intact.

(16)

Passing Arguments to a Function(2)

Pass by reference:

Single value is passed to a function via an actual argument.

The address of actual argument is passed into a function.

The value of corresponding argument can be altered within the function.

The value of the actual argument within the calling routine will also be changed.

16

(17)

Passing Arguments to a Function: Pass by reference

void main() {

int a = 7, b = 4;

swap(&a, &b);

printf("Original values are a = %d and b = %d",a,b);

printf("The values after swap are a = %d and b = %d",a,b);

}

void swap(int *x, int *y) {

int temp;

temp = *x;

*x = *y;

*y = temp;

printf("Swapped values are a = %d and b = %d", *x, *y);

} Output: Original Values are a = 7 and b = 4

Swapped values are a = 4 and b = 7

(18)

Passing Arguments to a Function: Pass by reference

The values after swap are a = 4 and b = 7

This happens because when function swap() is invoked, it creates a reference for the first incoming integer a in x and the second

incoming integer b in y.

18

(19)

Advantages & Disadvantages: Pass by value

It protects the value of actual argument from alteration within the function.

It does not allow information to be transferred back to the calling portion of the program via arguments.

Passing by value is restricted to a one way transfer of

information

(20)

Complete C Program Using Function

long int cube(int); /* Function declaration */

int main()

{ long int c;

c = cube(5); /* Function call */

printf(“Cube of 5 = %ld”,c);

return;

}

/* Function definition starts from here */

long int cube(int num)

{ long int cb; /*Local variable declaration */

cb = num*num*num;

return cb; /* Return value */

}

Actual parameter

Formal parameter

20

(21)

What will be the output???

int Addnum(int, int);

int main()

{ int a = 10,b = 20;

printf("%d %d %d",a,b,Addnum(a,b));

return;

}

int Addnum(int a, int b) { int c;

c = a+b;

return c;

}

(22)

•User-Defined Functions

• Examples

Functions with no arguments and no return value Functions with arguments and no return value Functions with arguments and return value

Functions with no arguments but returns a value

• Passing Array as an argument to a function One dimensional

Two dimensional Strings

22

(23)

Functions with no arguments and no return value

void displayline(void);

void sum(void);

void main()

{ displayline();

sum();

}

void displayline() { int j;

for(j=0;j<40;j++) printf(“*”);

}

void sum() {int a,b;

printf(“Enter a and b\n”);

scanf(“%d %d”,&a,&b);

printf(“Sum = %d ”,(a+b));

}

Calling function

Called functions

(24)

Functions with arguments and no return value

void displayline(char);

void Sum(float, float);

void main() { char ch;

float a,b;

printf(“Enter character to print in line\n”);

scanf(“%c”,&ch);

displayline(ch);

printf(“Enter value of a and b\n”);

scanf(“%f %f”,&a,&b);

Sum(a,b);

}

24

(25)

Functions Definition

void displayline(char ch) { int j;

for(j=0;j<40;j++) printf(“%c”,ch);

}

void Sum(float x, float y) {

printf(“Sum = %f ”,(x+y));

}

(26)

Functions with arguments and return value

int Add(int, int);

int Sub(int, int);

int Div(int, int); /* Function Prototype */

int main() { int x,y;

printf(“Enter two values:\n”);

scanf(“%d %d”,&x,&y);

printf(“Sum =%d”,Add(x,y));/*Function Call*/

printf(“Subtraction = %d”,Sub(x,y));

printf(“Division = %d”,Div(x,y));

return;

}

26

(27)

Function Definition

int Add(int a,int b) {

return(a+b);

}

int Sub(int a,int b) {

return(a-b);

}

int Div(int a,int b) {

return(a/b);

}

(28)

No arguments but returns a value

int ReadNumber(void);

void main()

{ int num = ReadNumber();

printf(“%d”,num);

}

int ReadNumber(void) { int number;

scanf(“%d”,&number);

return(number);

}

Example: getchar()

28

(29)

Passing Arrays To Functions (Pass by reference)

One- dimensional Array:

int maximum(int [], int);

main()

{ int val[5]={3,5,2,7,4};

printf(“%d\n”,Maximum(val,5));

}

int maximum(int a[], int size) { int i, max = a[0];

for(i=0; i<size; i++) if(max<a[i])

max = a[i];

return(max);

}

(30)

Rules to pass an Array to a function

1. The function must be called by passing name of the array.

2. In the function definition, the formal parameter must be an array type; the size of the array does not need to be specified.

3. The function prototype must show that the argument is an array.

30

(31)

Two Dimensional Array as a function Argument

float fun_name(int [][], int , int) main()

{

……….

fun_name(A,M,N);

………..

float fun_name(int A[][N], int M, int N) {

statements;

return;

}

}

(32)

Passing Strings to functions

Function Definition:

void fun_name(char arr_name[]) {

statements;

}

Function prototype:

void fun_name(char arr_name[]);

Calling a function:

fun_name(arr_name);

32

(33)

Passing Strings to functions: Example

/* Function name: string_copy Purpose: String Copying

Input Arguments: Two Strings Return Value: Nothing

Modifies: Target String

Sample Call:string_copy(source, target); */

void string_copy(char source[],char target[]) { int i=0;

printf(“Source String : %s”,source);

for(i = 0; source[i]!=‘\0’; i++) target[i] = source[i];

target[i] = ‘\0’;

}

(34)

Calling string_copy(a,b)

int main()

{ char a[100], char b[100];

printf(“Input Source string:\n”);

scanf(“%s”,a);

string_copy(a,b); /* Function call */

printf(“\n Target String:\n %s”,b);

return 0;

}

34

(35)

Recursive functions

Definition

Examples

(36)

Definition (Mathematical)

Recursion is the process of defining something in terms of itself, and is sometimes called circular definition.

A recursive process is one in which objects are defined in terms of other objects of the same type. Using some sort of recurrence relation.

The entire class of objects can then be built up from a few initial values and a small number of rules.

Ex: Fibonacci Number series

36

(37)

Definition (Computer Science)

A recursive function is one which calls itself.

Recursive functions are useful in evaluating certain types of mathematical function.

When a function calls another function and that second

function calls the third function then this kind of a function is called nesting of functions.

But a recursive function is the function that calls itself

repeatedly.

(38)

Simple example

main() {

printf(“This is an example of recursive function”);

main();

}

When this program is executed. The line is printed repeatedly and indefinitely. We might have to abruptly terminate the execution.

38

(39)

Factorial Calculation

long int fact(int n) /* non-recursive */

{

int t, ans;

ans = 1;

for(t=1; t<=n; t++) ans = ans*t;

return(ans);

}

long int factr(int n) /* recursive */

{

int ans;

if(n==1) return(1);

ans = factr(n-1)*n; /* recursive call */

return(ans);

}

(40)

Recursive version of power function

double power(double val, unsigned pow) {

if(pow == 0) /*pow(x, 0) returns 1*/

return(1.0);

else

return(power(val, pow-1)*val);

}

40

(41)

How recursive functions works???

When a function calls itself, a new set of local variables and parameters are allocated storage on the stack, and the

function code is executed from the top with these new variables.

A recursive call does not make a new copy of the function.

Only the arguments are new.

As each recursive call returns, the old local variables and parameters are removed from the stack and execution

resumes at the point of the function call inside the function.

(42)

Summing up the elements of an array

Algorithm Design:

1. If we have only one element, then the sum is simple.

2. Otherwise, we use the sum of the first element and the sum of the rest.

int sum(int first,int last,int array[]) { if (first == last)

return (array[first]);

return(array[first]+sum(first+1,last,array));

}

42

(43)

Example

For example:

Sum(1 8 3 2) = 1 + Sum(8 3 2) = 8 + Sum(3 2) = 3 + Sum (2)=

2 3 + 2 = 5 8 + 5 = 13

1 + 13 = 14

Answer = 14

(44)

Recursive Version of Fibonacci Series

int fib(int num) /*Fibonacci value of a number */

{

switch(num)

{ case 0: return(0);

break;

case 1: return(1);

break;

default: /*Including recursive calls */

return(fib(num - 1) + fib(num - 2));

break;

} }

44

(45)

Analysis

(46)

Printing in reverse order

/* This function reads a line of text char by char and then displays the characters in reverse order */

void Reverse(void) { char c;

if((c = getchar())!= ‘\n’) Reverse();

putchar(c);

return;

}

How it will work???

46

(47)

Pros and cons!!!

No significant reduction in code size as well as no improvement in memory utilization.

Also, the recursive versions of most routines may

execute a bit slower than their iterative equivalents

because of the overhead of the repeated function

calls.

(48)

Pros and cons!!!

The main advantage to recursive functions is that you can use them to create clearer and simpler versions of several

algorithms.

48

(49)

Precaution!!!

When writing recursive functions, you must have an if

statement somewhere to force the function to return without the recursive call being executed.

If you don't, the function will never return once you call it.

(50)

Exercises:

Q.1 Write a function:

count(int number,int array,int Size) that counts the number of times number appears in array. The array has Size elements. The function should be recursive. Write a

test program to test it.

Q.2 Write a recursive function for each of the following 1. Y = x 1 + x 2 +………..+ x n

2. q = p 1 * p 2 * ………….*p n

50

References

Related documents

RESUMO - No presente trabalho, foi desenvolvido um estudo referente à variabilidade, correlação e te- petibilidade dos caracteres de tamanho de inflorescência, número de botões,

Pass by value: when an argument is passed to a function, its value is copied into the

knowing what terms are in the top position in Google, and being able to quantify their value through cold, hard data will go a long way in understanding the true value of those

The study is helpful for many players in Home Appliances to make following strategies related to advertising for any particular company: -..  Advertising

The committee read, noted, considered public comment, edited, and approved the recommendations and information as submitted by the working group. A discussion occurred regarding

In this section, you build and format a business intelligence request using Oracle BI Answers, and create and format a Narrative View.. The Narrative view lets you add text

A dose is given EVERY TIME you eat any carbs AND/OR have a high blood sugar that requires insulin.. Delivered just as if you were taking a shot of Humalog, Novolog

1.3.4 The series compensation provides a means of regulating power flowing through two parallel lines by introducing series capacitance in one of the lines,