FUNCTIONS. C function can be classified into two categories, namely, library functions and user – defined functions. main is an example of user – defined.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Spring Semester 2013 Lecture 5
Modular Programming With Functions
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7: User-Defined Functions II
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
Functions Lecture 4 – Section 2: 9/21/05 Section 4: 9/22/05.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
UNIT III. Functions  To divide a big program into a number of relatively smaller and easily manageable subprograms. Each subprogram in C is called a.
PASSING VALUE TO A FUNCTION # CALL BY VALUECALL BY VALUE # CALL BY REFERENCECALL BY REFERENCE STORAGE CLASS # AUTOAUTO # EXTERNALEXTERNAL # STATICSTATIC.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
FUNCTIONS AND STRUCTURED PROGRAMMING CHAPTER 10. Introduction A c program is composed of at least one function definition, that is the main() function.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
Chapter 5 - Functions Outline 5.1Introduction 5.2Program Modules in C 5.3Math Library Functions 5.4Functions 5.5Function Definitions 5.6Function Prototypes.
C++ Lecture 2 Friday 11 July Chapter 3, Functions l built-in functions l function prototype, function definition and use l storage class and scope.
UNIT - 4 FUNCTIONS AND POINTERS. FUNCTION Functions is a sub-program that contains one or more statements and it performs some task when called.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
User defined functions
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Chapter 6: Function Introduction to function Standard functions User defined functions –function prototype –function definition Function call Storage classes.
C++ Programming Lecture 12 Functions – Part IV
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
A First Book of ANSI C Fourth Edition
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C Part 2 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens The Three Attributes of an Identifier Identifiers have three essential.
Functions Course conducted by: Md.Raihan ul Masood
User-Written Functions
FUNCTION Functions is a sub-program that contains one or more statements and it performs some task when called.
IS Program Design and Software Tools Introduction to C++ Programming
C++.
Quiz 2.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 5 - Functions Outline 5.1 Introduction
Functions.
User-Defined Functions
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 6 - Functions Outline 5.1 Introduction
Functions: Declaration, Definition, Call and return, Scope of variables, Storage classes, Recursive functions, Recursion vs Iteration.
6 Chapter Functions.
Dr Tripty Singh Tutorial for Fuctions
Function.
In C Programming Language
In C Programming Language
1-6 Midterm Review.
STORAGE CLASS.
Function.
Presentation transcript:

FUNCTIONS

C function can be classified into two categories, namely, library functions and user – defined functions. main is an example of user – defined functions. printf and scanf belong to the category of library functions. We have also used other library functions such as sqrt, cos, strcat, etc. The main distinction between these two categories is that library functions are not required to be written by us whereas a user – defined function has to be developed by the user at the time of writing a program. Introduction

Function COND… FUNCTION DECLARATION FUNCTION DEFINITION FUNCTION CALL

Function #include int mod(int, int); /* Function Prototype */ void main() { printf("The mod is: %d ", mod(4,5));/* Function calling */ } int mod(int x, int y) /* Function Definition */ { return x % y; }

FUNCTION DEFINITION SYNTAX A function definition, also known as function implementation shall include the following elements. 1. Function Name 2. Function Type 3. List of Parameters 4. Local variable declarations 5. Function Statements 6. A Return statement All the six elements are grouped into two parts, namely, 1. Function header (First three Elements) 2. Function Body (Second three Elements) function_type function_name(parameter_list) { local variable declaration; executable statement_1; executable statement_2; return statement; } Example: float mul ( float x, float y) { float result; result = x * y; return (result); }

FUNCTION PROTYPING OR FUNCTION DECLARATION A function prototype is a very important feature of modern C programming It must be added to a C program just before the main function, if we call that function before defining it It tells the compiler what type of value the function returns, numbers and types of parameters, and order in which these parameters are expected. There is no need for a prototype if the function is called after its definition

FUNCTION DECLARATION SYNTAX Like variables, all functions in a C program must be declared, before they are invoked, A function declaration (also known as function prototype) consists of four parts. 1. Function type (return type) 2. Function name 3. Parameter list 4. Terminating semicolon The general format is Function_type function_name(parameter_list); Example: float mul (float x, float y);

Function Definition A simple format of a C function definition is as follows: return-value-type function- name(parameters) { Declarations; Statements; Return (expression); } Function Prototype

WORKING PRINCIPLES

Formal and Actual Parameters In C, there are two types of parameters Formal parameters appear in the prototype and definition, and are representative of the data types the function expects to receive Actual parameters appear only in a function call and are the actual data passed

Example #include void MyFun( int ); Formal Parameter int main( void ) { int x=3; printf( “x has a value of %d”, x); MyFun( x );Actual Parameter printf( “x has a value of %d”, x); return 0;Parameter Passing } void MyFun( int x ) Formal Parameter { printf( “x has a value of %d”, x); x = 77; printf( “x has a value of %d”, x); }

CATEGORIES OF FUNCTIONS Category 1 : Functions with no arguments and no return values. Category 2 : Functions with arguments and no return values. Category 3 : Functions with arguments and one return value. Category 4 : Functions with no arguments but return a value. Category 5 : Functions with default arguments.

