chapter 6-functions

31
PRESENTED BY BIPLAV SARMA FACULTY(IT) Chapter 5 Functions in C

Upload: biplav-sarma

Post on 16-Apr-2017

92 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Chapter 6-Functions

PRESENTED BY BIPLAV SARMA

FACULTY(IT)

Chapter 5Functions in C

Page 2: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

2

OUTLINE

What is a Function Why Use Functions Passing Values between Functions

Scope Rule of Functions Calling Convention Advanced Features of Functions

Function Declaration and Prototypes Call by Value and Call by Reference Recursion Conclusions

Page 3: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

3

Top-Down Design

Involves repeatedly decomposing a problem into smaller problems

Eventually leads to a collection of small problems or tasks each of which can be easily coded

The function construct in C is used to write code for these small, simple problems.

Page 4: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

4

WHAT IS A FUNCTON?

A function is a self-contained block of statements that perform a coherent task of some kind.

Every C program can be thought of as a collection of these functions.

There is no limit on the number of functions that might be present in a C program.

If a program contains only one function, it must be main( )

Page 5: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

5

Contd…

Divide and conquer Construct a program from smaller pieces or

components These smaller pieces are called modules

Each piece more manageable than the original program

Page 6: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

6

Benefits of functions

Divide and conquer Manageable program development

Software reusability Use existing functions as building blocks for new

programs Abstraction - hide internal details (library functions)

Avoid code repetition

Page 7: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

7

Function definition format

return-value-type function-name( parameter-list ){ declarations and statements}

Function-name: any valid identifier Return-value-type: data type of the result (default int)

void – indicates that the function returns nothing Parameter-list: comma separated list, declares

parameters A type must be listed explicitly for each parameter

unless, the parameter is of type int

Page 8: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

8

Contd…

return-value-type function-name( parameter-list ){ declarations and statements}

Declarations and statements: function body (block) Variables can be declared inside blocks (can be nested) Functions can not be defined inside other functions

Returning control If nothing returned

return; or, until reaches right brace

If something returned return expression;

Page 9: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

9

Example-Passing values to a function

/* Sending and receiving values between functions */#include<stdio.h>int calsum(int,int,int);void main( ){int a, b, c, sum ;printf ( "\nEnter any three numbers " ) ;scanf ( "%d %d %d", &a, &b, &c ) ;sum = calsum ( a, b, c ) ;printf ( "\nSum = %d", sum ) ;}int calsum (int x,int y,int z ){return ( x + y + z ) ;}

Page 10: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

10

EXAMPLE 2

/* Find the hightest value among 3 numbers using functions */

#include<stdio.h>int maximum(int,int,int);void main( )

{int a, b, c, m ;printf ( "\nEnter any three numbers " ) ;scanf ( "%d %d %d", &a, &b, &c ) ;m = maximum( a, b, c ) ;printf ( "\nMaximum Value = %d", m ) ;}

Page 11: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

11

Contd…

int maximum (int x,int y,int z ){int max=x;if(y>max)max=y;if(z>max)max=z;

return max;

}

Page 12: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

12

Function Prototypes

Function prototype Function name Parameters – what the function takes in Return type – data type function returns (default int) Used to validate functions Prototype only needed if function definition comes after use

in program The function with the prototype

int maximum( int, int, int ); Takes in 3 ints Returns an int

Promotion rules and conversions Converting to lower types can lead to errors

Page 13: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

13

Header Files

Header files Contain function prototypes for library functions <stdlib.h> , <math.h> , etc Load with #include <filename>

#include <math.h>Custom header files

Create file with functions Save as filename.h Load in other files with #include "filename.h" Reuse functions

Page 14: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

14

Calling Functions: Call by Value and Call by Reference

Used when invoking functionsCall by value

Copy of argument passed to function Changes in function do not effect original Use when function does not need to modify argument

Avoids accidental changesCall by reference

Passes original argument Changes in function effect original Only used with trusted functions

Page 15: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

15

Call by Value#include<stdio.h>/* CALL BY VALUE using functions */void main( ) {int a;void change(int);printf ( "\nEnter the number " ) ;scanf ( "%d", &a) ;printf ( "\nYou entered = %d",a ) ;change(a);printf ( "\nValue after change() %d",a ) ;}void change(int a){a=40;printf ( "\nValue of a in change()%d",a ) ;return;}

Page 16: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

