UNIT 3 FUNCTIONS AND ARRAYS

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

CSE202-Lec#4. CSE202 C++ Programming

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

15 FUNCTIONS IN C 15.1 INTRODUCTION

Functions BCA-105. Few Facts About Functions:

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

CSE 230 Intermediate Programming in C and C++ Functions

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

FUNCTIONS. Without return With return Without return With return. Example: function with arguments and with return value

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

Unit III Functions. C functions can be classified into two categories, namely, library functions and user defined functions.

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

Unit 3 Decision making, Looping and Arrays

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

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

SUHAIL T A

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Chapter-13 USER DEFINED FUNCTIONS

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

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

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

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

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

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

FUNCTIONS OMPAL SINGH

Data Types and Variables in C language

Subject: Fundamental of Computer Programming 2068

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

UIC. C Programming Primer. Bharathidasan University

Functions. Arash Rafiey. September 26, 2017

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Prepared by: Shraddha Modi

C Programming Lecture V

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


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

C: How to Program. Week /Mar/05

Chapter 5 C Functions

OBJECTIVE QUESTIONS: Choose the correct alternative:

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

Tutorial No. 2 - Solution (Overview of C)

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C

Chapter 2 - Introduction to C Programming

Flow Control. CSC215 Lecture

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

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

Lecture 04 FUNCTIONS AND ARRAYS

M.EC201 Programming language

Programming for Engineers Introduction to C

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

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

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

DECLARAING AND INITIALIZING POINTERS

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

Structured Programming. Functions and Structured Programming. Functions. Variables

Functions. Systems Programming Concepts

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

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

Basics of Programming

Fundamentals of Programming Session 12

IV Unit Second Part STRUCTURES

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

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Fundamentals of Programming Session 4

Function Call Stack and Activation Records

SOLUTION FOR FUNCTION. 1) Write a program to display Hello 10 times. Create user-defined function message().

UNIT - V STRUCTURES AND UNIONS

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

UNIT-IV. Structure is a user-defined data type in C language which allows us to combine data of different types together.

UNIT 3 OPERATORS. [Marks- 12]

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

M.CS201 Programming language

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

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

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

A Fast Review of C Essentials Part I

Model Viva Questions for Programming in C lab

Fundamentals of Computer Programming Using C

AMCAT Automata Coding Sample Questions And Answers

Fundamentals of Programming Session 14

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

Q 1. Attempt any TEN of the following:

User Defined Functions

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Computer Programming Unit 3

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

LESSON 6 FLOW OF CONTROL

A Fast Review of C Essentials Part II

Iterative Languages. Scoping

Fundamental Concepts and Definitions


University of Kelaniya Sri Lanka

C: How to Program. Week /Apr/16

Language Fundamentals

Case Control Structure. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

Functions and Recursion

C Programming Class I

Functions and Recursion

Software Design & Programming I

Chapter 7 Functions. Now consider a more advanced example:

Transcription:

UNIT 3 FUNCTIONS AND ARRAYS Functions Function definitions and Prototypes Calling Functions Accessing functions Passing arguments to a function - Storage Classes Scope rules Arrays Defining an array processing an array - Passing arrays to Functions Multidimensional Arrays Arrays and strings

FUNCTIONS If a program is divided into functional parts, then each part may be independently coded and later combined into a single unit. These subprograms are called functions. Functions are much easier to understand, debug, and test. Another approach is to design a function that can be called and used whenever required.

Advantages It facilitates top-down modular programming as shown below. In this programming style, the high level logic of the overall problem is solved first while the details of each lower-level function are addressed later. Main program Function 1 Function 2 Function 3 Function 4

Advantages The length of a source program can be reduced by using functions at appropriate places. It is easy to locate and isolate a faulty function for further investigations. A function may be used by many other programs. This means that a C programmer can build on what others have already done.

A multi-function program A function is a self-contained block of code that performs a particular task. Once a function has been designed and packed, it can be treated as a 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.