Function with No return type and No arguments Void func1(); void main() { ……. func1(); ……. } void func1() { ……. }

#include void add(); void main() { add(); } void add() { int a,b,c; printf(“enter any two numbers”) scanf(“%d%d”,&a,&b); c= a+b; printf(“the addition of %d and %d is %d”,a,b,c); }

Function with No return type and with arguments void func1(int,int); void main() { ……. func1(x,y); ……. } void func1 (int a,int b) { ……. }

#include void add(int,int); void main() { int x,y,c; printf(“enter any two numbers”) scanf(“%d%d”,&x,&y); add(x,y); } void add(int a,int b) { int c; c= a+b; printf(“the addition of %d and %d is %d”,a,b,c); }

Function with return type and with arguments int func1(int,int); void main() { ……. a=func1(x,y); ……. } int func1(int a,int b) { ……. }

#include int add(int,int); Void main() { int x,y,c; printf(“enter any two numbers”) scanf(“%d%d”,&x,&y); c = add(x,y); printf(“The Result = %d ”,c); } int add(int a,int b) { int c; c= a+b; return (c); }

Function with return type and No arguments int func1(); void main() { ……. a=func1(); ……. } int func1() { ……. }

#include int add(); Void main() { int c; c = add(); printf(“The Result = %d ”,c); } int add() { int a,b,c; printf(“enter any two numbers”) scanf(“%d%d”,&a,&b); c= a+b; return (c); }

Function without a prototype #include int sum(int x, int y) { return x+y; } void main() { printf("The sum is: %d ", sum(4,5)); }

Storage class Every variable or constant possesses a data type In addition to the data type, a variable possesses an attribute called storage class. where v1,v2 are the variables data_type is the valid data type in c language storage_class gives information regarding lifetime and scope. Storage_class data_type v1,v2,v3,………………..vn.

Storage class cont’ Lifetime Lifetime or Longetivity of a variable refers to the duration for which the variable retains a given value during the execution of a program. Scope It is the portion of the program in which the variable may be visible or available.It can classified into two types Type 1: Local variable (or) private variable (or) internal variable. Type 2: Global variable (or) public variable (or) external variable.

Types Sl.NoTypes of Storage ClassReserved words 1Automaticauto 2Registerregister 3Staticstatic 4Externalextern

Automatic variables By default all variables are automatic storage class. Their memory space is automatically allocated as the variable is declared. These variables are given only temporary memory space and after the execution all the automatic variables will get disposed. It can not be accessed directly by other functions.

#include void fun(int); void main() { int i; a=10; fun(a); } void fun(int a) { prinf("%d",a); } #include void fun(); void main() { int i; a=10; fun(); } void fun() { prinf("%d",a); //error }

Sample Program #include Void main() { float f1 = 10.2; { float f1 = 40.00; { float f1 = 33.9; printf(“the value of f1 in block 3 is %f”,f1); } printf(“the value of f1 in block 2 is %f”,f1); } printf(“the value of f1 in block 1 is %f”,f1); }

External variables It refers to the location outside a block i.e., prior to the main() or beyond the closing braces ( } ) of the outermost block in a program. The value is available throughout the program because of its global scope. Whenever an external variable is modified in a block, the effect is propagated to all places where ever it is used.

#include int a; void fun(); void main() { int i; a=10; fun(); } void fun() { prinf("%d",a); }

Static Variables The variables are declared with static keyword. It can be internal static (or) external static based on the place of its declaration. Both are declared using the keyword static. The storage used by an static variable in a block is not lost after the completion of the execution. Even after the termination of the block, the value of the static variable is available. If the value is changed during the execution the recent value is retained. When the execution enters the next time the same block, the initialiser is neglected and the recently stored value is retained.

#include static int count; void main() { int i,x; printf("\ncount is %d",count); getch(); } #include static int count; void func(); void main() { int i,x; printf("\n%d",count); count++; func(); printf("\n%d",count); getch(); } void func() { printf("\n%d",count); }

Sample Program #include int fun(int); void main() { int i,x; for(i=1;i<=10;i++) { x = fun(i); printf(“The I value is %d”,x); } int fun(int a) { auto int sum = 100; sum = sum + a; return(sum); } #include int fun(int); void main() { int i,x; for(i=1;i<=10;i++) { x = fun(i); printf(“The I value is %d”,x); } int fun(int a) { static int sum = 100; sum = sum + a; return(sum); }

Output When sum is auto The I Value is:101 The I Value is:102 The I Value is:103 The I Value is:104 The I Value is:105 The I Value is:106 The I Value is:107 The I Value is:108 The I Value is:109 The I Value is:110 When sum is static The I Value is:101 The I Value is:103 The I Value is:106 The I Value is:110 The I Value is:115 The I Value is:121 The I Value is:128 The I Value is:136 The I Value is:145 The I Value is:155

Register Variables The variables are declared using register keyword. The scope and lifetime is same as that of automatic variables. For any given operation the data available in the memory should be transferred to the CPU registers. So if the data are stored in register itself then the time for data transfer from the memory to the register is saved. Only a few values can be placed at a time and hence it is advisable to use limited register variables. main() { register int i; for(i=0;i<10;i++) printf(“%d”,i); }

