Unit iv functions

Publish in

Engineering

115 views

Please download to get full document.

View again

of 39
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Share
Description
1. FUNCTIONS UNIT- IV Fundamental of Computer programming -206 2. By- Er. Indrajeet Sinha , +919509010997 CONTENTS: UNIT-IV  Functions in C  Passing Parameters,…
Transcript
  • 1. FUNCTIONS UNIT- IV Fundamental of Computer programming -206
  • 2. 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 structure  The void pointer, 2
  • 3. FUNCTIONS IN C Lecture no.- 34, UNIT- IV
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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 : %dn", 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
  • 11. 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
  • 12. 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
  • 13. PASSING PARAMETERS, USING RETURNED DATA Lecture no.- 35, UNIT- IV
  • 14. 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
  • 15. By- Er. Indrajeet Sinha , +919509010997 15 PARAMETERS Example: Formal parameters float ave(float a, float b) { return (a+b)/2.0; } Actual parameters ave(x, 10.0)
  • 16. By- Er. Indrajeet Sinha , +919509010997 4.2.1.1- BY VALUE Function Arguments While calling a function, there are two ways in which arguments can be passed to a function − 1. Call by value 2. 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
  • 17. 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
  • 18. 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 : %dn", a ); printf("Before swap, value of b : %dn", b ); /* calling a function to swap the values */ swap(a, b); printf("After swap, value of a : %dn", a ); printf("After swap, value of b : %dn", b ); return 0; } 18 Output:- Before swap, value of a :100 Before 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.
  • 19. 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
  • 20. 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 : %dn", a ); printf("Before swap, value of b : %dn", 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 : %dn", a ); printf("After swap, value of b : %dn", 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 :100 Before swap, value of b :200 After swap, value of a :100 After swap, value of b :200
  • 21. PASSING ARRAYS, PASSING CHARACTERS AND STRINGS Lecture no.- 36, UNIT- IV
  • 22. 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
  • 23. By- Er. Indrajeet Sinha , +919509010997 EXAMPLE PASSING ARRAY Function: 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
  • 24. 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; } 24 Output:- Average value is: 214.400000
  • 25. 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
  • 26. 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: %ldn", sec ); return 0; } void getSeconds(unsigned long *par) { /* get the current number of seconds */ *par = time( NULL ); return; } 26 Output:- Number of seconds :1294450468
  • 27. PASSING STRUCTURES, ARRAY OF STRUCTURES, POINTER TO STRUCTURES, THE VOID POINTER Lecture no.- 37, UNIT- IV
  • 28. 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
  • 29. 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("OutputnName: %s",stu.name); printf("nRoll: %d",stu.roll); } Output: Enter student's name: Kevin Amla Enter roll number: 149 Output Name: Kevin Amla Roll: 149
  • 30. 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
  • 31. 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 distancen"); printf("Enter feet: "); scanf("%d", &dist1.feet); printf("Enter inch: "); scanf("%f", &dist1.inch); printf("Second distancen"); 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
  • 32. 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 distancen");  printf("Enter feet: "); 32
  • 33. 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; } } Output First distance Enter feet: 12 Enter inch: 6.8 Second distance Enter feet: 5 Enter inch: 7.5 33
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. COMPUTER, NUMBER SYSTEM UNIT- V Fundamental of Computer programming -206
  • Related Search

    Next Document

    kerangka Tulisan

    We Need Your Support
    Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

    Thanks to everyone for your continued support.

    No, Thanks