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

C Functions - Module II

Uploaded by

Kheerthna G
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

C Functions - Module II

Uploaded by

Kheerthna G
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Functions

Mrs.A.Reshma Parveen
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

Mrs.A.Reshma Parveen
Advantage of functions in C

There are the following advantages of C functions.


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

Mrs.A.Reshma Parveen
Function Aspects
There are three aspects of a C function.
• 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.
• 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.
• 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.
Mrs.A.Reshma Parveen
Function Aspects
Sno C function aspects Syntax
1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)


3 Function definition return_type function_name (argument list) {function body;}

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

return_type function_name(data_type parameter...)


{
//code to be executed
}

Mrs.A.Reshma Parveen
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.

Mrs.A.Reshma Parveen
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:
void hello()
{
printf("hello c");
}
• 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:
int get()
{
return 10;
}
Mrs.A.Reshma Parveen
Return Value
• 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.
float get()
{
return 10.2;
}

• Now, you need to call the function, to get the value of the function.

Mrs.A.Reshma Parveen
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.

• function without arguments and without return value

• function without arguments and with return value

• function with arguments and without return value

• function with arguments and with return value

Mrs.A.Reshma Parveen
Different aspects of function calling
• Example1 for Function without argument and without return value
#include<stdio.h>
void printName();
void main ()
{
printf("Hello "); Hello World
printName();
}
void printName()
{
printf(“ World");
}
Mrs.A.Reshma Parveen
Different aspects of function calling
• Example 2 for Function without argument and without return value
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Mrs.A.Reshma Parveen
Different aspects of function calling
• Example 1 for Function without argument and with return value
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Mrs.A.Reshma Parveen
Different aspects of function calling
• Example 2: program to calculate the area of the square
#include<stdio.h>
float square();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
float square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}

Mrs.A.Reshma Parveen
Different aspects of function calling
• Example for Function with argument and without return value
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

Mrs.A.Reshma Parveen
Assignment
• Write solution for below problem:
David got this end examination result this morning. He has 5 subjects in this examination and
each one is out of hundred. The pass mark for each subject is 40 marks. David scored 25 marks
above the pass mark in his language paper1 and 5 marks above pass mark in language2. He
scored 30 less from century in his science paper, 27 more than pass mark in maths, 13 less from
century in his social paper. He wants to know his grading as per below grading rule.
Grade ‘A’ – if percentage >=90
Grade B – if percentage from 80 to 89
Grade C – if percentage from 70 to 79
Grade D – if percentage from 60 to 69
Grade E – if percentage from 40 to 59
Fail – if percentage <40
Write a userdefined function named grade_calc() to do this calculation
by passing marks as arguments

Mrs.A.Reshma Parveen
Different aspects of function calling
• Example1 for Function with argument and with return value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

Mrs.A.Reshma Parveen
Different aspects of function calling
• Program to check whether a number is even or odd
#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{ printf("\nThe number is odd"); }
else
{ printf("\nThe number is even"); }
}
int even_odd(int n)
{
if(n%2 == 0)
{ return 1; }
else
{ return 0; }
}
Mrs.A.Reshma Parveen
C Library Functions
• Library functions are the inbuilt function 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 language. 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.

Mrs.A.Reshma Parveen
C Library Functions
SNo Header file Description
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
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.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.

Mrs.A.Reshma Parveen
Function Arguments
• If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
• Formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
• While calling a function, there are two ways in which arguments can be passed to a function −

Sr.No. Call Type & Description


1 Call by value- This method 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.

2 Call by reference- This method 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. This means that changes made to the parameter affect the argument.

Mrs.A.Reshma Parveen
Call by Value
There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.

Mrs.A.Reshma Parveen
Call by Value
•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.
•In call by value method, we can not modify the value of the actual parameter by the formal
parameter.
•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.
•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.

Mrs.A.Reshma Parveen
Call by Value

Mrs.A.Reshma Parveen
Call by Value x

100
Copy
num

100
#include<stdio.h> the value

