Functions BCA-105. Few Facts About Functions:

Similar documents
Unit 7. Functions. Need of User Defined Functions

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

UNIT 3 FUNCTIONS AND ARRAYS

Function Call Stack and Activation Records

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

15 FUNCTIONS IN C 15.1 INTRODUCTION

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.

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

CSE 230 Intermediate Programming in C and C++ Functions

CS356: Discussion #6 Assembly Procedures and Arrays. Marco Paolieri

CS1150 Principles of Computer Science Methods

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.

CS113: Lecture 4. Topics: Functions. Function Activation Records

Chapter 7 Functions. Now consider a more advanced example:

BSM540 Basics of C Language

Pointers, Arrays and Parameters

M.CS201 Programming language

Advanced C Programming and Introduction to Data Structures

CSE101-lec#12. Designing Structured Programs Introduction to Functions. Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

Programming for Engineers Introduction to C

Functions. Systems Programming Concepts

5 Functions & Pointers

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

C Programming for Engineers Functions

Computer Systems Lecture 9

MODULE 5: Pointers, Preprocessor Directives and Data Structures

Lecture 04 FUNCTIONS AND ARRAYS

Software Development & Education Center C Programming

CS1150 Principles of Computer Science Methods

Programming Studio #9 ECE 190

Fundamentals of Programming & Procedural Programming

Functions. Using Bloodshed Dev-C++ Heejin Park. Hanyang University

Lecture 3: C Programm

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

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

1 P a g e A r y a n C o l l e g e \ B S c _ I T \ C \

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

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

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

Lab 3. Pointers Programming Lab (Using C) XU Silei

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Functions. Lecture 6 COP 3014 Spring February 11, 2018

Lecture 9 - C Functions

Lecture 04 FUNCTIONS AND ARRAYS

Flow Control. CSC215 Lecture

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

A PROBLEM can be solved easily if it is decomposed into parts. Similarly a C program decomposes a program into its component functions.

AMCAT Automata Coding Sample Questions And Answers

Code No: R Set No. 1

A Fast Review of C Essentials Part I

C++ For Science and Engineering Lecture 15

Understand Execution of a Program

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

CS-201 Introduction to Programming with Java

MODULE 3: Arrays, Functions and Strings

COMPUTER SCIENCE HIGHER SECONDARY FIRST YEAR. VOLUME II - CHAPTER 10 PROBLEM SOLVING TECHNIQUES AND C PROGRAMMING 1,2,3 & 5 MARKS

Fundamentals of Programming. Lecture 3: Introduction to C Programming

Today's Topics. CISC 458 Winter J.R. Cordy

Fundamentals of Programming Session 4

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

CS201 Some Important Definitions

More loops Ch

Functions. Arash Rafiey. September 26, 2017

Lecture 5: Methods CS2301

What Is a Function? Illustration of Program Flow

QUIZ. What are 3 differences between C and C++ const variables?

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Chapter 5 C Functions

CSCI 2132 Software Development. Lecture 18: Functions

PERIYAR CENTENARY POLYTECHNIC COLLEGE Periyar Nagar- Vallam Thanjavur

Fundamentals of Programming

Data Types. Data Types. Integer Types. Signed Integers

Programming for Engineers Pointers

Functions in MIPS. Functions in MIPS 1

QUIZ. Source:

IV Unit Second Part STRUCTURES

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

Here's how you declare a function that returns a pointer to a character:

CSCI 171 Chapter Outlines

Informatica e Sistemi in Tempo Reale

b. array s first element address c. base address of an array d. all elements of an array e. both b and c 9. An array elements are always stored in a.

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

Decision Making -Branching. Class Incharge: S. Sasirekha

APS105. Modularity. C pre-defined functions 11/5/2013. Functions. Functions (and Pointers) main. Modularity. Math functions. Benefits of modularity:

Computer Programming & Problem Solving ( CPPS ) Turbo C Programming For The PC (Revised Edition ) By Robert Lafore

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

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

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

Introduction to Programming (Java) 4/12

CS536 Spring 2011 FINAL ID: Page 2 of 11

C-LANGUAGE CURRICULAM

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Lecture 5 C Programming Language

PROGRAMMAZIONE I A.A. 2017/2018

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

