Unit iv functions

39
FUNCTIONS UNIT- IV Fundamental of Computer programming -206

Transcript of Unit iv functions

Page 1: Unit  iv functions

FUNCTIONS

UNIT- IV

Fundamental of Computer programming -206

Page 2: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

CONTENTS: UNIT-IV

Functions in C Passing Parameters, using returned data Passing arrays, passing characters and strings Passing structures, array of structures, pointer

to structures The void pointer,

2

Page 3: Unit  iv functions

FUNCTIONS IN C

Lecture no.- 34, UNIT- IV

Page 4: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.1.1- INTRODUCTION TO MODULAR PROGRAMMING

Definition A modular programming is the process of subdividing a

computer program into separate sub-programs.

The benefits of using modular programming include:

Less code has to be written. A single procedure can be developed for reuse,

eliminating the need to retype the code many times. Programs can be designed more easily because a small

team deals with only a small part of the entire code. Modular programming allows many programmers to

collaborate on the same application. The code is stored across multiple files. Code is short, simple and easy to understand. 4

Page 5: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.1.2- FUNCTION DECLARATION, CALLING AND DEFINITION

Definition:- A function is a group of statements that together

perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

Defining a Function The general form of a function definition in C

programming language is as follows − return_type function_name( parameter list ) {

body of the function ;}

5

Page 6: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

CONT… Here are all the parts of a function −

Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Body − The function body contains a collection of statements that define what the function does. 6

Page 7: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Example:

/* function returning the max between two numbers */

int max(int num1, int num2) { /* local variable declaration */

int result; if (num1 > num2) result = num1; else result = num2; return result;

}

7

Page 8: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Function Declarations A function declaration tells the compiler about a function

name and how to call the function. The actual body of the function can be defined separately.

A function declaration has the following parts − return_type function_name( parameter list );

int max(int num1, int num2);

Parameter names are not important in function declaration only

their type is required, so the following is also a valid declaration

int max(int, int); 8

Page 9: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Calling a Function

While creating a C function, we give a definition of what the function has to do. To use a function, we will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

To call a function, we simply need to pass the required parameters along with the function name, and if the function returns a value, then we can store the returned value. 9

Page 10: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

For example −#include <stdio.h>int max(int num1, int num2); /* function declaration */ int main ()

{ /* local variable definition */ int a = 100;

int b = 200; int ret; ret = max(a, b); /* calling a function to get max value */ printf( "Max value is : %d\n", ret ); return 0; } /* function returning the max between two numbers */

int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }

10

Page 11: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.1.3 & -1.4 STANDARD LIBRARY & USER DEFINE FUNCTIONS

C functions can be classified into two categories:- Library functions User-defined functions

11

Page 12: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Definition: Library functions are those functions which are

defined by C library, example printf(), scanf(), strcat() etc. we just need to include appropriate header files to use these functions. These are already declared and defined in C libraries.

User-defined functions are those functions which are defined by the user at the time of writing program. Functions are made for code reusability and for saving time and space.

12

Page 13: Unit  iv functions

PASSING PARAMETERS, USING RETURNED DATA

Lecture no.- 35, UNIT- IV

Page 14: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.2.1 PARAMETER PASSING MECHANISM

Definition:What is Parameter ? In computer programming, a parameter is a special kind

of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine.These pieces of data are called arguments.

Function With Parameter :

add(a,b);

Here Function add() is Called and 2 Parameters are Passed to Function. a,b are two Parameters.

Function Call Without Passing Parameter :

Display(); 14

Page 15: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

15

PARAMETERSExample:Formal parameters

float ave(float a, float b) { return (a+b)/2.0; }

Actual parameters

ave(x, 10.0)

Page 16: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.2.1.1- BY VALUEFunction Arguments While calling a function, there are two ways in which

arguments can be passed to a function −

1. Call by value2. Call by reference

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

16

Page 17: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Example: Consider the function swap()definition as follows./* function definition to swap the values */ void swap(int x, int y)

{ int temp; temp = x; /* save the value of x */ x = y; /* put y into x */ y = temp; /* put temp into y */ return;

}

17

Page 18: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

let us call the function swap() by passing actual values as in the following example −

#include <stdio.h> /* function declaration */ void swap(int x, int y); int main ()

{ /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a );printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */ swap(a, b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0;

} 18

Output:-Before swap, value of a :100Before swap, value of b :200

After swap, value of a :100 After swap, value of b :200

