Unit III Function and Storage Classes
Unit III Function and Storage Classes
Library functions: Math functions, other miscellaneous functions such as getchar(), putchar(), malloc(),
calloc().
User defined functions - function definition, functions declaration, function call, scope of variables - local
variables, global variables.
Function parameters: Parameter passing- call by value & call by reference, Passing arguments to
Functions, Recursive functions. Storage classes-auto, register, static, extern, scope rules.
1. **Math Functions**: These functions are part of the `<math.h>` library in C and C++. Some
commonly used math functions include:
- `sin`, `cos`, `tan`: Trigonometric functions
- `exp`, `log`, `log10`: Exponential and logarithmic functions
- `sqrt`, `pow`: Square root and power functions
- `ceil`, `floor`: Ceiling and floor functions
- `abs`: Absolute value
- `round`, `trunc`: Rounding functions
Example:
```c
#include <math.h> double
result = sin(3.14);
```
2. **Character I/O Functions**: These functions handle character input and output operations. In C,
`getchar()` and `putchar()` are commonly used.
- `getchar()`: Reads a single character from standard input (usually the keyboard).
- `putchar()`: Writes a single character to standard output (usually the console).
Example:
```c
int ch = getchar();
putchar(ch);
```
3. **Dynamic Memory Allocation Functions**: These functions allow dynamic memory allocation
during runtime, managed through `<stdlib.h>`.
- `malloc()`: Allocates a block of memory of a specified size in bytes.
- `calloc()`: Allocates a block of memory for an array of elements, initialized to zero.
- `realloc()`: Resizes the previously allocated block of memory.
Example:
```c
#include <stdlib.h>
int *arr = malloc(10 * sizeof(int)); // Allocates memory for an array of 10 integers
```
These functions are essential in programming as they provide efficient and tested implementations for
tasks like mathematical calculations, character input/output, and memory management, saving developers
from having to implement these functionalities from scratch.
FUNCTIONS:
o A function is a block of code or set of statements that are used toperform a particular task
which repeatedly occurs in the main program.
o By using functions, we can divide complex problem into small components that makes
program easy to understand and use.
o A function is often executed several times, from several different places(sub function) during
the execution of the program.
o After executing the subprogram, the program control return back to main function.
Syntax Example
return-type function-name (parameter-list) int add(int x,int y)
{ {
body of function; int z;
} z=x+y;
return(z);
}
return Statement:
return type specifies the type of value(int, float, char, double) that function is expected to return to the program
calling the function.
It may or may not present send back result to calling function.
Syntax Example
return; return;
return(); return();
return(value); return(1);
return(variable); return(c);
Note:
Default data type is int.
Only one value can be returned to a function. Pointers are used to return more values.
If return (a,b,c) is used, only c value is returned to the function
Example:
Calling the function by simply specifying the function name, return value and parameters if present.
Syntax Example
return_variable= function_name(arg1, arg2, ….arg n); c=add(x,y);
Types of Arguments/Parameters:
Output:
globally declared values: m=10 n=10
locally declared values: m=20 n=20
without arguments and without return type without argument and with return type
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(); int my_add();
int main()
int main() {
{ int c;
int c; c=my_add();
c=my_add(); printf("sum is %d",c);
return(0); return(0);
} }
Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11
With argument and without return type With argument and with return type
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(int a,int b); int my_add(int a, int b);
Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11
Return Type:
S.no Result type Function
1 Integer strlen, strcmp,strcmpi
2 String strcat, strcpy, strrev, strupr, strlwr, strset, strnset
3 Address strchr, strnchr,strstr
This function returns the nearest integer which is less than or equal to the argument
floor ( ) passed to this function.
This function returns the nearest integer value that passed to this function. If
decimal value is from “.1 to .5”, it returns integer value less than the argument. If
decimal value is from “.6 to .9”, it returns the integer value greater than the
round() argument.
This function returns nearest integer value which is greater than or equal to the
ceil() argument passed to this function.
exp() This function is used to calculate the exponential “e” to the xth power.
sqrt() This function is used to find square root of the argument passed to this function.
trunk() This function truncates the decimal value from floating point value and returns
integer value.
The method of passing arguments by value is known as call by value. In this method, the values of
actual arguments are copied to the formal parameters of the function.
If the arguments are passed by value, the changes made in the values of formal parameter inside the
called function are not reflected back to the calling function.
Program:
#include<stdio.h>
#include<conio.h>
void swap(int a, int b);
void main()
{
a=10, b=20;
clrscr();
printf(“ Before swap %d%d”a,b);
swap(a,b);
printf(“After swap %d%d”,a,b);
getch();
}
int swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
printf(“In swap %d%d”,x,y);
}
Output:
Before swap 10 20
In swap 20 10
After swap 10 20
Program
#include<stdio.h>
#include<conio.h>
void swap(int a, int b);
void main()
{
a=10, b=20;
clrscr();
printf(“ Before swap %d%d”a,b);
swap(&a,&b);
printf(“After swap %d%d”,a,b);
getch();
}
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
printf(“In swap %d%d”,*x,*y);
}
Output:
Before swap 10 20
In swap 20 10
After swap 20 10
RECURSION FUNCTION:
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
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.
1.8 Recursion
A function that calls itself is known as recursion. Recursion is the process of calling the same function itself
again and again until base condition is satisfied.
Syntax:
Function1()
{
Function1();
}
The recursion continues until some condition is met .i,e it must have at least one if statement to
terminate the recursion.
Illustrative Program:
i) Computation of Sine series
ii) Scientific calculator using built-in functions (refer book page no 5.33)
iii) Binary Search using recursive functions .
For example,
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int f;
clrscr();
printf(“ enter a number”);
scanf(“%d”,&n);
f=fact(n);
printf(“Factorial of a given number is %d”,f);
getch();
}
int fact(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
Output:
enter a number
5
Factorial of a given number is
120
Sum of n numbers using recursive function
#include<stdio.h>
#include<conio.h>
int sum(int n);
void main()
{
int s;
clrscr();
printf(“ enter a number”);
scanf(“%d”,&n);
s=sum(n);
printf(“Sum of a given number is %d”,s);
getch();
}
int sum(int n)
{
if(n==1)
return 1;
else
return (n+sum(n-1));
}
Output:
enter a number
2
Sum of a given number is
3
Program to find power of a number using recursion:
#include<stdio.h>
#include<conio.h>
int powe(int,int);
void main()
{
int pow,num,result=0;
clrscr();
printf("enter the number and power");
scanf("%d%d",&num,&pow);
result=powe(num,pow);
printf("the power is %d",po);
getch();
}
int powe(int num,int pow)
{
int sum=num;
if(pow>1)
sum=num*powe(num,pow-1);
return sum;
}
OUTPUT
enter the number and power6
3
the power is 216
#include<stdio.h>
#include<conio.h>
#define size 10
intbinsearch(int[ ],int,int,int);
int main()
{
intnum,i,key,position;
intlow,high,list[size];
printf(“\n Enter the total number of elements:”);
scanf(“%d”,&num);
printf(“\n Enter the elements of list:”);
for(i=0;i<num;i++)
{
scanf(“%d”,&list[i]);
}
low=0;
high=num-1;
printf(“\n Enter element to be searched:”);
scanf(“%d”,&key);
position=binsearch(list,key,low,high);
if(position!= -1)
printf(“\n Number present at %d”,(position+1));
else
printf(“\n Number isnot present in the list:”);
return(0);
}
intbinsearch(int a[ ],intx,intlow,int high)
{
int mid;
if(low>high)
return -1;
mid=(low+high)/2;
if (x==a[mid])
return (mid);
else if(x<a[mid])
{
binsearch (a,x,low,mid-1);
else
binsearch (a,x, ,mid+1,high);
Output: }
Enter the total number of elements: 5
Enter the elements of list:3 5 2 6 7
Enter element to be searched: 2
Number present at:3