Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Similar documents
Functions. Prof. Indranil Sen Gupta. Dept. of Computer Science & Engg. Indian Institute t of Technology Kharagpur. Introduction

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

Function. specific, well-defined task. whenever it is called or invoked. A function to add two numbers A function to find the largest of n numbers

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

C Functions. 5.2 Program Modules in C

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Functions. Systems Programming Concepts

INTRODUCTION TO C++ FUNCTIONS. Dept. of Electronic Engineering, NCHU. Original slides are from

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

ECET 264 C Programming Language with Applications

C Programs: Simple Statements and Expressions

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

CSE123. Program Design and Modular Programming Functions 1-1

Lecture 04 FUNCTIONS AND ARRAYS

6-1 (Function). (Function) !*+!"#!, Function Description Example. natural logarithm of x (base e) rounds x to smallest integer not less than x

Lecture 2:- Functions. Introduction

Function Call Stack and Activation Records

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Unit 7. Functions. Need of User Defined Functions

Chapter 3 - Functions

Tutorial 5. PDS Lab Section 16 Autumn Functions The C language is termed as function-oriented programming

Calling Prewritten Functions in C

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Lecture 04 FUNCTIONS AND ARRAYS

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

CS110: PROGRAMMING LANGUAGE I

Chapter 5 C Functions

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

15 FUNCTIONS IN C 15.1 INTRODUCTION

Programming and Data Structure

Programming for Engineers Functions

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Preview from Notesale.co.uk Page 2 of 79

Expressions and operators

Lesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University

C++ Programming Lecture 11 Functions Part I

Programming in C Quick Start! Biostatistics 615 Lecture 4

Functions and Recursion

COP3502 Programming Fundamentals for CIS Majors 1. Instructor: Parisa Rashidi

Functions and Recursion

Computer Science & Engineering 150A Problem Solving Using Computers

To define methods, invoke methods, and pass arguments to a method ( ). To develop reusable code that is modular, easy-toread, easy-to-debug,

Function Example. Function Definition. C Programming. Syntax. A small program(subroutine) that performs a particular task. Modular programming design

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 3. Existing Information. Notes. Notes. Notes. Lecture 03 - Functions

Chapter 5 Methods. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

DUBLIN CITY UNIVERSITY

Chapter 5 Methods / Functions

Programming Fundamentals for Engineers Functions. Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. Modular programming.

C++, How to Program. Spring 2016 CISC1600 Yanjun Li 1

C++ PROGRAMMING SKILLS Part 3 User-Defined Functions

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

Introduction to Programming

C Functions Pearson Education, Inc. All rights reserved.

Chapter 3. Computer Science & Engineering 155E Computer Science I: Systems Engineering Focus. Existing Information.

Technical Questions. Q 1) What are the key features in C programming language?

EL6483: Brief Overview of C Programming Language

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

CS101 Introduction to computing Function, Scope Rules and Storage class

Introduction to Computers II Lecture 4. Dr Ali Ziya Alkar Dr Mehmet Demirer

DUBLIN CITY UNIVERSITY

(2-2) Functions I H&K Chapter 3. Instructor - Andrew S. O Fallon CptS 121 (January 18, 2019) Washington State University

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

Chapter 3 - Functions

Fundamentals of Programming Session 12

CSE 230 Intermediate Programming in C and C++ Functions

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

Benefits of Methods. Chapter 5 Methods

Dept. of CSE, IIT KGP

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

Chapter 4 Functions By C.K. Liang

C Programming for Engineers Functions

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Chapter 5 Methods. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