Note:-It shows that there are no changes in the values, though they had been changed inside the function.

Page 19: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.2.1.2 BY REFERENCE The call by reference method of passing arguments to

a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.

Example:/* function definition to swap the values */ void swap(int *x, int *y) {

int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return;

} 19

Page 20: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

#include <stdio.h> /* function declaration */ void swap(int *x, int *y); int main ()

{ /* local variable definition */ int a = 100; int b = 200; printf("Before swap, value of a : %d\n", a ); printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */

swap(&a, &b); printf("After swap, value of a : %d\n", a ); printf("After swap, value of b : %d\n", b ); return 0;

}20

Note:-It shows that the change has reflected outside the function as well, unlike call by value where the changes do not reflect outside the function.

Output:-Before swap, value of a :100Before swap, value of b :200

After swap, value of a :100 After swap, value of b :200

Page 21: Unit  iv functions

PASSING ARRAYS, PASSING CHARACTERS AND STRINGS

Lecture no.- 36, UNIT- IV

Page 22: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.3.1 PASSING ARRAY TO A FUNCTION Whenever we need to pass a list of elements as

argument to the function, it is prefered to do so using an array. 

Declaring Function with array in parameter list

22

Page 23: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

EXAMPLE PASSING ARRAYFunction:

double getAverage(int arr[], int size) {

int i; double avg; double sum = 0; for (i = 0; i < size; ++i)

{ sum += arr[i]; }

avg = sum / size; return avg;

}23

Page 24: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Now, let us call the above function as follows −#include <stdio.h> /* function declaration */ double getAverage(int arr[], int size); int main ()

{ /* an int array with 5 elements */ int balance[5] = {1000, 2, 3, 17, 50}; double avg;

/* pass pointer to the array as an argument */ avg = getAverage( balance, 5 ) ;

/* output the returned value */ printf( "Average value is: %f ", avg ); return 0;

} 24Output:-Average value is: 214.400000

Page 25: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.3.3 PASSING STRINGS TO FUNCTION Strings are just char arrays. So, they can be passed to a function

in a similar manner as arrays.#include <stdio.h> void displayString(char str[]); int main()

{ char str[50]; printf("Enter string: "); gets(str); displayString(str); // Passing string c to function. return 0; }

void displayString(char str[]){printf("String Output: "); puts(str); } 25

Page 26: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.3.4 PASSING POINTERS TO A FUNCTION

C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type.

#include <stdio.h> #include <time.h> void getSeconds(unsigned long *par); int main ()

{ unsigned long sec; getSeconds( &sec );

/* print the actual value */ printf("Number of seconds: %ld\n", sec ); return 0; }

void getSeconds(unsigned long *par) { /* get the current number of seconds */ *par = time( NULL ); return; } 26

Output:-Number of seconds :1294450468

Page 27: Unit  iv functions

PASSING STRUCTURES, ARRAY OF STRUCTURES, POINTER TO STRUCTURES, THE VOID POINTER

Lecture no.- 37, UNIT- IV

Page 28: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.4.1 PASSING STRUCTURE TO FUNCTION

In C, structure can be passed to functions by two methods: Passing by value (passing actual value as argument) Passing by reference (passing address of an argument)

Passing structure by value A structure variable can be passed to the function as an

argument as a normal variable.

If structure is passed by value, changes made to the structure variable inside the function definition does not reflect in the originally passed structure variable.

28

Page 29: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

C program to create a structure student, containing name and roll and display the information.

29

#include <stdio.h> struct student { char name[50]; int roll; }; void display(struct student stu); // function prototype should be below to the structure declaration otherwise compiler shows error int main() { struct student stud; printf("Enter student's name: "); scanf("%s", &stud.name); printf("Enter roll number:"); scanf("%d", &stud.roll);

display(stud); // passing structure variable stud as argument return 0; } void display(struct student stu) { printf("Output\nName: %s",stu.name);

printf("\nRoll: %d",stu.roll); }Output:

Enter student's name: Kevin AmlaEnter roll number: 149 Output Name: Kevin Amla Roll: 149

Page 30: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Passing structure by reference

• The memory address of a structure variable is passed to function while passing it by reference.

• If structure is passed by reference, changes made to the structure variable inside function definition reflects in the originally passed structure variable.

C program to add two distances (feet-inch system) and display the result without the return statement.

30

Page 31: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

#include <stdio.h> struct distance { int feet; float inch; }; void add(struct distance d1,struct distance d2, struct distance *d3);

