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

Functions IP Notes

Uploaded by

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

Functions IP Notes

Uploaded by

tejanandamuri152
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Functions in C

Introduction
 A function is a block of code that performs a specific task.
 When solving a big problem, it is broken down into smaller sub-problems to make it
easier to manage.
 In C programming, functions are used to break a large program into smaller,
manageable parts.
 Every C program must have a function called main(). Without the main() function, the
program cannot run.

 Every function in C has the following


 Function Declaration (Function Prototype)
 Function Definition
 Function Call
Function declaration
 A function declaration tells the compiler the function's name, return data type, and
parameters.
 It is also known as a function prototype.
 The function declaration can be placed before the main() function or inside any function.

 Syntax: returnType functionName(ParameterList);


Function definition
 A function definition contains the actual code of the function.
 It is also called the body of the function.
 The function's tasks are written inside the function definition.
 The instructions are placed within curly braces { }.
 The function definition can be placed either before or after the main() function.

Syntax: returnType functionName(ParameterList)


{
Statements; // function body
}
Function Call
 A function call tells the compiler to execute the function.
 When a function is called, the program jumps to the function's definition, executes the
code, and then returns to the function call.
 A function call can be made inside the main() function, any other function, or even
within the function itself.
 Syntax: functionName(ParameterList);
Function with Prototype
Syntax: Example:
#include<stdio.h> #include<stdio.h>
returnType functionName(parameters ); void message( );
void main() void main()
{ {
functionName(parameters ); message( );
} }
returnType functionName(parameters ) void message( )
{ {
Statements; // function body Printf(“Hello World”);
} }

Function without Prototype


Syntax: Example:
#include<stdio.h> #include<stdio.h>
returnType functionName(parameters ) void message( )
{ {
Statements; // function body printf(“Hello World”);
} }
void main() void main()
{ {
functionName(parameters ); message( );
} }

Function with parameters


 Parameters are variables declared in a function's signature to accept input values.
 Parameters are basically classified into two types. They are
1. Actual parameters
2. Formal parameters
Example:
#include<stdio.h>
void simpleInterest(float p,float t,float r); // function prototype
void main()
{
float p,t,r;
printf("Enter p,t,r values: ");
scanf("%f%f%f",&p,&t,&r);
simpleInterest(p,t,r); // calling function(Actual parameters)
}
void simpleInterest(float p,float t,float r) // called function( Formal parameters)
{
float si;
si=(p*t*r)/100;
printf("Simple Interest is: %.2f",si);
}

Functions advantages
 Functions allow for modular programming.
 Functions make the program more readable and easier to understand.
 Functions make program implementation simpler.
 Once created, a function can be used multiple times (code reusability).
 Functions help in breaking large programs into smaller, manageable modules.

Types of Functions in C
In C Programming Language, based on providing the function definition, functions are divided
into two types. Those are as follows...
 System Defined Functions
 User Defined Functions
System Defined Functions
 A system-defined function is a function whose definition is provided by the system.
 These are also known as Library Functions, Standard Functions, or Pre-Defined
Functions.
 Their implementation is provided in header files like stdio.h, math.h, etc.
 Example: printf() and scanf() are in the stdio.h header file.

Example Program
#include<stdio.h>
#include<math.h>
int main()
{
float x=36;
double d1=3.0,d2=2.0;
printf("%f\n",sqrt(x));
printf("%lf\n",pow(d1,d2));
return 0;
}
User Defined Functions
 A user-defined function is a function created by the user.
 In C programming, users can create their own functions, called user-defined functions.
 For example, the main() function is user-defined because the user writes it.
 User-defined functions are classified based on data flow:

 Without Parameters and without Return value


 With Parameters and without Return value
 Without Parameters and with Return value
 With Parameters and with Return value

Function without Parameters and without Return value


In this type of function, there is no data transfer between the calling function and the called
function. The program control simply jumps from the calling function to the called function,
executes the called function, and then returns to the calling function.

Example Program
#include <stdio.h>
void addition(); // Function declaration
int main()
{
addition(); // Calling function
return 0;
}
void addition()// Called function
{
int a, b;
printf("Enter any two integer numbers: ");
scanf("%d%d", &a, &b);
printf("Sum = %d\n", a + b);
}

Function with Parameters and without Return value


In this type of function, data is transferred from the calling function to the called function
through parameters, but no data is returned to the calling function. The program control jumps
from the calling function to the called function with the parameters, executes the called function,
and then returns to the calling function.

