Unit 7. Functions. Need of User Defined Functions

Similar documents
15 FUNCTIONS IN C 15.1 INTRODUCTION

UNIT 3 FUNCTIONS AND ARRAYS

DECLARAING AND INITIALIZING POINTERS

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

Functions. Systems Programming Concepts

Storage class in C. Automatic variables External variables Static variables Register variables Scopes and longevity of above types of variables.

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

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

Fundamentals of Programming Session 12

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

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Functions BCA-105. Few Facts About Functions:

Functions. Arash Rafiey. September 26, 2017

UNIT III (PART-II) & UNIT IV(PART-I)

CSE 230 Intermediate Programming in C and C++ Functions

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

Functions. Lecture 6 COP 3014 Spring February 11, 2018

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

Chapter 8: Function. In this chapter, you will learn about

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

Introduction to C Final Review Chapters 1-6 & 13

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

UNIT- 3 Introduction to C++

Lecture 04 FUNCTIONS AND ARRAYS

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

C Functions. Object created and destroyed within its block auto: default for local variables

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

User Defined Functions

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

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

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

A Fast Review of C Essentials Part I

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

Lecture 04 FUNCTIONS AND ARRAYS

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

C-LANGUAGE CURRICULAM

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

Chapter 5 C Functions

Fundamentals of Programming & Procedural Programming

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

AMCAT Automata Coding Sample Questions And Answers

Model Viva Questions for Programming in C lab

BLM2031 Structured Programming. Zeyneb KURT

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

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Subject: Fundamental of Computer Programming 2068

Chapter 7 Functions. Now consider a more advanced example:

3 The L oop Control Structure

Lecture 2: C Programming Basic

Fundamentals of Programming Session 13

MODULE 3: Arrays, Functions and Strings

SUHAIL T A

A Fast Review of C Essentials Part II

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

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

Computer Science & Engineering 150A Problem Solving Using Computers

Chapter 3 - Functions

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

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

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

ARRAYS(II Unit Part II)

C: How to Program. Week /Apr/16

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

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Function Call Stack and Activation Records

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Work relative to other classes

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

PROGRAMMAZIONE I A.A. 2017/2018

Unit 4. Input/Output Functions

CSE123. Program Design and Modular Programming Functions 1-1

Lecture 9 - C Functions

Functions and Recursion

LESSON 6 FLOW OF CONTROL

Structured Programming. Functions and Structured Programming. Functions. Variables

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

M1-R4: Programing and Problem Solving using C (JAN 2019)

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

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

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

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

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

INTRODUCTION 1 AND REVIEW

EC 413 Computer Organization

Flow Control. CSC215 Lecture

C: How to Program. Week /Mar/05

Unit 3 Decision making, Looping and Arrays

Introduction to Programming (Java) 4/12

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


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

Assist. Prof. Dr. Caner ÖZCAN

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

University of Kelaniya Sri Lanka

CSCI 171 Chapter Outlines

MA 511: Computer Programming Lecture 2: Partha Sarathi Mandal

Transcription:

Unit 7 Functions Functions are the building blocks where every program activity occurs. They are self contained program segments that carry out some specific, well defined task. Every C program must have a function. One of the functions must be. Program execution will always begin by carrying out the instructions in function. Additional functions will be subordinate to and also to one another. C functions can be classified into two categories. Library functions : predefined in the standard library of C. Need is just to include the Library. User defined functions : They have to be developed by the user at the time of program writing. Need of User Defined Functions If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. This approach clearly results in a number of advantages. 1. It facilitates top-down modular programming. 2. Length of a program can be reduced by using function. 3. Debugging is easier. 4. Reusability of function increases. The general form of a function is: function_name (arg1, arg2, arg3) type arg1, arg2, arg3. statement 1; : : statement n;