static int min(int a, int b) Returns the smaller of two int values. static double pow(double a,

12. Numbers. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Subject: Fundamental of Computer Programming 2068

Functions. (transfer of parameters, returned values, recursion, function pointers).

OBJECTIVE QUESTIONS: Choose the correct alternative:

Introduction to C Language

Lecture 5. Functions II. Functions with Arguments. CptS 121 Summer 2016 Armen Abnousi

Chapter 6 Methods. Dr. Hikmat Jaber

Lecture 2: C Programming Basic

Lecture 9 - C Functions

Functions in C C Programming and Software Tools

Lecture 14. Daily Puzzle. Math in C. Rearrange the letters of eleven plus two to make this mathematical statement true. Eleven plus two =?

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

9 C Language Function Block

ANSI C Programming Simple Programs


PASS$MOCK$EXAM$ $FOR$PRACTICE$ONLY$

Lab Instructor : Jean Lai

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Using Free Functions

Computer Programming

Chapter 5 Methods. Modifier returnvaluetype methodname(list of parameters) { // method body; }

Transcription:

1 Functions Functions are everywhere in C Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Introduction Function A self-contained program segment that carries out some specific, well-defined task. Some properties: Every C program consists of one or more functions. One of these functions must be called main. Execution of the program always begins by carrying out the instructions in main. A function will carry out its intended action whenever it is called or invoked.

In general, a function will process information that is passed to it from the calling portion of the program, and returns a single value. Information is passed to the function via special identifiers called arguments or parameters. The value is returned by the return statement. Some functions may not return anything. Return data type specified as void.

#include <stdio.h> int factorial (int m) int i, temp=1; for (i=1; i<=m; i++) temp = temp * i; return (temp); main() int n; for (n=1; n<=10; n++) printf ( %d! = %d \n, n, factorial (n) ); Output: 1! = 1 2! = 2 3! = 6.. upto 10!

Why Functions? Functions Allows one to develop a program in a modular fashion. Divide-and-conquer approach. All variables declared inside functions are local variables. Known only in function defined. There are exceptions (to be discussed later). Parameters Communicate information between functions. They also become local variables. 5

Use of functions: Area of a circle #include <stdio.h> #define PI 3.1415926 /* Function to compute the area of a circle */ float myfunc (float r) float a; a = PI * r * r; return (a); /* return result */ main() float radius, area; float myfunc (float radius); scanf ( %f, &radius); area = myfunc (radius); printf ( \n Area is %f \n, area); Macro definition Function call Function definition Function argument Function declaration (return value defines the type)

Defining a Function A function definition has two parts: The first line. The body of the function. return-value-type function-name ( parameter-list ) declarations and statements 7

The first line contains the return-value-type, the function name, and optionally a set of comma-separated arguments enclosed in parentheses. Each argument has an associated type declaration. The arguments are called formal arguments or formal parameters. Example: int gcd (int A, int B) The argument data types can also be declared on the next line: int gcd (A, B) int A, B; ----- 8

The body of the function is actually a compound statement that defines the action to be taken by the function. int gcd (int A, int B) int temp; while ((B % A)!= 0) temp = B % A; B = A; A = temp; return (A); BODY 9

When a function is called from some other function, the corresponding arguments in the function call are called actual arguments or actual parameters. The formal and actual arguments must match in their data types. The notion of positional parameters is important Point to note: The identifiers used as formal arguments are local. Not recognized outside the function. Names of formal and actual arguments may differ. 10

#include <stdio.h> /* Compute the GCD of four numbers */ main() int n1, n2, n3, n4, result; scanf ( %d %d %d %d, &n1, &n2, &n3, &n4); result = gcd ( gcd (n1, n2), gcd (n3, n4) ); int gcd (int A, int B) int temp; while ((B % A)!= 0) temp = B % A; B = A; A = temp; return (A); printf ( The GCD of %d, %d, %d and %d is %d \n, n1, n2, n3, n4, result); 11

Some Points A function cannot be defined within another function. All function definitions must be disjoint. Nested function calls are allowed. A calls B, B calls C, C calls D, etc. The function called last will be the first to return. A function can also call itself, either directly or in a cycle. A calls B, B calls C, C calls back A. Called recursive call or recursion. 12

Example:: main calls ncr, ncr calls fact #include <stdio.h> int ncr (int n, int r); int fact (int n); main() int i, m, n, sum=0; scanf ( %d %d, &m, &n); for (i=1; i<=m; i+=2) sum = sum + ncr (n, i); printf ( Result: %d \n, sum); int ncr (int n, int r) return (fact(n) / fact(r) / fact(n-r)); int fact (int n) int i, temp=1; for (i=1; i<=n; i++) temp *= i; return (temp); 13

14 #include <stdio.h> int A; void main() A = 1; myproc(); printf ( "A = %d\n", A); Scope of Variables void myproc() int A = 2; while( A==2 ) printf ( "A = %d\n", A); break; printf ( "A = %d\n", A); Output: A = 2 A = 1

Math Library Functions Math library functions perform common mathematical calculations #include <math.h> Format for calling functions FunctionName (argument); If multiple arguments, use comma-separated list printf ("%f", sqrt(900.0)); Calls function sqrt, which returns the square root of its argument. All math functions return data type double. Arguments may be constants, variables, or expressions. 15

Math Library Functions double acos(double x) Compute arc cosine of x. double asin(double x) Compute arc sine of x. double atan(double x) Compute arc tangent of x. double atan2(double y, double x) Compute arc tangent of y/x. double cos(double x) Compute cosine of angle in radians. double cosh(double x) Compute the hyperbolic cosine of x. double sin(double x) Compute sine of angle in radians. double sinh(double x) Compute the hyperbolic sine of x. double tan(double x) Compute tangent of angle in radians. double tanh(double x) Compute the hyperbolic tangent of x. 16

Math Library Functions double ceil(double x) Get smallest integral value that exceeds x. double floor(double x) Get largest integral value less than x. double exp(double x) Compute exponential of x. double fabs (double x ) Compute absolute value of x. double log(double x) Compute log to the base e of x. double log10 (double x ) Compute log to the base 10 of x. double pow (double x, double y) Compute x raised to the power y. double sqrt(double x) Compute the square root of x. 17

Function Prototypes Usually, a function is defined before it is called. main() is the last function in the program. Easy for the compiler to identify function definitions in a single scan through the file. However, many programmers prefer a top-down approach, where the functions follow main(). Must be some way to tell the compiler. Function prototypes are used for this purpose. Only needed if function definition comes after use. 18

Function prototypes are usually written at the beginning of a program, ahead of any functions (including main()). Examples: int gcd (int A, int B); void div7 (int number); Note the semicolon at the end of the line. The argument names can be different; but it is a good practice to use the same names as in the function definition. 19

Header Files Header files Contain function prototypes for library functions. <stdlib.h>, <math.h>, etc Load with: #include <filename> Example: #include <math.h> Custom header files Create file(s) with function definitions. Save as filename.h (say). Load in other files with Reuse functions. #include "filename.h" 20

Parameter passing: by Value and by Reference Used when invoking functions. Call by value Passes the value of the argument to the function. Execution of the function does not affect the original. Used when function does not need to modify argument. Avoids accidental changes. Call by reference Passes the reference to the original argument. Execution of the function may affect the original. Not directly supported in C can be effected by using pointers C supports only call by value 21

Example: Random Number Generation rand function Prototype defined in <stdlib.h> Returns "random" number between 0 and RAND_MAX i = rand(); Pseudorandom Preset sequence of "random" numbers Scaling Same sequence for every function call To get a random number between 1 and n 1 + (rand() % n ) To simulate the roll of a dice: 1 + (rand() % 6) 22

Random Number Generation: Contd. srand function Prototype defined in <stdlib.h>. Takes an integer seed, and randomizes the random number generator. srand (seed); 23

#define: Macro definition Preprocessor directive in the following form: #define string1 string2 Replaces string1 by string2 wherever it occurs before compilation. For example, #define PI 3.1415926 24

#define: Macro definition #include <stdio.h> #define PI 3.1415926 main() float r = 4.0, area; area = PI * r * r; #include <stdio.h> main() float r = 4.0, area; area = 3.1415926 * r * r; 25

#define with arguments #define statement may be used with arguments. Example: #define sqr(x) x*x How will macro substitution be carried out? r = sqr(a) + sqr(30); r = a*a + 30*30; r = sqr(a+b); r = a+b*a+b; The macro definition should have been written as: WRONG? #define sqr(x) (x)*(x) r = sqr(a+b); r = (a+b)(a+b); 26

How are function calls implemented? The following applies in general, with minor variations that are implementation dependent. The system maintains a stack in memory. Stack is a last-in first-out structure. Two operations on stack, push and pop. Whenever there is a function call, the activation record gets pushed into the stack. Activation record consists of the return address in the calling program, the return value from the function, and the local variables inside the function. 27

STACK main().. x = gcd (a, b);.. Activation record Local Variables Return Value Return Addr int gcd (int x, int y).... return (result); Before call After call After return 28

main().. x = ncr (a, b);.. int ncr (int n, int r) return ( fact(n) / ( fact(r) * fact(n-r) )); int fact (int n) return (result); LV2, RV2, RA2 LV1, RV1, RA1 LV1, RV1, RA1 LV1, RV1, RA1 Before call Call ncr Call fact fact returns ncr returns

Storage Class of Variables 30

What is Storage Class? It refers to the permanence of a variable, and its scope within a program. Four storage class specifications in C: Automatic: auto External : extern Static : static Register : register 31

Automatic Variables These are always declared within a function and are local to the function in which they are declared. Scope is confined to that function. This is the default storage class specification. All variables are considered as auto unless explicitly specified otherwise. The keyword auto is optional. An automatic variable does not retain its value once control is transferred out of its defining function. 32

#include <stdio.h> int factorial( int m ) auto int i; auto int temp=1; for ( i=1; i<=m; i++ ) temp = temp * i; return ( temp ); main() auto int n; for (n=1; n<=10; n++) printf ( %d! = %d \n, n, factorial (n) ); 33

Static Variables Static variables are defined within individual functions and have the same scope as automatic variables. Unlike automatic variables, static variables retain their values throughout the life of the program. If a function is exited and re-entered at a later time, the static variables defined within that function will retain their previous values. Initial values can be included in the static variable declaration. Will be initialized only once. 34

Static Variables void test( int x ) static int count = 0; Initialization will happen only the first time the function is called main( ) if ( x == 0 ) scanf( %d, &marks) ; if ( count == 2 ) test( marks ); printf ( Three consecutive zeros ); else count++; else count = 0; return; Function that detects three consecutive zeros in a stream of 100 marks. int k, marks; for ( k=0; k < 100; k++ ) 35

Register Variables These variables are stored in high-speed registers within the CPU. Commonly used variables may be declared as register variables. Results in increase in execution speed. The allocation is done by the compiler. For example: register float y; // Instructs the compiler to allocate some register to y 36

External Variables They are not confined to single files. Their scope extends from the point of definition through the remainder of the program. They may span more than one file. They too are global variables. 37

38 External Variables FILE a.c extern int k; void f ( void ) k++; Informs the compiler that k is an integer variable but space is not to be allocated for it. FILE b.c int k=0; extern void f ( void ); void g ( void ) f( ); printf( %d\n, k );