Parameter Passing Methods In C there are two ways of passing parameters to a function Call by Value Call by Reference

Call by value  Copy of data passed to function  Changes to copy do not change original  Prevent unwanted side effects This Method copies the value of actual parameters(calling program) into the formal parameters(called program) of the functions. Here the changes of the formal parameters cannot affect the actual parameters. Because only the copy of actual arguments were passed. A function can return only one value per call.

Example #include int cube (int) void main() { int n=5; printf(“Cube of %d is %d”,n,cube(n)); } int cube (int x); { x=x*x*x; return x; } O/p: Cube of 5 is 125

Call by reference  Function can directly access data  Changes affect original It is another way of passing parameter to the functions here the address of arguments are copied into the parameters inside the functions. The address is used to access the actual arguments used in the call. By using this we can make a function to return more the one value(indirectly).

Example #include void interchange (int *a, int *b) void main() { int i=5,j=10; printf(“Before : I and J value is %d and %d”,I,j); interchange(&i,&j); printf(“After : I and J value is %d and %d”,I,j); } void interchange (int *a, int *b) { int t; t=*a *a=*b *b=t } O/p: Before : I and J value is 5 and 10 After : I and J value is 10 and 5

Call by value Vs Call by reference Call by value  Copy of data passed to function  Changes to copy do not change original  Prevent unwanted side effects Call by reference  Function can directly access data  Changes affect original

#include void swap(int, int); void main() { int num1, num2; num1 = 10; num2 = 20; swap ( num1, num2 ); printf("%d %d\n", num1, num2); } void swap(int val1, int val2) { int temp; temp = val1; val1 = val2; val1 = temp; }

Swap two integers using call by value(cont.) In the above example, we passed parameters by value, a copy is made of the variable and thus any change made to the parameters val1 and val2 will not be passed back to the main function The main function will not know anything about the swapping of val1 and val2 Therefore, the output of the above program will be ….? Normally if we wished to pass back a value we would use return or we would pass the parameters by reference

Nested Functions In C, it provides a facility to write one function with in another function. This is called nesting of functions Main() { func1(); } func1() { func2(); } func2() { }

Recursion

Recursion is a process of calling the same function itself again and again until same condition is satisfied. This is used for repetitive computation in which each action is satisfied in terms of a previous result A function can call itself –Directly –Indirectly Function1() { Function1(); }

Recursion vs. Iteration Repetition –Iteration: explicit loop –Recursion: repeated function calls Termination –Iteration: loop condition fails –Recursion: base case recognized Both can have infinite loops Balance between performance (iteration) and good software engineering (recursion)

Sl.No.IterationRecursion 1. Iteration explicitly user a repetition structure. Recursion achieves repetition throught repeated function calls. 2. Iteration terminates when the loop continuation condition fails. Recursion terminates when a base case is reached. 3. Iteration keeps modifying the counter until the loop continuation condition fails. Recursion keeps producing simple versions of the original problem until the base case is reached. 4. An infinite loop occurs when the loop step continuation test never becomes false. An infinite loop occurs if the recursion doses not reduce the problem each time in a manner that converges the base case. 5. Iteration normally occurs within a loop so extra memory assignment is omitted. Recursion causes another copy of the function & hence a considerable memory space is occupied. 6. It reduces the processor operating time. It increases the processor operating time. Difference Between Iteration and Recursion

Example: fibonacci.c function Fibonacci ( n ) { if ( n is less than or equal to 1 ) then return n else return Fibonacci ( n - 2 ) + Fibonacci ( n - 1 ) } /* Compute the n-th Fibonacci number, when=0,1,2,... */ long fib ( int n ) { if ( n <= 1 ) return n ; else return fib( n - 2 ) + fib( n - 1 ); }

int main(void) { int number; printf("Enter number: "); scanf("%d", &number); printf("Fibonacci(%d) = %ld\n", number, fib(number)); return 0; } Example: fibonacci.c Sample main() for testing the fib() function:

Scope Where can you use a variable which is declared in a function? In that function only Not in a calling function Not in a called function

Scope: Local Variables Formal parameters: only accessible whilst a function is executing Variables declared in a function body: only accessible whilst the function is executing In fact, this is true of every block in a program

C Standard Library Every implementation of C comes with a standard library of predefined functions. Note that, in programming, a library is a collection of functions. The functions that are common to all versions of C are known as the C Standard Library.

C Standard Library Function Examples Function Name Math Name ValueExample abs(x) absolute value |x||x| abs(-1) returns1 sqrt(x) square rootx 0.5 sqrt(2.0) returns1.414 … exp(x) exponentialexex exp(1.0) returns2.718 … log(x) natural logarithm ln x log(2.718…) returns1.0 sin(x) sinesin x sin(3.14…) returns0.0 cos(x) cosinecos x cos(3.14…) returns tan(x) tangenttan x tan(3.14…) returns0.0 ceil(x) ceiling ┌ x ┐ ceil(2.5) returns3.0 floor(x) floor └ x ┘└ x ┘ floor(2.5) returns2.0