Consider a set of statements as shown below: printline( ) int i; for(i=1;i<40;i++) printf( - ); printf( \n ); The above set of statements defines a function called printline() which could print a line of 39-characters length. This function can be used in a program as follows:

main() printline(); printf( This illustrates the use of C functions\n ); printline(); printline( ) int i; for(i=1;i<40;i++) printf( - ); printf( \n );

The program will print the following output: --------------------------------------- This illustrates the use of C functions --------------------------------------- As we know the program execution always begins with the main() function. During execution of the main(), the first statement encountered is printline(); which indicates that the function printline() is to be executed. At this point the, the program control is transferred to the function printline(); After executing the printline() function which outputs as a line of 39 characters length, the control is transferred back to the main().

main() function1(); function2(); function1() ----------- function3(); function2() -------------- -------------- function3() -------------- -------------- Flow of control in By a A. multi-function Vijay Bharath program

SYNTAX:ALL FUNCTION HAVE THE FORM function-name(argument list) argument declaration; local variable declarations; executable statement1; executable statement2; ------------------- ------------------- return(expression);

A function can have any number of executable statements. A function that does nothing, may not include any executable statements at all. For example: do_nothing() The return statement is the mechanism for returning value to the calling function. This also an optional statement. Its absence indicates that no value is being returned to the called function.

Argument List The argument list contains valid variable names separated by commas. The list must be surrounded by parenthesis. Note that no semicolon follows the closing parenthesis. The argument variables receive values from the calling function, thus providing a means for data communication from the calling function to the called function.

Examples of function arguments: quadratic(a,b,c) power(x,n) mul(a,b) All arguments variables must be declared for their types after the function header and before the opening brace of the function body. Example: power(x,n) float x; int n; -------- --------

RETURN VALUES AND THEIR TYPES A function may or may not send back any value to the calling function. If it does, it is done through the return statement. The return statement can take one of the following forms return; or return(expression); The plain return does not return any value; it acts much as the closing brace of the function.

When the return is encountered, the control is immediately passed back to the calling function. The second form of return with an expression returns the value of the expression. For example, the function mul(x,y) int x, y; int p; p=x*y; return(p); Returns the value of p. The last two statements can be combined into one statement as follows: return(x*y);

A function may have more than one return statement. This situation arises when the value returned is based on certain condition. For E.g. if (x<=0) return(0); else return(1); All function by default return an int type. We can force a function to return a particular type of data by using a type specifier in the function header. Example: double product(x,y) float sqr_root(p)

Calling a function A function can be called by simply using the function name in a statement. Example : main() int p; p=mul(10,5); printf( %d\n,p); When the compiler encounters a function call, the control is transferred to the function mul(x,y). This function is then executed line by line as described and a value is returned when a return statement is encountered. This value is assigned to p.

Valid function statements printf( %d\n, mul(p,q)); Y=mul(p,q) / (p+q); If (mul(m,n) > total) printf( large ); However, a function cannot be used on the left hand side of an assignment statement. For instance: is invalid. mul(a,b) = 15;

Write a program to calculate the factorial #include<stdio.h> fact(int n) void main() if (n<=1) return(1); int f; else clrscr(); return(n * fact(n-1)); printf("\n enter the number"); scanf("%d",&n); f=fact(n); printf("\nfactorial of the no. is %d",f); getch();

Category of functions A function, may belong to one of the following categories. 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 return values.

Category 1: No arguments and No return values When a function has no arguments, there is no data transfer between the calling function and the called function. This is depicted in the following Fig. function 1() -------- functio2(); -------- -------- no input no output Function 2() ----- ----- ----- -----

main() printline(); sum(); printline(); printline( ) int i; output: for(i=1;i<40;i++) ------------------------------------ printf( - ); enter the first number:25 printf( \n ); enter the second number:38 the sum of numbers is: 63 sum() ------------------------------------ int a,b,c; Printf( enter the first number: ); scanf( %d,&a); Printf( enter the second number: ); scanf( %d,&b); c=a+b; printf( the sum of numbers is : %d,c); It is important to note that the function sum() receives its data directly from the terminal. When the closing braces of the sum() is reached, the control is transferred back to the calling function main().