int main() { struct distance dist1, dist2, dist3; printf("First distance\n"); printf("Enter feet: "); scanf("%d", &dist1.feet); printf("Enter inch: "); scanf("%f", &dist1.inch);

printf("Second distance\n"); printf("Enter feet: "); scanf("%d", &dist2.feet);

printf("Enter inch: "); scanf("%f", &dist2.inch); add(dist1, dist2, &dist3); //passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference printf("\nSum of distances = %d\'-%.1f\"", dist3.feet, dist3.inch);

return 0; } ….…..

Cont… in next slide

31

Page 32: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

#include <stdio.h> struct distance { int feet; float inch; }; void add(struct distance d1,struct distance d2, struct distance *d3);

int main() { struct distance dist1, dist2, dist3; printf("First distance\n"); printf("Enter feet: "); scanf("%d", &dist1.feet); printf("Enter inch: "); scanf("%f", &dist1.inch);

printf("Second distance\n"); printf("Enter feet: "); scanf("%d", &dist2.feet); printf("Enter inch: "); scanf("%f", &dist2.inch); add(dist1, dist2, &dist3); //passing structure variables dist1 and dist2 by value whereas passing structure

variable dist3 by reference printf("\nSum of distances = %d\'-%.1f\"", dist3.feet, dist3.inch); return 0; } void add(struct distance d1,struct distance d2, struct distance *d3) { //Adding distances d1 and d2 and

storing it in d3 d3->feet = d1.feet + d2.feet; d3->inch = d1.inch + d2.inch; if (d3->inch >= 12) { /* if inch is greater or equal to 12, converting it to feet. */ d3->inch -= 12; ++d3->feet; } }

32

Page 33: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

void add(struct distance d1,struct distance d2, struct distance *d3) { //Adding distances d1 and d2 and storing it in d3

d3->feet = d1.feet + d2.feet; d3->inch = d1.inch + d2.inch; if (d3->inch >= 12)

{ /* if inch is greater or equal to 12, converting it to feet. */ d3->inch -= 12; ++d3->feet;

} }

OutputFirst distance Enter feet: 12 Enter inch: 6.8 Second distance Enter feet: 5 Enter inch: 7.5 Sum of distances = 18'-2.3" 33

Page 34: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

In this program, structure variables dist1 and dist2 are passed by value to the add function (because value of dist1 and dist2 does not need to be displayed in main function).

But, dist3 is passed by reference ,i.e, address of dist3 (&dist3) is passed as an argument.

Due to this, the structure pointer variable d3 inside the add function points to the address of dist3 from the calling main function. So, any change made to the d3 variable is seen in dist3 variable in main function.

34

Page 35: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

4.4.4- VOID POINTER Void Pointers in C : Definition

Suppose we have to declare integer pointer, character pointer and float pointer then we need to declare 3 pointer variables.

Instead of declaring different types of pointer variable it is feasible to declare single pointer variable which can act as integer pointer, character pointer.

Void Pointer Basics : In C General Purpose Pointer is called as void Pointer. It does not have any data type associated with it It can store address of any type of variable A void pointer is a C convention for a raw address. The compiler has no idea what type of object a void Pointer

really points to ? 35

Page 36: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Declaration of Void Pointer :

void * pointer_name;

Void Pointer Example :

void *ptr; // ptr is declared as Void pointer char cnum; int inum; float fnum;

ptr = &cnum; // ptr has address of character data ptr = &inum; // ptr has address of integer data ptr = &fnum; // ptr has address of float data 36

Page 37: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Explanation :void *ptr;

Void pointer declaration is shown above.

We have declared 3 variables of integer, character and float type.

1. When we assign address of integer to the void pointer, pointer will become Integer Pointer.

2. When we assign address of Character Data type to void pointer it will become Character Pointer.

3. Similarly we can assign address of any data type to the void pointer.

4. It is capable of storing address of any data type 37

Page 38: Unit  iv functions

By- Er. Indrajeet Sinha , +919509010997

Summary : Void Pointer

38

Scenario Behavior

When We assign address of integer variable to void pointer

Void Pointer Becomes Integer Pointer

When We assign address of character variable to void pointer

Void Pointer Becomes Character Pointer

When We assign address of floating variable to void pointer

Void Pointer Becomes Floating Pointer

Page 39: Unit  iv functions

COMPUTER, NUMBER SYSTEM

UNIT- V

Fundamental of Computer programming -206