Function Declaration and Prototypes Before defining the function, it is desired to declare the function along with its prototype. In function prototype, the return value of function, type, and number of arguments are specified. The declaration of all functions statement should be first statement in. The general form of function declaration using ANSI Prototype is where arg1, arg2... are the list of arguments. data_type function_name (type1 arg1, type2 arg2 - - - - ); Function prototypes are desirable because they facilitate error checking between calls to a function and corresponding function definition. They also help the compiler to perform automatic type conversions on function parameters. When a function is called, actual arguments are automatically converted to the types in function definition using normal rules of assignment. Function Definition The general form of a function definition is: data_type function_name (formal argument list) argument declarations; local variable declarations; executable statement 1; executable statement 2; ---------- executable statement n; return (expression); Where data_type represents the data type of the value which is returned. The type specification can be omitted if the function returns an integer or a character. The formal argument list is a comma separated list of variables that receive the values from main program when a function is called. The identifiers used as formal arguments are "local" as they are not recognized outside of the function. They are also known as parameters or formal parameters. An empty pair of parenthesis must follow the function name if the function definition does not include any arguments. The argument declarations follow the first line. Each formal argument must have the same data type as its corresponding actual argument. The remainder of the function definition is a compound statement that defines the action to be taken by the function. It is referred to as the body of the function.

Calling a Function A fun can be called by specifying its name followed by a list of arguments enclosed in parentheses and separated by commas. If a function call does not require any arguments, an empty pair of parenthesis must follow the function name. The arguments appearing in the function call are referred to as actual arguments, in contrast to the formal arguments that appear in the first line of function definition. e.g.: /* Program to find square of given number */ float square (float); /* function prototype dec/n*/ float a, b; printf ("\n Enter the number:"); scanf ("%f", &a); b = square (a); /* calling of function with */ / * actual arguments */ printf ("Square of entered no. is = %f", b); float square (x) / * function definition with format l argument * / float x; /* format l argument declaration * / float y; y = x * x; return (y); output: Enter the number: 2 /* Local variable declaration Square of the entered number is = 4 The return Statement Information is returned from the function to the calling portion of the program via return statement. It causes control to be returned to the point from where the function was accessed. The return statement can take one of the following forms: return; or return (expression);

In the return (expression); statement, the value of the expression is returned to the calling of the program. e.g.: /* Program to convert lower case character to upper case */ # include <stdio.h> char lower, upper; char Lower_to_upper (char Lower); printf ("\n Enter the Lower case character:"); scanf ("%c", & Lower); upper = Lower_to_upper (lower); printf ("\n The upper case Equivalent is % c", upper); char lower_to_upper (Char ch) char c2; c2 = (c1 > = 'a' && c1 < = 'z')? ('A' + c1 - 'a'): c1; return (c2); A function can have multiple return statements, each containing different expressions. e.g.: int square (x) int x; if (x < = 0) return 0; else return (x * x); The absence of return statement indicates that no value is being returned. Storage Classes There are two different ways to characterize variables: i) by data types ii) by storage class Data types refers to the type of information while storage class refers to the life-time of a variable and its scope within the program. A variable in C can have any one of the four storage classes. 1. Automatic variable

2. External variable 3. Static variable 4. Register variable Automatic Variable The scope of an automatic variable is confined to that function in which it is declared. It is created when the function is called and destroyed automatically when the function is exited. Hence the name is Automatic. By default, a variable declared inside a function with storage class specification is an automatic variable. Automatic variable values cannot be changed accidently by what happens in some other functions in the program. e.g.: int m = 1000; function 2( ); printf ("%d \n", m); function 1( ) int m = 10; printf ("%d \n", m); function 2( ) int m = 100; function 1( ); printf ("%d \n", m); output: 10 External Variable 100 1000 An external variable is also known as a global variable. It is not confined to a single function. Its scope extends from the point of definition through the remainder of the program. External variables can be accessed from any function that falls within their scope. They are declared outside a function. If a local variable and a global variable have the same name, local variable will have precedence over global in the function where it is declared. e.g.: int count;

