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

Unit III Function and Storage Classes

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

Unit III Function and Storage Classes

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

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.

Library functions play a crucial role in programming by providing ready-made solutions to


common tasks. Here's a brief overview of some categories of library functions:

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.

Functions are Classified into two types:

(i) User defined functions:


 User-defined functions are those functions which are defined(written) by the user according to
their requirements.
 Users have full scope to implement their own ideas in the function.
 Examples: add (), sub (), mul()
How function works?
1. Once the function is called from main
function, it takes some data to the sub
function(called function)
2. When the program control is passed to
sub function, working of main function is
temporarily stopped.
3. Once the execution of sub function is
completed, again program control returns
back to main function(calling function).

Elements of user defined function:( Components)


1. Function declaration or prototype
2. Function definition
3. Function call
(i) Function Declaration:
- Likevariableand an array, a functionmust also bedeclaredbefore it is called.
- A function declaration tells the compiler about a function name and how to call the
function.
Syntax Example
return-type function-name (parameter-list) ; int add(int x, int y);

Return type: int, char, float, void


Function name: specifies the name of the function.
Parameter list: list of variables with data type separated by comma
(ii) Function Definition (function-body)
The function bodycontains following 3 parts.
Bodyis enclosed within curly braces {}.
 Local variable declaration.
 Execution statement that performs specific task.
 return statement that return the value evaluated by the 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:

int add(int x, int y) // function definition


{
int z; //local declaration
z=x +y //execution statement
return(z); //returnstatement
}
Note:
If a function does not return any value, then keyword void must be used as return type while declaring
function definition.

(iii) Function Call:

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

Simple Program to add two numbers using function: Output:


#include<stdio.h> enter two numbers
int add(int,int); 5
int main() 6
{ The sum is 11
int a,b,c;
printf("enter two numbers\n");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("The sum is %d",c);
return(0);
}
int add(int x,int y)
{
int z;
z=x+y;
return(z);
}

Types of Arguments/Parameters:

Actual parameter – Parameters transferred from calling function(main function) to called


function(function definition)
Formal Parameters - Parameters transferred to calling function(main function) from called
function(function definition)
Example:
Global And Local Variable:
Local Variables: Global Variable:
 Defined within the body of the function.  Defined outside the main function.
 Other functions cannot access these  These variables can be used throughout the
variables. program.

Program using global and local variable:


#include<stdio.h>
void test();
int m = 10, n =10 ; // global
variable int main()
{
printf("globally declared values: m=%d n=%d\n", m,n);
test();
}
void test()
{
int m=20,n=20; // local variable
printf("locally declared values: m=%d n=%d\n:",m,n);
}

Output:
globally declared values: m=10 n=10
locally declared values: m=20 n=20

FUNCTION PROTOTYPES: ( CATEGORIES OF FUNCTION)

1. Without arguments and without return type


2. Without arguments and with return type
3. With arguments and without return type
4. With arguments and with return type
1. Without arguments and without return type
o There is no data transfer between calling and the called function.
o The called function is used to perform any operation. They work independently.
o They read the data values and print the results in same block.
2. Without arguments and with return type
o In this type of function , no argument are passed through the main() function. But the
called function returns the values to the main function.
o Thecalledfunctionisindependent.
3. With argument and without return type:
oIn this type the arguments are passed through the function call.
o The called function operates on the values. But no result is sent back.
4. With argument and with return type( fruitful function)
o In this type the arguments are passed through the function call.
o The result is sent back to the main function.

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

void my_add(int x,int y) int my_add(int x,int y)


{ {
int z; int z;
printf("enter the values "); printf("enter the values ");
scanf("%d\n%d",&x,&y); scanf("%d%d",&x,&y);
z=x+y; z=x+y;
printf("sum is %d",z); return(z);
} }

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

int main() int main()


{ {
int a,b; int a,b,c;
printf("enter the values "); printf("enter the values ");
scanf("%d%d",&a,&b); scanf("%d%d",&a,&b);
my_add(a,b); c=my_add(a,b);
return(0); printf("sum is %d",c);
} return(0);
}
void my_add(int x,int y) int my_add(int x,int y)
{ {
int z; int z;
z=x+y; z=x+y;
printf("sum is %d",z); return(z);
} }

Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11

Calculator Program: ( with argument and with return type)