Example Program
#include <stdio.h>
void addition(int a, int b); // Function declaration
int main()
{
int a, b; // Using variables a and b
printf("Enter any two integer numbers: ");
scanf("%d%d", &a, &b);
addition(a, b); // Calling function
return 0;
}
void addition(int a, int b) // Function definition
{
printf("Sum = %d\n", (a + b));
}
Function without Parameters and with Return value
In this type of function, there is no data transfer from the calling function to the called function
(parameters), but there is data transfer from the called function to the calling function (return
value). The program control jumps from the calling function to the called function, executes the
called function, and then returns to the calling function along with a return value.

Example Program
#include <stdio.h>
int addition(); // Function declaration
int main()
{
I nt result;
result = addition(); // Calling function
printf("Sum = %d\n", result);
return 0;
}
int addition()// Called function
{
int a, b;
printf("Enter any two integer numbers: ");
scanf("%d%d", &a, &b);
return (a + b); // Return the sum of a and b
}
Function with Parameters and with Return value
In this type of function, there is data transfer from the calling function to the called function
(parameters) as well as from the called function to the calling function (return value). The
program control jumps from the calling function to the called function along with the parameters,
executes the called function, and then returns to the calling function with a return value.

Example Program
#include <stdio.h>
int addition(int a, int b); // Function declaration
int main()
{
int a, b, result;
printf("Enter any two integer numbers: ");
scanf("%d%d", &a, &b);
result = addition(a, b); // Calling function
printf("Sum = %d\n", result);
return 0;
}
int addition(int a, int b) // Called function
{
return (a + b); // Return the sum of a and b
}

Parameter Passing Methods in C

When a function is executed in a program, control transfers from the calling function to the
called function. This transfer may include data values, known as parameters. In C, there are two
types of parameters:

 Actual Parameters: The values specified in the calling function.


 Formal Parameters: The parameters declared in the called function.

When a function is executed, copies of the actual parameter values are assigned to the formal
parameters.

In C, there are two methods to pass parameters:

1. Call by Value

 In this method, a copy of the actual parameter values is made and used in the called
function.
 Changes made to the formal parameters do not affect the actual parameters.

Example Program:

#include <stdio.h>
void swap(int a, int b); // Function declaration
int main()
{
int a = 10, b = 20;
printf("\nBefore swap in main: a=%d, b=%d", a, b);
swap(a, b); // Calling function
printf("\nAfter swap in main: a=%d, b=%d", a, b);
return 0;
}
void swap(int a, int b) // Called function
{
int temp;
printf("\nBefore swap in swap: a=%d, b=%d", a, b);
temp = a;
a = b;
b = temp;
printf("\nAfter swap in swap: a=%d, b=%d", a, b);
}

2. Call by Reference

 In this method, the memory addresses of the actual parameters are passed to the called
function.
 The formal parameters must be pointer variables, allowing direct access to the actual
parameters.
 Changes made to the formal parameters will affect the actual parameters.

Example Program:

#include <stdio.h>
void swap(int *a, int *b); // Function declaration
int main()
{
int a = 10, b = 20; // Using variables a and b
printf("\nBefore swap in main: a=%d, b=%d", a, b);
swap(&a, &b); // Calling function
printf("\nAfter swap in main: a=%d, b=%d", a, b);
return 0;
}
void swap(int *a, int *b)
{
int temp;
printf("\nBefore swap in swap: a=%d, b=%d", *a, *b);
temp = *a; // Swap values using dereferencing
*a = *b;
*b = temp;
printf("\nAfter swap in swap: a=%d, b=%d", *a, *b);
}

Scope of Variables
The scope of a variable is the part of the program where it can be accessed. In C programming,
variables can be declared in two places:

1. Local Variables:

 Declared inside a function or block.


 Can only be used within that function or block.
 Exists only while the function is running; it is destroyed after the function
finishes.

Example:
int add()
{
int a = 4; // Local variable
int b = 5; // Local variable
return a + b;
}

Global Variables:

 Declared outside of all functions.


 Can be accessed by any function throughout the program.
 Holds its value for the entire program's duration, unless shadowed by a local variable
with the same name.

Example:
int a = 4, b = 5; // Global variables
int add()
{
return (a + b);
}

Storage Classes

 In the C programming language, storage classes are used to define things such as storage