MPATE-GE 2618: C Programming for Music Technology. Unit 4.1

Transcription:

Functions When programs become too large and complex and as a result the task of debugging, testing, and maintaining becomes difficult then C provides a most striking feature known as user defined function to solve this problem. If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These independently coded programs are called sub programs that are much easier to understand, debug and test. In C these sub programs are referred to as functions. A function is a self contained block of statements that perform a coherent task of some kind. Or A function is a self contained block of code that is designed to perform a specific task. Once a function has been designed and packed then it can be treated as a separate entity/module/component or black box that takes some data from the main program and returns a value. The inner details of operation are invisible to the rest of the program. All that the program knows about a function is: What goes in and what comes out. Every C program is a collection of these functions Few Facts About Functions: 1. Functions can be either library functions or user defined functions. For example printf( ), scanf( ) are library functions. And user defined functions may be of any name like message( ), show( ) or etc. 2. There can be any number of functions in a program and any function can call any other function any number of times. 3. The order in which the function get called and the order in which they are defined in a program need not necessarily be same. 4. The use of user defined functions allows a large program to be broken down into a number of smaller self contained component/blocks, each of which has a definite purpose. Advantages of Functions: There are several advantages of using functions in a program like:- 1. Writing user defined functions avoids rewriting the same code again and again 2. Functions makes debugging or error rectification very easy 3. Functions make testing very easy. 4. Functions provide a main concept of reusability of same code again and again. 5. Functions divide a large program or problem into a number of small sub programs or sub problems User Defined Functions Page: 1 By Hemant Kumar

For example: here a small program is given below This program will print the following output: -------------------------------------------------------------------------- This illustrates the use of C functions -------------------------------------------------------------------------- The above program contains two user defined functions: main() function and printline() function Elements of User Defined Functions: In order to make use of a user defined functions, we need to establish three elements that are related to functions. 1. Function definition 2. Function call 3. Function declaration The function definition is an independent program module that is specially written to implement the requirements of the function. In order to use this function we need to invoke it at a required place in the program. This is known as function call. The program that calls the function is referred to as the calling function. The calling program should declare any function (like variable declaration) that is to be used later in the program. This is known as the function declaration or function prototype. User Defined Functions Page: 2 By Hemant Kumar

Elements of User Defined Functions: A function definition is also known as function implementation. It includes the following elements: 1. Function name 2. Function s return type 3. List of parameters 4. local variable declaration 5. Function statements (or function body or logical statement) 6. A return statement All the six elements are grouped into two parts Function header (first three elements) Function body (second three elements) A general format of a function definition to implement these two parts is given below: The first line Function_type function_name(parameter list) is known as function header. And the statement within the opening and closing braces constitute the function body, which is a compound statement. The parameters which are declared in function header are known as formal parameters. The parameters which are passed in function calling are known as actual parameters. Types of User Defined Functions: User defined functions are of the following types depending upon the parameters are passed or not and whether a value is returned or not. 1. Function with no arguments and no return values 2. Function with arguments and with no return values 3. Function with arguments and with one return value 4. Function with no arguments but return a value 5. Function that return multiple values. User Defined Functions Page: 3 By Hemant Kumar

Function with No arguments and No return type: When a function has no arguments, it does not receive any value or data from calling function. Similarly, when it does not return a value, the calling function does not receive any data from the called function. For example: The above function void printline(void) does not take any argument that is why its argument list is void. And does not return any value that is why its return type is void. Function with arguments but No return type: When a function takes some arguments, it receives values or data from calling function or from main function. When it does not return a value, the calling function does not receive any data from the called function. The parameters which are passed in function calling are known as actual parameters and the parameters which are declared in function definition are known as formal parameters. When a function call is made, these actual parameters and formal parameters must be matched in type, sequence, and number. For example: User Defined Functions Page: 4 By Hemant Kumar