#include<stdio.h> Output:
int my_add(int a,int b); enter a,b values
int my_sub(int a,int b); 4
int my_mul(int a,int b); 3
float my_div(int a,int b); the sum is: 7
the dif is: 1
int main() the product is: 12
{ the division is: 1.000000
int a,b,c;
float d;
printf("enter a,b values\n");
scanf("%d%d",&a,&b);
c=my_add(a,b);
printf("the sum is: %d\n",c);
c=my_sub(a,b);
printf("the dif is: %d\n",c);
c=my_mul(a,b);
printf("the product is: %d\n",c);
d=my_div(a,b);
printf("the division is: %f\n",d);
return(0);
}

int my_add(int x,int y)


{
int z;
z=x+y;
return(z);
}
int my_sub(int x,int y)
{
int z;
z=x-y;
return(z);
}
int my_mul(int x,int y)
{
int z;
z=x*y;
return(z);
}
float my_div(int x,int y)
{
float z;
z=x/y;
return(z);
}

Benefits of Using Functions


 Reduction in code redundancy
 Enabling codereuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability
 Powerful programming tool

BUILT-IN FUNCTIONS ( STANDARD LIBRARY FUNCTIONS)


Built-in functions are nothing but predefined functions or library functions.
These functions are defined by C library.
Example printf(), scanf(), strcat() etc.
Various standard library functions and a macro defined under:
- math.h to perform mathematical operations
- String.h Perfoms All String Operations

String Built-In Functions:


String.h header file supports all the string functions in C language.
Some of the string library functions are given below.

Function Purpose Syntax


strlen Calculates the length of the string s. strlen(str1);
strcmp Compares two strings. strcmp(str1, str2);
strcmpi Compares two strings without case sensitive. Strcmpi(str1,str2);
strcat Appendsthecopyofthestringsrc totheendofthe string dest. strcat(str1, str2);
strcpy Copies the source string src to the destination string strcpy(str1,str2);
dest.
strrev Reverse the content of the string s. strrev(str1);
strlwr Converts the string to lowercase. strlwr(str1);
strupr Converts the string to uppercase. strupr(str1);
strset Set all character in a string s to the character ch. strset(str1,ch);
strnset Setthefirstncharacterinastringstothecharacter ch. Strnset(str1,ch,n);
strchr Scansastringforthefirstoccurrenceofthegiven character. strchr(str1,ch);
strrchr Scansastringforthelastoccurrenceofthegiven character. strrchr(str1,ch);
strstr Scansastringforthefirstoccurrenceofthesubstring in anotherstring. strstr(str1,ch);

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

Math Built-In Functions:

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.

sin() This function is used to calculate sine value.

cos() This function is used to calculate cosine.

cosh() This function is used to calculate hyperbolic cosine.

exp() This function is used to calculate the exponential “e” to the xth power.

tan() This function is used to calculate tangent.

tanh() This function is used to calculate hyperbolic tangent.

sinh() This function is used to calculate hyperbolic sine.

log() This function is used to calculates natural logarithm.

log10() This function is used to calculates base 10 logarithm.

sqrt() This function is used to find square root of the argument passed to this function.

pow() This is used to find the power of the given number.

trunk() This function truncates the decimal value from floating point value and returns
integer value.

Program using different math built-in functions: Output:


#include<stdio.h> floor of 5.4 is 5.000000
#include<math.h> round of 5.4 is 5.000000
int main() ceil of 5.4 is 6.000000
{ The value of sin(3.014) : 0.127247
printf("floor of 5.4 is %f\n", floor(5.4)); The value of cos(3.014) : -0.991871
printf("round of 5.4 is %f\n", round(5.4)); The value of tan(3.014) : -0.128290
printf("ceil of 5.4 is %f\n", ceil(5.4)); The value of sinh(0.25) : 0.252612
printf("The value of sin(3.014) : %f \n", sin(3.014)); The value of cosh(0.25) : 1.031413
printf("The value of cos(3.014) : %f \n", cos(3.014)); The value of tanh(0.25) : 0.244919
printf("The value of tan(3.014) : %f \n", tan(3.014)); The value of log(6.25) : 1.832581
printf("The value of sinh(0.25) : %f \n", sinh(0.25)); The value of log10(6.25) : 0.795880
printf("The value of cosh(0.25) : %f \n", cosh(0.25)); The value of exp(6.25) : 6.250000
printf("The value of tanh(0.25) : %f \n", tanh(0.25)); sqrt of 16 = 4.000000
printf("The value of log(6.25) : %f \n", log(6.25)); 5 power 3 = 125.000000
printf("The value of log10(6.25) : %f \n",log10(6.25));
printf("The value of exp(6.25) : %f \n",6.25);
printf ("sqrt of 16 = %f\n", sqrt (16) );
printf ("5 power 3 = %f\n", pow (5, 3) );
return(0);
}