location, scope, lifetime, and the default value of a variable.
 In C, the memory for variables is allocated either in computer memory (RAM) or in CPU
registers. The allocation of memory depends on the storage class.
 In C programming, there are four storage classes:
1. Automatic storage class
2. External storage class
3. Static storage class
4. Register storage class

Automatic storage class


The default storage class for all local variables is the automatic storage class. Variables with this
class have the following properties:
Property Description

Keyword auto (default; often omitted)

Storage Location Main Memory

Default Initial Value Garbage Value (uninitialized)

Scope Local to the block or function in which the variable is defined

Life time Exists only while the control remains within the block

Example:
#include <stdio.h>
void display()
{
auto int num = 10; // 'auto' is optional
printf("Inside display(): num = %d\n", num);
}
int main()
{
auto int a = 5;
printf("Inside main(): a = %d\n", a);
display();
return 0;
}
Register storage class
 The register storage class allocates variable memory in CPU registers, not RAM.
 Register variables provide faster access than other storage classes.
 Only a limited number of register variables can be used due to the few CPU registers
available.

Property Description

Keyword register

Storage Location CPU Register

Default Initial Value Garbage Value (uninitialized)

Scope Local to the block or function in which the variable is defined

Life time Exists only while the control remains within the block

Example:
#include <stdio.h>
int main()
{
register int count; // Register variable
for (count = 0; count < 3; count++)
{
printf("Count: %d\n", count);
}
return 0;
}

External storage class


The default storage class for all global variables (declared outside functions) is the external
storage class. Variables of this class have the following properties:

Property Description

Keyword extern

Storage Location Main Memory

Default Initial Value Zero

Scope Global to the program (accessible throughout)

Life time Until the end of the program

Example:
#include <stdio.h>
int count = 0; // Global variable
void increment()
{
count++;
}

int main()
{
printf("Count before: %d\n", count);
increment();
printf("Count after: %d\n", count);
return 0;
}

Static Storage Class

 The static storage class creates variables that retain their value until the program ends.
 Static variables are initialized only once but can be changed multiple times.

Property Description
Property Description

Keyword static

Storage Location Main Memory

Default Initial Value Zero

Scope Local to the block where the variable is defined

Life time Value persists between different function calls

Example:
#include <stdio.h>
void countCalls()
{
static int count = 0;
count++;
printf("Function called %d times\n", count);
}
int main()
{
countCalls();
countCalls();
countCalls();
return 0;
}
Recursive Functions
 The process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called as recursive function.
 Using recursion technique, certain mathematical problems can be solved quite easily.
 In recursive function, both calling function and called function are represented at one
place.

Syntax:
return_type function_name(parameters)
{
--------
--------
function_name(parameters);
}
Advantages:
 Reduce unnecessary calling of function.
 Through Recursion one can solve problems in easy way while its iterative solution is very
big and complex.
Program-1: /* Factorial Program using Recursion */
#include<stdio.h>
int factorial(int);
void main()
{
int n, fact;
printf("Enter any number:");
scanf("%d",&n);
fact =factorial(n);
printf("factorial of %d is: %d",n, fact);
}
int factorial(int n)
{
if(n==0)
return 1;
else if(n==1)
return 1;
else
return n*factorial(n-1);
}

Program-2: /*Fibonacci Series using Recursion*/


#include<stdio.h>
int Fibonacci(int);
void main()
{
int n, i = 0, c;
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", fibonacci(i));
i++;
}
}
int fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( fibonacci(n-1) + fibonacci(n-2) );
}
Passing Arrays as parameters to functions
If user wants to pass a single-dimension array as a parameter or an argument in a
function, user would have to declare a formal parameter in one of following three ways and all
three declaration methods produce similar results because each tells the compiler that an integer
pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal
parameters.
Way-1: Formal parameters as a pointer −
void myFunction(int *param)
{
Statements;
}
Way-2: Formal parameters as a sized array −
void myFunction(int param[10])
{
Statements;
}
Way-3: Formal parameters as an un-sized array −
void myFunction(int param[ ])
{
Statements;
}
Program: #include <stdio.h>
int function(int arr[], int size);
int main ()
{
int a[5]={10,20,30,40,50},result;
result = function(a,5);
printf( "Sum of array elements is: %d ",result);
return 0;
}
int function(int arr[], int size)
{
int i,sum=0;
for(i=0;i<size;i++)
{
sum=sum+arr[i];
}
return sum;
}

You might also like