void change(int num) ; 1155fh0 455500

int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
} Mrs.A.Reshma Parveen
Call by Value
• 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.
• By default, C programming uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function. 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;
}
Mrs.A.Reshma Parveen
Call by Value
#include <stdio.h>
void swap(int x, int y) {
/* function declaration */
void swap(int x, int y); int temp;

int main () { temp = x; /* save the value of x */


/* local variable definition */ x = y; /* put y into x */
int a = 100; y = temp; /* put temp into y */
int b = 200;
return;
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 */ Let us put this code in a single C file,
swap(a, b); compile and execute it, it will produce the
following result
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
Mrs.A.Reshma Parveen
Call by Reference
•In call by reference, the address of the variable is passed into the function call as the
actual parameter.
•The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
•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.

Mrs.A.Reshma Parveen
Call by Reference

Mrs.A.Reshma Parveen
Call by Reference x

200
num

1155fh0
#include<stdio.h>
void change(int *); 1155fh0 455500
int main() {
num=1155fh0
int x=100; *num=point to value in 1155fh0=200
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100; *num=*num+100
printf("After adding value inside function num=%d \n", *num);
}
Mrs.A.Reshma Parveen
Call 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.

To pass a value by reference, argument pointers are passed to the functions just like any other value. So
accordingly you need to declare the function parameters as pointer types as in the following
function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

/* 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;
}
Mrs.A.Reshma Parveen
Call by reference
#include <stdio.h>
void swap(int *,int *); void swap(int *x, int *y) {
int main () {
int temp;
/* local variable definition */
int a = 100; temp = *x; /* save the value of x */
int b = 200; *x = *y; /* put y into x */
*y = temp; /* put temp into y */
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b ); return;
}
/* calling a function to swap the values */
swap(&a, &b); Let us put this code in a single C file,
compile and execute it, it will produce the
printf("After swap, value of a : %d\n", a ); following result
printf("After swap, value of b : %d\n", b );

return 0;
}

Mrs.A.Reshma Parveen
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 the An address of value is passed into the function
function
2 Changes made inside the function is Changes made inside the function validate
limited to the function only. outside of the function also.
The values of the actual parameters do The values of the actual parameters do change
not change by changing the formal by changing the formal parameters.
parameters.

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

Mrs.A.Reshma Parveen
Difference between Actual Parameters and Formal Parameter

No. Actual Parameters Formal Parameter


1 The Actual Parameters are the values that The Formal parameters are the variables defined
are passed to function when it is by the function(at function definition) that receives
invoked(function call) values when function is called.

2 The actual parameters are passed by the The formal parameters are the called function or
calling function function definition

3 In Actual parameter there is no mentioning In Formal parameter the data types of the receiving
of data types only values or variable names values should be included.
is mentioned

Example: Example:
Void main() { Void main(int x,int y)
int a=10;b=20; {
display(a,b); Printf(“Sum is:%d”,x+y);
} }

Mrs.A.Reshma Parveen
Recursion
• 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.

Mrs.A.Reshma Parveen
Recursion

int main() {
recursion();
}

void recursion() {
recursion(); /* function calls itself */
}

Mrs.A.Reshma Parveen
Recursion
Example: Sum of Natural Numbers Using Recursion
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum = %d", result);
return 0;
}
int sum(int n)
{
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Mrs.A.Reshma Parveen
Recursion
Advantages and Disadvantages of Recursion
Advantages:
• The code becomes shorter and reduces the unnecessary calling to functions.
• Useful for solving formula-based problems and complex algorithms.
• Useful in Graph and Tree traversal as they are inherently recursive.
• Recursion helps to divide the problem into sub-problems and then solve them, essentially divide
and conquer.
Disadvantages:
• The code becomes hard to understand and analyze.
• A lot of memory is used to hold the copies of recursive functions in the memory.
• Time and Space complexity is increased.
• Recursion is generally slower than iteration.

Mrs.A.Reshma Parveen

You might also like