16

Call by Value

Page 17: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

17

Call by Reference #include<stdio.h>void interchange(int *num1,int *num2){

int temp; temp = *num1; *num1 = *num2; *num2 = temp; printf("\\n During Call of Interchange:”);

printf("\nNumber 1 : %d",num1); printf("\nNumber 2 : %d",num2);

}int main() {

int num1=50,num2=70; printf("\nNumber 1 : %d",num1); printf("\nNumber 2 : %d",num2); interchange(&num1,&num2); printf("\nNumber 1 : %d",num1); printf("\nNumber 2 : %d",num2);

return(0);}

Page 18: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

18

Call by Reference

Page 19: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

19

Basic Difference

Call by Value Call by Reference

Duplicate Copy of Original Parameter is Passed

Actual Copy of Original Parameter is Passed

No effect on Original Parameter after modifying parameter in function

Original Parameter gets affected if value of parameter changed inside function

Page 20: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

20

Header Files

In order to call upon functions compiled in separate files, you need to include their definition as a declaration or a prototype for simplicity, if you have functions in several files, each

of which call upon some of the same functions, you can place the prototypes in a single file, called a header file all other shared definitions and declarations can go here as well

Page 21: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

21

Contd…

A header files typically only contain definitions and declarations, not executable code consider as an example a calculator program that has its’

functions split into multiple files: a main function in one file which calls upon stack operations in a file stack.c a parsing operation to get tokens from a string in the file getop.c a function to get char input in the file getch.c a header file contains prototypes and common declarations called

calc.h

Page 22: Chapter 6-Functions

05/03/2023

22

Commonly Used Header Files

Editted by Biplav Sarma

Header File Contains Function Prototypes for:<stdio.h> standard input/output library functions

and information used by them<math.h> math library functions<stdlib.h> conversion of numbers to text, text to

numbers, memory allocation, random numbers, and other utility functions

<time.h> manipulating the time and date<ctype.h> functions that test characters for certain

properties and that can convert case<string.h> functions that manipulate character strings

Page 23: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

23

Example: Finding hypotenuse of a Triangle

#include <stdio.h>#include <stdlib.h>#include <math.h>int main ( ){ float side1, side2, hypotenuse ; printf(“Enter the lengths of the right triangle sides: “) ; scanf(“%f%f”, &side1, &side2) ; if ( (side1 <= 0) || (side2 <= 0) { exit (1) ; } hypotenuse = sqrt ( (side1 * side1) + (side2 * side2) ) ; printf(“The hypotenuse = %f\n”, hypotenuse) ; return 0 ;}

Page 24: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

24

Recursion

In C, it is possible for the functions to call themselves. A function is called ‘recursive’ if a statement within the body of a function calls the same function.

Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.

Page 25: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

25

Example: Finding factorial of a number

#include<stdio.h>rec(int);void main( ){int a, fact ;printf ( "\nEnter any number " ) ;scanf ( "%d", &a ) ;fact = rec ( a ) ;printf ( "Factorial value = %d", fact ) ;}

Page 26: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

26

Contd…

int rec ( int x ){int f ;if ( x == 1 )return ( 1 ) ;elsef = x * rec ( x - 1 ) ;return ( f ) ;}

Page 27: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

27

Displaying Fibonacci series

#include <stdio.h> int fibonaci(int i) { if(i == 0) { return 0; } if(i == 1)

{ return 1;

} return fibonaci(i-1) + fibonaci(i-2); }

Page 28: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

28

Contd…

int main() { int i; for (i = 0; i < 10; i++) {

printf("%d\t%n", fibonaci(i)); } return 0; }

Page 29: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

29

Summary

To avoid repetition of code and bulky programs functionally related statements are isolated into a function.

Function declaration specifies what is the return type of the function and the types of parameters it accepts.

Function definition defines the body of the function. Variables declared in a function are not available to

other functions in a program. So, there won’t be any clash even if we give same name to the variables declared in different functions.

Page 30: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

30

Contd…

Pointers are variables which hold addresses of other variables.

A function can be called either by value or by reference.

Pointers can be used to make a function return more than one value simultaneously.

Recursion is difficult to understand, but in some cases offer a better solution than loops.

Adding too many functions and calling them frequently may slow down the program execution.

Page 31: Chapter 6-Functions

05/03/2023Editted by Biplav Sarma

31

THANKS