0% found this document useful (0 votes)
5 views31 pages

PPA Unit-6

Uploaded by

mohanpaul857
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views31 pages

PPA Unit-6

Uploaded by

mohanpaul857
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT-6

C - Functions

BCA-102 PPA Naveen Kumar

Subject Code Subject Faculty Name


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.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division is such that each function performs a
specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function.
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.

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


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

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Example
Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns
the maximum value between the two −
/* 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;
}

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


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 );
For the above defined function max(), the function declaration is as follows −
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);
Function declaration is required when you define a function in one source file and you call that function in
another file. In such case, you should declare the function at the top of the file calling the function.

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Calling a Function
While creating a C function, you give a definition of what the function has to do. To
use a function, you 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, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned
value. For example −
Subject Code 102 Subject PPA Faculty Name Naveen Kumar
#include <stdio.h> /* function returning the max between two numbers */
/* function declaration */ int max(int num1, int num2) {
int max(int num1, int num2); /* local variable declaration */
int main () { int result;
/* local variable definition */
int a = 100; if (num1 > num2)
int b = 200; result = num1;
int ret; else
/* calling a function to get max value */ result = num2;
ret = max(a, b); return result;
printf( "Max value is : %d\n", ret ); }
return 0;
} Subject Code 102 Subject PPA Faculty Name Naveen Kumar
Types of functions in C programming
Depending on whether a function is defined by the user or already included in C compilers, there are two types of functions in
C programming
There are two types of functions in C programming:
· Standard library functions
· User defined functions
Standard library functions
The standard library functions are built-in functions in C programming to handle tasks such as mathematical computations, I/O
processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions are available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output on the screen). This function is defined
in "stdio.h"header file.
There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(), getchar() etc. Once you
include "stdio.h" in your program, all these functions are available for use.

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by the user are called user-defined
functions.
Depending upon the complexity and requirement of the program, you can create as many user-defined functions as you want.
How user-defined function works?
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}

int main()
{
... .. ...
... .. ...

functionName();

... .. ...
... .. ...
}
Subject Code 102 Subject PPA Faculty Name Naveen Kumar
The execution of a C program begins from the main() function.
When the compiler encounters functionName(); inside the main function, control of the program jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside the function definition are
executed.
Remember, function name is an identifier
and should be unique.
This is just an overview on user-defined
function. Visit these pages to learn more
on:
·
User-defined Function in C program
ming
· Types of user-defined Functions

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Advantages of user-defined function
1. The program will be easier to understand, maintain and debug.
2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can
be divided among many programmers.
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
Subject Code 102 Subject PPA Faculty Name Naveen Kumar
a function −
Call Type & Description

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

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


By default, C 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.
Call by value and call by reference in C
There are two ways to pass value or data to function in C language: call by value and call by reference.
Original value is not modified in call by value but it is modified in call by reference.
Call by value in C
In call by value, original value is not modified.
In call by value, value being passed to the function is locally stored by the function parameter in stack
memory location. If you change the value of function parameter, it is changed for the current function only. It
will not change the value of variable inside the caller method such as main().

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Let's try to understand the concept of call by value in c language by the example given below:
#include <stdio.h>
#include <conio.h>
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);
}
int main() {
int x=100;
clrscr();
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
getch();
return 0;
}
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

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Difference between call by value and call by reference in c

No. Call by value Call by reference

1 A copy of value is passed to An address of value is


the function passed to the function

2 Changes made inside the Changes made inside the


function is not reflected on function is reflected outside
other functions the function also

3 Actual and formal Actual and formal


arguments will be created in arguments will be created in
different memory location same memory location

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Recursion
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you
to call a function inside the same function, then it is called a recursive call of the function.
void recursion() {
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers
need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop.

Recursive functions are very useful to solve many mathematical problems, such as calculating the factorial of a
number, generating Fibonacci series, etc.

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Number Factorial
The following example calculates the factorial of a given number using a recursive function −
#include <stdio.h>

int factorial(int i) {

if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}

int main() {
int i = 12;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Factorial of 12 is 479001600
Subject Code 102 Subject PPA Faculty Name Naveen Kumar
Fibonacci Series
The following example generates the Fibonacci series for a given number using a recursive function −
#include <stdio.h>

int fibonacci(int i) {

if(i == 0) {
return 0;
}

if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

int main() {

int i;

for (i = 0; i < 10; i++) {


printf("%d\t\n", fibonacci(i));
}

return 0;
}

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


When the above code is compiled and executed, it produces the
following result −
0
1
1
2
3
5
8
13
21
34

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Storage Classes in C
Storage classes are used to define scope and life time of a variable.
There are four storage classes in C programming.
· auto
· extern
· static
· register

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Storage Classes Storage Place Default Value Scope Life-time

auto RAM Garbage Value Local Within function

Till the end of main


extern RAM Zero Global program, May be declared
anywhere in the program
Till the end of main
program, Retains value
static RAM Zero Local
between multiple
functions call

register Register Garbage Value Local Within function

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


1) auto
The auto keyword is applied to all local Output:
variables automatically. It is the default 10 10
storage class that is why it is known as
automatic variable.
1. #include <stdio.h>
2. void main(){
3. int a=10;
4. auto int b=10;//same like above
5. printf("%d %d",a,b);
6. }
Subject Code 102 Subject PPA Faculty Name Naveen Kumar
2) register
The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster
access than other variables.
It is recommended to use register variable only for quick access such as in counter.
Note: We can't get the address of register variable.
1. register int counter=0;

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


3) static
The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

1. #include <stdio.h>

2. void func() {

3. static int i=0;//static variable

4. int j=0;//local variable

5. i++;

6. j++;

7. printf("i= %d and j= %d\n", i, j);

8. }

9. void main() {

10. func();

11. func();

12. func();

13. }

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


4) extern
The extern variable is visible to all the programs. It is used if two or more files are sharing same
variable or function.
1. extern int counter=0;

C - Scope of variables
A scope in any programming is a region of the program where a defined variable can have its existence and
beyond that variable it cannot be accessed. There are three places where variables can be declared in C
programming language −
· Inside a function or a block which is called local variables.
· Outside of all functions which is called global variables.
· In the definition of function parameters which are called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Subject Code 102 Subject PPA Faculty Name Naveen Kumar
Local Variables
Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to
functions outside their own. The following example shows how local variables are used. Here all the variables a, b, and c are local to main() function.
#include <stdio.h>

int main () {

/* local variable declaration */


int a, b;
int c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;

printf ("value of a = %d, b = %d and c = %d\n", a, b, c);

return 0;
}

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. The following program show how
global variables are used in a program.

#include <stdio.h>

/* global variable declaration */


int g;

int main () {

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}
A program can have same name for local and global variables but the value of local variable inside a function will take preference. Here is an
example −

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


#include <stdio.h>

/* global variable declaration */


int g = 20;

int main () {

/* local variable declaration */


int g = 10;

printf ("value of g = %d\n", g);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of g = 10

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


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 () {

/* local variable declaration in main function */


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;
}

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


/* 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

Subject Code 102 Subject PPA Faculty Name Naveen Kumar


UNIT-VI Complete

Subject Code 102 Subject PPA Faculty Name Naveen Kumar

You might also like