Category 2: Arguments but No return values The nature of data communication between the calling function and the called function with arguments but no return values is shown in Fig. function 1() -------- function2(a); -------- -------- values of arguments no return value Function 2(f) ----- ----- ----- -----

We shall modify declaration of both the called functions to include arguments as follows: printline(ch) value(p,r,n) The arguments ch,p,r,n are called the formal arguments. For example: value(500,0.12,5) ----- actual arguments would send the values 500, 0.12, and 5 to the function value(p,r,n). So the actual arguments which become the values of the formal arguments of the called function.

The actual and formal arguments should match in number, type and order. The values of actual arguments are assigned to the formal arguments on a one to one basis, starting with the first arguments as shown below:

Arguments matching between the function call and the called function Function call Called function actual arguments main() ------- function1(a1, a2, a3,....am); ------- function1(f1, f2, f3,..... fn) - - - - - - - - - formal arguments - - - - -

We should ensure that the function call has matching arguments. In case, the actual arguments are more than the formal arguments (m > n), the extra actual arguments are discarded. On the other hand, if the actual arguments are less than the formal arguments, the unmatched formal arguments are initialized to garbage value. Any mismatch in data type may also result in passing of garbage values. Remember no error message will be generated.

main() int a,b; printline(); Printf( enter the first number: ); scanf( %d,&a); Printf( enter the second number: ); scanf( %d,&b); sum(a,b); printline(); printline( ) int i; output: for(i=1;i<40;i++) ----------------------------------- printf( - ); printf( \n ); enter the first number:53 enter the second number:47 the sum of numbers is: 100 sum(m,n) ----------------------------------- int m,n; int c; c=m+n; printf( the sum of numbers is : %d,c);

Category 3: Arguments with return values Two-way data communication between functions. We shall modify the use of two-way data communication between the calling and the called function as follows. function 1() -------- function2(a); -------- -------- values of arguments Function result Function 2(f) ----- ----- ----- return(e);

main() int a,b,x; printline(); Printf( enter the first number: ); scanf( %d,&a); Printf( enter the second number: ); scanf( %d,&b); x=sum(a,b); printf( the sum of numbers is : %d,x); printline(); printline( ) int i; output: for(i=1;i<40;i++) ----------------------------------- printf( - ); printf( \n ); enter the first number:53 enter the second number:47 the sum of numbers is: 100 sum(m,n) ----------------------------------- int m,n; int c; c=m+n; return(c);

Handling of Non-integer function By default the function will return integer type. For example, sum(m,n) float m,n; float c; c=m+n; return(c); does all calculations using float but the return statement will returns only the integer part of SUM. This is due to the absence of type-specifier in the function header.

We must do two things to enable a calling function to receive a non-integer value from a called function: 1. The explicit type-specifier, corresponding to the data type required must be mentioned in the function header. The general form of the function header definition is: type-specifier function-name (argument list) argument declaration; function statements; The type-specifier tells the compiler, the type of data the function is to return.

2. The called function must be declared at the start of the body in the calling function, like any other variable. This is to tell the calling function the type of data that the function is actually returning. Example: #include<stdio.h> float mul(x,y) #include<conio.h> float x,y; main() return(x*y); float a,b,mul(); double div(); clrscr(); a=12.345; double div(p,q) b=9.82; float p,q; printf("%f\n", mul(a,b)); printf("%f\n", div(a,b)); return(p/q); getch();

Nesting of functions C permits nesting of functions freely. main() can call function1(), which calls function2, which calls function3, and soon. There is no limit as to how deeply functions can be nested.

Example main() int a,b,c; difference(p,q) float ratio(); int p,q; scanf( %d %d %d,&a,&b,&c); printf( %f\n,ratio(a,b,c)); if(p!=q) return(1); float ratio(x,y,z) else int x,y,z; return(0); if(difference(y,z)) return(x/(y-z)); else return(0.0);