main count = 10; - - - - - - - - - - - - - - - - function ( ) int count = 0; - - - - - - - - - - - - - - count ++; When the function references the variable count, it will be referencing only its local variable, not the global one. The value of count in will not be affected. e.g.: /* illustration of working of global variable int x; x = 10; printf ("x = %d \n", x); printf ("x = %d \n", fun1( )); printf ("x = %d \n", fun2( )); printf ("x = % d \n", func3( )); fun1( ) x = x + 10; return x; fun2( ) int x = 1; return x; fun3( ) x = x+10;

output: x = 10 x = 20 x = 1 x = 30 return (x); External Declaration In the program segment discussed just previously, the main cannot access the variable y as it has been declared after the main function. This problem can be solved by declaring the variable with the storage class extern. e.g.: main() extern int y; /* external declaration */ -------- fun1() extern int y; /* external declaration */ -------- int y; /*definition */ The external declaration of y inside the functions informs the compiler that y is an integer type defined somewhere else in the program. The extern declaration does not allocate storage space for variable. Static Variable Static variables are defined within a function in the same manner as automatic variables, except that the variable declaration must begin with the static storage class designation. e.g.: static int x; or static float y; A static variable is initialized only once, when the program is compiled. It is never initialized again. A static variable may be either an internal type or an external type, depending on the place of declaration. Internal static variables are those which are declared inside a function. The scope of internal static variables extends upto the end of the function in which they are defined. Therefore, internal static variables are similar to auto variables, except that they remain in existence (alive) throughout the remaining program. Therefore, internal static variables can be used to retain values between function calls.

e.g.: /* Illustration of static variable */ main() stat() int i; for(i=1; i<=3; i++) static int x = 0; x = x+1; printf("x = %d;\t", x); Output: x = 1; x = 2; x = 3; stat(); An external static variable is declared outside of all functions and is available to all the functions in that program. The difference between a static external variable and a simple external variable is that the static external variable is available only within the file. Register Variable We can tell the compiler that a variable should be kept in one of the machine's registers, instead of keeping in the memory (where normal variables are stored) since a register access is much faster than a memory access and keeping the frequently accessed variables in the register will lead to faster execution of programs. For example, Loop control variables. This is done as given below: register int count; Since only a few variables can be placed in the register, it is important to carefully select the variables for this purpose. However, C will automatically convert register variables into non-register variables once the limit is reached. Passing Parameters to Functions Call by Value Call by value means sending the values of the arguments to functions. When a single value is passed to a function via an actual argument, the value of the actual argument is copied into the function. Therefore, the value of the corresponding formal argument can be altered within the function, but the value of the actual argument within the calling routine will not change. This procedure for passing the value of an argument to a function is known as passing by value or call by value. e.g.: /* A simple C program containing a function that alters the value of its argument. */ #include <stdio.h> main()

modify (int a) a * = 3; int a = 2; printf("\na = %d (from main, before calling the function)",a); modify(a); printf("\na = %d (from main, after calling the function)",a); printf("\na = %d (from the function, after being modified)",a); return; output: Call by Reference a = 2 (from main, before calling the function) a = 6 (from the function, after being modified) a = 2 (from main, after calling the function) Call by reference means sending the addresses of the arguments to the called function. In this method the addresses of actual arguments in the calling function are copied into formal arguments of the called functions. Thus using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them. Using a call by reference intelligently, it is possible to make a function return more than one value at a time, which involves the study of pointer. Passing Arrays to a Function Array elements can be passed to a function by calling the function by value, or by reference. In call by value, we pass values of array elements to the function while in call by reference we pass the name of array, without any subscript, and the size of array elements to the function. e.g.:1. /* passing by call by value * / int i; display (int m) static int num [ ] = 50, 55, 60, 65, 60; for (i = 0; i < = 4: i++) display (marks [i]); printf ("%d \n", m);

2. /* demonstration of call by reference * / float largest( ); static float value [4] = 2.5, -4.75, 1.2, 3.67; printf ("%f \n", largest (value, 4)); float largest (float arr[ ], int n) int i; float max; max = arr [0]; for (i = 1; i < n; i++) if (max < arr [i]) max = arr [i]; return (max); Recursion in Function Recursion is a process by which a function calls itself repeatedly, until some specified condition has been satisfied. The process is used for repetitive computation in which each action is stated in terms of previous result. In order to solve a problem recursively, two conditions must be satisfied: 1. The problem must be written in recursive form. 2. The problem statement must include a stopping condition. e.g.: /* To calculate the factorial of an integer recursively * / # include <stdio.h> int n; long int fact (int); printf ("\n n = "); scanf ("%d", &n); printf ("\n n! = % ld" fact (n)); long int fact (int n)

if (n < = 1) return 1; else return (n * factorial (n-1)); using recursion.