0% found this document useful (0 votes)
3 views

lecture5 (1)

The document provides an overview of functions in C programming, including their definition, advantages, and types. It explains the syntax for declaring, calling, and defining functions, as well as the concepts of call by value and call by reference. Additionally, it covers recursion and its applications, along with examples demonstrating these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lecture5 (1)

The document provides an overview of functions in C programming, including their definition, advantages, and types. It explains the syntax for declaring, calling, and defining functions, as well as the concepts of call by value and call by reference. Additionally, it covers recursion and its applications, along with examples demonstrating these concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

C Functions

In c, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function
can be called multiple times to provide reusability and modularity to the C program. In
other words, we can say that the collection of functions creates a program. The
function is also known as procedure or subroutine in other programming languages.

The C standard library provides numerous built-in functions that your program can
call. For example, strcat() to concatenate two strings, memcpy() to copy one
memory location to another location, and many more functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in
a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always an overhead in a C program.

Function Aspects

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to


tell the compiler about the function name, function parameters, and return type.
o Function call Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.
o Function definition It contains the actual statements which are to be
executed. It is the most important aspect to which the control comes when the
function is called. Here, we must notice that only one value can be returned
from the function.
S C function Syntax
N aspects

1 Function return_type function_name (argument list);


declaration

2 Function call function_name (argument_list)

3 Function return_type function_name (argument list)


definition {function body;}

The syntax of creating function in c language is given below:

1. return_type function_name(data_type parameter...){


2. //code to be executed
3. }

A function definition in C programming consists of a function header and a function


body. 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.

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity of
a big program and optimizes the code.
Return Value

A C function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the
function.

Example without return value:

1. void hello(){
2. printf("hello c");
3. }

If you want to return any value from the function, you need to use any data type such
as int, long, char, etc. The return type depends on the value to be returned from the
function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

1. int get(){
2. return 10;
3. }

In the above example, we have to return 10 as a value, so the return type is int. If you
want to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as
the return type of the method.

1. float get(){
2. return 10.2;
3. }

Now, you need to call the function, to get the value of the function.
C Library Functions

Library functions are the inbuilt functions in C that are grouped and placed at a
common place called the library. Such functions are used to perform some specific
operations. For example, printf is a library function used to print on the console. The
library functions are created by the designers of compilers. All C standard library
functions are defined inside the different header files saved with the extension .h. We
need to include these header files in our program to make use of the library functions
defined in such header files. For example, to use the library functions such as
printf/scanf we need to include stdio.h in our program which is a header file that
contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.

SN Header Description
file

1 stdio.h This is a standard input/output header file. It


contains all the library functions regarding standard
input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like


gets(), puts(),etc.

4 stdlib.h This header file contains all the general library


functions like malloc(), calloc(), exit(), etc.

5 math.h This header file contains all the math operations


related functions like sqrt(), pow(), etc.

6 time.h This header file contains all the time-related


functions.

7 ctype.h This header file contains all character handling


functions.

8 stdarg.h Variable argument functions are defined in this


header file.

9 signal.h All the signal handling functions are defined in this


header file.

1 setjmp.h This file contains all the jump functions.


0

1 locale.h This file contains locale functions.


1

1 errno.h This file contains error handling functions.


2

1 assert.h This file contains diagnostics functions.


3
Call by value and Call by reference in C

There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.

C functions exchange information by means of parameters and arguments. The


term parameter refers to any declaration within the parentheses following
the function name in a function declaration or definition; the term argument refers
to any expression within the parentheses of a function call.
Let's understand call by value and call by reference in c language one by one.

Call by value in C

o In call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is
used in the function call; in the call by value method.
o In call by value method, we can not modify the value of the actual parameter by
the formal parameter.
o In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
o The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.

Let's try to understand the concept of call by value in c language by the example
given below:

1. #include<stdio.h>
2. change(int num);
3. int main() {
4. int x=100;
5. printf("Before function call x=%d \n", x);
6. change(x);//passing value in function
7. printf("After function call x=%d \n", x);
8. return 0;
9. }
10. change(int num) {
11. printf("Before adding value inside function num=%d \n",num);
12. num=num+100;
13. printf("After adding value inside function num=%d \n", num);
14. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
Call by Value Example: Swapping the values of the two variables
1. #include <stdio.h>
2. swap(int , int); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the
value of a and b in main
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual
parameters do not change by changing the formal parameters in call by value, a = 10,
b = 20
10. }
swap (int a, int b)
11. {

12. temp = x; /* save the value of x */


13. x = y; /* put y into x */
14. y = temp; /* put temp into y */
15. printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal
parameters, a = 20, b = 10
16. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

Call by reference in C

o In call by reference, the address of the variable is passed into the function call
as the actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters
and actual parameters. All the operations in the function are performed on the
value stored at the address of the actual parameters, and the modified value
gets stored at the same address.
Consider the following example for the call by reference.

1. #include<stdio.h>
2. Change(int *num);
3. int main() {
4. int x=100;
5. printf("Before function call x=%d \n", x);
6. change(&x);//passing reference in function
7. printf("After function call x=%d \n", x);
8. return 0;
9. }
10.
11. void change(int *num) {
12. printf("Before adding value inside function num=%d \n",*num);
13. (*num) += 100; (OR (num=num+100))
14. printf("After adding value inside function num=%d \n", *num);
15. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the v
alue of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actua
l parameters do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal
parameters, a = 20, b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c

No Call by value Call by reference


.

1 A copy of the value is passed into An address of value is passed into


the function the function

2 Changes made inside the Changes made inside the function


function is limited to the function validate outside of the function
only. The values of the actual also. The values of the actual
parameters do not change by parameters do change by
changing the formal parameters. changing the formal parameters.

3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory
location location

Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take
precedence over global variables. Following is an example −
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b) {

printf ("value of a in sum() = %d\n", a);


printf ("value of b in sum() = %d\n", b);
return a + b;
}
When the above code is compiled and executed, it produces the following result −
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Recursion in C

Recursion is the process which comes into existence when a function calls a copy of
itself to work on a smaller problem. Any function which calls itself is called recursive
function, and such function calls are called recursive calls. Recursion involves several
numbers of recursive calls. However, it is important to impose a termination condition
of recursion. Recursion code is shorter than iterative code however it is difficult to
understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks that
can be defined in terms of similar subtasks. For Example, recursion may be applied to
sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is
always overhead. Any problem that can be solved recursively, can also be solved
iteratively. However, some problems are best suited to be solved by the recursion, for
example, tower of Hanoi, Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 is 1*2*3*4*5*6 = 720 . Factorial is not defined for
negative numbers, and the factorial of zero is one, 0!

1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Output
Enter the number whose factorial you want to calculate?5
factorial = 120

We can understand the above program of the recursive method call by the figure
given below:

Recursive Function

A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific
subtask. After this, the recursion stops and the final result is returned from the
function.

The case at which the function doesn't recur is called the base case whereas the
instances where the function keeps calling itself to perform a subtask, is called the
recursive case. All the recursive functions can be written using this format.

Pseudocode for writing any recursive function is given below.

1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }

Example of recursion in C

Let's see an example to find the nth term of the Fibonacci series.

1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Memory allocation of Recursive method

Each recursive call creates a new copy of that method in the memory. Once some
data is returned by the method, the copy is removed from the memory. Since all the
variables and other stuff declared inside function get stored in the stack, therefore a
separate stack is maintained at each recursive call. Once the value is returned from
the corresponding function, the stack gets destroyed. Recursion involves so much
complexity in resolving and tracking the values at each recursive call. Therefore we
need to maintain the stack and track the values of the variables defined in the stack.

Let us consider the following example to understand the memory allocation of the
recursive functions.

1. int display (int n)


2. {
3. if(n == 0)
4. return 0; // terminating condition
5. else
6. {
7. printf("%d",n);
8. return display(n-1); // recursive call
9. }
10. }

Explanation

Let us examine this recursive function for n = 4. First, all the stacks are maintained
which prints the corresponding value of n until n becomes 0, Once the termination
condition is reached, the stacks get destroyed one by one by returning 0 to its calling
stack. Consider the following image for more information regarding the stack trace for
the recursive functions.
Storage Classes in C

Storage classes in C are used to determine the lifetime, visibility, memory location,
and initial value of a variable. There are four types of storage classes in C

o Automatic
o External
o Static
o Register

Storage Storage Default Scope Lifetime


Classes Place Value

auto RAM Garbage Local Within function


Value

extern RAM Zero Globa Till the end of the main


l program Maybe declared
anywhere in the program

static RAM Zero Local Till the end of the main


program, Retains value
between multiple
functions call

register Register Garbage Local Within the function


Value

Automatic

o Automatic variables are allocated memory automatically at runtime.


o The visibility of the automatic variables is limited to the block in which they are
defined.

The scope of the automatic variables is limited to the block in which they are
defined.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, an
d c.
8. return 0;
9. }

Output:

garbage garbage garbage


Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10. printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }

Output:

11 20 20 20 11
Static

o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which they
are defined.
o A same static variable can be declared many times but can be assigned at only
one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.

Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }

Output:

0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }

Output:

10 24
11 25
12 26

Register

o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator for
the register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the CPU
register. However, it is compiler?s choice whether or not; the variables can be
stored in the register.
o We can store pointers into the register, i.e., a register can store the address of a
variable.
o Static variables can not be stored into the register since we can not use more
than one storage specifier for the same variable.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
5. printf("%d",a);
6. }

Output:

0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the addr
ess of a register variable.
6. }

Output:

main.c:5:5: error: address of register variable ?a? requested


printf("%u",&a);
^~~~~~

External

o The external storage class is used to tell the compiler that the variable defined
as extern is declared with an external linkage elsewhere in the program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere in
the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only
once.
o If a variable is declared as external then the compiler searches for that variable
to be initialized somewhere in the program which may be extern or static. If it is
not, then the compiler will show an error.

Example 1
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }

Output

main.c:(.text+0x6): undefined reference to `a'


collect2: error: ld returned 1 exit status
Example 2
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to a
6. printf("%d",a);
7. }

Output

0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and ini
tializer at same time
6. printf("%d",a);
7. }

Output

compile time error


main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
1. #include <stdio.h>
2. int main()
3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized some
where in the pogram or not.
5. printf("%d",a);
6. }
7. int a = 20;

Output

20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line

Output

compile time error


Different aspects of function calling

A function may or may not accept any argument. It may or may not return any value.
Based on these facts, There are four different aspects of function calls.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value

Example 1

1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7. }
8. void printName()
9. {
10. printf("skycodes");
11. }

Output

Helloskycodes

Example 2

1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value

Example 1

1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }

Output

Going to calculate the sum of two numbers:


Enter two numbers 10 24
The sum is 34

Example 2: program to calculate the area of the square

1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }

Output

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000

Example for Function with argument and without return value

Example 1

1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34
Example 2: program to calculate the average of five numbers.

1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value

Example 1

1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }

Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }

Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even

You might also like