The above function void printline(char ch) takes one argument that is why its argument list is char ch. And does not return any value that is why its return type is void. Some more examples are given Function with arguments with returning values: Functions with arguments and with returning values: receive input values or data from calling function (or from main function) and return the calculated value as output to the calling function (or to the main function) for the further processing. This concept uses the actual parameters in function calling and formal parameters in function definition and they must be equal in each type like types, numbers, and sequence. For example: Functions with No arguments But return values: The function which do not take any argument or parameter i.e. they don t take any input from main or calling function but they take input data directly from user or they use directly given values with the help of local variables and return the calculated or operated value as output to the calling function in main. Sometimes such functions are also known as utility functions because they provide some certain operated calculated value each time. A typical example of this type as we are discussing is getchar function which is declared in the header file <stdio.h>. The getchar User Defined Functions Page: 5 By Hemant Kumar

function has no parameters but it returns an integer type data that represents a character. For example review the following code segment: Functions with returning Multiple values (i.e. Call By Reference) All the above discussed functions are the functions which can return maximum one value only. This is because a return statement can return only one value at a time. But however we want to get more information from the function, we can achieve it using actual arguments not only to send the information to the function definition but also get back information from the function definition. The arguments that are sued to send out information are called output parameters. The mechanism of sending back information through arguments is achieved using what are known as the address operator (&) and indirection operator (*). For example: - The actual arguments x and y are input arguments, s and d are output arguments. In the function call, while we pass the actual values of x and y to the function we pass the address of locations or variables where the values of s and d are stored in the memory. (That is why, the indirection operator (*) is known as address operator). User Defined Functions Page: 6 By Hemant Kumar

The indirection operator * in the declaration of sum and diff in the header of function indicates these variables are to store addresses, not actual values of variables. Now, the variables sum and diff point to the memory locations of s and d respectively. The variables *sum and *diff are known as pointers and sum and diff as pointer variables. The use of pointer variables as actual parameters for communicating data between functions is called pass by pointer or call by address or call by reference. Rules for Call By Value (or Pass by Pointers) Nested Functions (or Nesting of Functions) C allows nesting of functions. Main function can call a function func1, which calls func2, which calls func3... and so on. There is in principle no limit as to how deeply functions can be nested. For example: User Defined Functions Page: 7 By Hemant Kumar

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 it is called circular definition ; recursion is the process of defining something in terms of itself. Recursion is the process in which a function calls itself in it until a specific condition is satisfied or when a function calls to itself within its definition until a specific condition is satisfied this process is known as recursion and such functions are known as recursive functions. Assume that the number entered through scanf( ) is 3. Using figure give below visualizes what exactly happens when the recursive function rec( ) gets called. Go through the figure carefully. The first time when rec( ) is called from main( ), x collects 3. From here, since x is not equal to 1, the if block is skipped and rec( ) is called again with the argument ( x 1 ), i.e. 2. This is a recursive call. Since x is still not equal to 1, rec( ) is called yet another time, with argument (2-1). This time as x is 1, control goes back to previous rec( ) with the value 1, and f is evaluated as 2. User Defined Functions Page: 8 By Hemant Kumar

Similarly, each rec( ) evaluates its f from the returned value, and finally 6 is returned to main( ). The sequence would be grasped better by following the arrows shown in following Figure Let it be clear that while executing the program there do not exist so many copies of the function rec( ). These have been shown in the figure just to help you keep track of how the control flows during successive recursive calls. Recursion and Stack There are different ways in which data can be organized. For example, if you are to store five numbers then we can store them in five different variables, an array, a linked list, a binary tree, etc. All these different ways of organizing the data are known as data structures. The compiler uses one such data structure called stack for implementing normal as well as recursive function calls. A stack is a Last in First out (LIFO) data structure. This means that the last item to get stored on the stack (often called Push operation) is the first one to get out of it (often called as Pop operation). Now let us see how the stack works in case of the following program. User Defined Functions Page: 9 By Hemant Kumar

In this program before transferring the execution control to the function fun( ) the values of parameters a and b are pushed onto the stack. Following this the address of the statement printf( ) is pushed on the stack and the control is transferred to fun( ). It is necessary to push this address on the stack. In fun( ) the values of a and b that were pushed on the stack are referred as i and j. In fun( ) the local variable sum gets pushed on the stack. When value of sum is returned sum is popped up from the stack. Next the address of the statement where the control should be returned is popped up from the stack. Using this address the control returns to the printf( ) statement in main( ). Before execution of printf( ) begins the two integers that were earlier pushed on the stack are now popped off. User Defined Functions Page: 10 By Hemant Kumar