CALL BY VALUE AND CALL BY REFERENCE

The argument passing methods in c language are classified as:

1. Call by value or pass by value.


2. Call by reference or pass by address.

Call by value (or) pass by 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

Call by reference (or) pass by address

 The Method of passing arguments by address is known as call by reference.


 In this method, the addresses of the actual arguments are passed to the formal parameters of the
function. If the arguments are passed by reference, the changes made in the formal parameters are
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();
}
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();
}

How Recursion Function Works?

The recursion continues until some condition is met .i,e it must have at least one if statement to
terminate the recursion.

A Recursion Function must have the following statements:


- A statement to test whether function is calling itself again.
- A statement that calls the function itself must be an argument
- A conditional statement( if-else)
- A return statement
Advantages of recursion:
- Recursion makes program simple and ease
- All algorithms can be defined recursively which makes it easier to visualize and prove.
Disadvantages of recursion:
- Recursions use more memory and are generally slow. Instead, you can use loop.
Program Output

Program to find factorial of a given number: enter a number 5


#include<stdio.h> Factorial of a given number is
int fact(int n); 120
int main()
{
int f,n;
printf(" enter a number");
scanf("%d",&n);
f=fact(n);
printf("Factorial of a given number is %d",f);
return(0);
}
int fact(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
Program to compute GCD of two given numbers enter two integers
#include<stdio.h> 6
int gcd(int x,int y); 12
int main() gcd of two numbers is :6
{
int a,b;
printf("enter two integers\n"); scanf("%d
%d",&a,&b);
printf("gcd of two numbers is :%d %d\n",gcd(a,b));
return(0);
}
int gcd(int x,int y)
{
if(y!=0)
return gcd(y,x%y);
else
return(x);
}
To find Sum of n numbers using recursion function : Enter a positive integer: 3
#include <stdio.h> sum=6
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
Sum of N numbers –How Recursive Function works.

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 .

Conputation of Sine Series:


Sine Series is a series which is used to find the value of Sin(x).
where, x is the angle in degree which is converted to Radian.

The formula used to express the Sin(x) as Sine Series is


Expanding the above notation, the formula of Sine Series is

For example,

Let the value of x be 30.

So, Radian value for 30 degree is 0.52359.

So, the value of Sin(30) is 0.5.

Computation of Sine Series Output


#include<stdio.h> Enter the value for x : 30
int main() Enter the value for n : 5
{ The value of Sin(0.523598) = 0.5000
int i, n;
float x, sum, t;
printf(" Enter the value for x : ");
scanf("%f",&x);
printf(" Enter the value for n : ");
scanf("%d",&n);
x=x*3.14159/180;
t=x;
sum=x;
/* Loop to calculate the value of Sine */
for(i=1;i<=n;i++)
{
t=(t*(-1)*x*x)/(2*i*(2*i+1));
sum=sum+t;
}
printf(" The value of Sin(%f) = %.4f",x,sum);
}

Binary Search Using Recursion Output:


#include <stdio.h> enter the element to search
int binarySearch(int arr[], int left, int right, int x) 75
{ Element is present at index 3
if (right >= left)
{
int mid = left + (right - left)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, left, mid-1, x);
return binarySearch(arr, mid+1, right, x);
}
return -1;
}
int main(void)
{
int arr[]= {25,35,50,75,100};
int x, result;
int n = sizeof(arr)/ sizeof(arr[0]);
printf("enter the element to search");
scanf("%d",&x);
result = binarySearch(arr, 0, n-1, x);
if (result ==-1)
printf("Element is not present in array");
else
printf("Element is present at index %d",result);
return 0;
}

Factorial using recursive function

#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

Program Binary Search using recursive function:

#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

You might also like