Recursion When a called function in turn calls another function a process of chaining occurs. Recursion is a special case of this process, where a function calls itself. A very simple example of recursion is below:- main() printf( this is an example of recursion ); main();

Program to calculate the factorial value #include<stdio.h> fact(int n) void main() if (n<=1) return(1); int f; else clrscr(); return(n * fact(n-1)); printf("\n enter the number"); scanf("%d",&n); f=fact(n); printf("\nfactorial of the no. is %d",f); getch();

Declaration of storage class Variables in C not only have the data type but also storage class that provides the information about their location and visibility. The storage class decides the portion of the program within which the variables are recognized. Consider the following example:-

/* Example of storage class */ int m; main() global variable int i; float balance;... function1() function1() int i; float sum;......

The variable m which is declared before the main() function is called global variable. It can be used in all the functions in the program. It need not be declared in other functions. A global variable is also known as external variable. The variables i, balance, sum are called local variables because they are declared inside a function. Local variables are visible and meaningful only inside the function in which they are declared.

Note that the variable i has been declared in both the functions. Any change in the value of i in one function does not affect its value in the other. There are four storage classes : Storage class auto static extern register Meaning Local variable known to only to the function in which it is declared. Default is auto. Local variable which exists and retains its value even after the control is transferred to the calling function Global variable known to all functions in the file. Local variable which is stored in the register.

The storage class is another qualifier that can be added to a variable declaration as shown below: auto int count; register char ch; static int x; extern long total;

Automatic variables Automatic variables are declared inside a function in which they are to be utilized. They are created when the function is called and destroyed automatically when the function is exited. Automatic variables are therefore private (or local) to the function in which they are declared. A variable declared inside a function without storage class specification is, by default, an automatic variable.

For instance, the storage class of the variable number in the example below is automatic. main() int number; ------- We may also use the keyword auto to declare automatic variables explicitly. main() auto int number; -------

main() int n, a,b;.......... if(n<=100) int n, sum;............ /* sum not valid here */ Scope level 1 Scope level 2 The variable n, a and b defined in main() have scope from the beginning to the end of main(). However, the variable n defined in the main() cannot enter into the block of scope level 2 because the scope level 2 contains another variable named n. The second n is available only inside the scope level 2 and no longer available the moment control leaves the if block.

External variables Variables that are both alive and active throughout the entire program are known as external variables. They are also known as global variables Unlike local variables, global variables can be accessed by any function in the program. External variables are declared outside the main() function as follows:

External variables int number; float length; main() -------- -------- function1() ------ The variable number and length are available for use in all the three functions. In case a local variable and a global variable have the same name, the local variable will have precedence over the global one in the function where it is declared. function2() ------

int x; main() X=10; Printf( x=%d\n,x); Printf( x=%d\n, fun1()); fun3() Printf( x=%d\n,fun2()); Printf( x=%d\n,fun3()); x=x+10; return(x); fun1() X=x+10; return(x); OUTPUT: fun2() int x; X=1; return(x); x=10 X=20 X=1 X=30

External declaration In the below program, main() cannot access the variable y as it has been declared after the main() function. This problem is solved by declaring the variable with the storage class extern. main() extern int y;... func1() extern int y;... int y;

External declaration Although the variable y has been defined after the both the functions, the external declaration of y inside the function informs the compiler that y is an integer type defined somewhere else in the program. main() extern int y;... func1() extern int y;... int y;

Static variable The value of static variables persists until the end of a program. static int x; A static variable may be either an external type or an internal type, depending on the place of declaration. Internal static variables are those which are declared inside a function. The scope of internal static variable extend up to the end of function in which they are defined.

Static variable main() int i; for(i=1;i<=3;i++) stat(); stat() static int x=0; output: x=x+1; x=1 printf( x=%d\n,x); x=2 x=3

Register variables 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). Register access is much faster than a memory access, keeping the frequently accessed variable register int count; Only 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 nonregister variables once the limit is reached