C Programming Module 3-Function
C Programming Module 3-Function
Function
*
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. 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.
A single procedure can be developed for reuse, eliminating the need to retype the
code many times.
Programs can be designed more easily because a small team deals with only a small
part of the entire code.
Modular programming allows many programmers to collaborate on the same
application.
The code is stored across multiple files.
Code is short, simple and easy to understand and modify, make simple to figure out
how the program is operate and reduce likely hood of bugs.
Errors can easily be identified, as they are localized to a subroutine or function or
isolated to specific module.
The same code can be reused in many applications.
The scoping of variables and functions can easily be controlled.
Disadvantages
However it may takes longer to develop the program using this technique.
There are basically two types of function those are
1) Library function
Library functions are the in-built function in C programming system.
a. main ( )
b. printf ( )
c. scanf ( )
*
d. strcpy ( )
e. strcat ( )
f. strcmp ( )
are the examples of Library functions available in C.
2. User defined function
C allows programmer to define their own function according to their requirement. These
types of functions are known as user-defined functions.
• 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.
Calling a function
Function with return and without return can be called to using the different syntax.
add (a, b) ; // calling function without return
c=add (a, b); // calling function without return
*
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
Actual Parameters/argument
*
The arguments which are mentioned or used inside the function call is knows as actual
argument and these are the original values and copy of these are actually sent to the
called function It can be written as constant, expression or any function call like
Function (x);
Function (20, 30);
Function (a*b, c*d);
Function(2,3,sum(a, b));
Formal Parameters/Arguments
The arguments which are mentioned in function definition are called formal arguments
or dummy arguments.
These arguments are used to just hold the copied of the values that are sent by the
calling function through the function call.
These arguments are like other local variables which are created when the function call
starts and destroyed when the function ends.
The basic difference between the formal argument and the actual argument are
The formal argument are declared inside the parenthesis whereas the local
variable declared at the beginning of the function block.
The formal argument are automatically initialized when the copy of actual
arguments are passed while other local variable are assigned values through the
statements.
Order number and type of actual arguments in the function call should be
matchwith the order number and type of the formal arguments.
Return type
*
It is used to return value to the calling function. It can be used in two way as
return
Or return(expression);
Ex:-
return (a);
return (a*b);
return (a*b+c);
Here the 1st return statement used to terminate the function without returning anyvalue
Ex:-
/*summation of two values*/
int sum (int a1, int a2);
void main()
{
int a,b,s;
printf(“enter two no”);
scanf(“%d%d”,&a,&b);
s=sum(a,b);
printf(“summation is = %d”,s);
}
int sum(intx1,int y1)
{
int z;
z=x1+y1;
return z;
}
Any function can be called by another function even main() can be called by otherfunction.
main()
*
{
function1()
}
function1()
{
Statement;
function2;
}
function 2()
{
}
So every function in a program must be called directly or indirectly by the main()
function. A function can be called any number of times.
A function can call itself again and again and this process is called recursion.
A function can be called from other function but a function can’t be defined in
another function
*
Category of Function based on argument and return type
This type of function has arguments and always returns a value. In this method, the arguments
are passed to the function while calling it. The function will return some value when it is called
from main() or any subfunction in the program. In it, data types are a must to define. If the
return is of 'int' type, then the return value will also be 'int' type. This type of user-defined
function is also called a fully dynamic function because the total control is in the hand of the
end-user.
#include <stdio.h>
void main()
{
int sub(int,int); // return value and arguments of function
int a=15,b=7;
int result = sub(a,b);
printf("a-b = %d",result);
}
int sub(int x,int y) // return value and arguments of function
{
return(x-y); // this is return value,'int type'
}
Output:
a-b = 8
In this type of function, the arguments are also passed to the function while calling it. But it
will not return any value when the function is called from the main function or any submethod.
This function contains arguments but does not return any value. In this method, we allow the
user to enter the values as input rather than fixed values. Since we are allowing the user to
enter the values as input, we do not expect any return type value. This type of function can be
used in real-life problems. Let us take an example where the user will enter two values as input
and these values will be passed to the user-defined function, which will do addition.
*
#include<stdio.h>
Sum = x + y;
Output:
Explanation:
Integer variables x and y are declared inside the main function. Then we called the "Add" with
contains user-entered values. In the "Add(x,y)", there are integer variables of 'Sum' also integer
(x,y) is present as arguments in this function. So, it will allow the user to pass two values as an
'integer'. Then, x and y are added using the + operator and 'printf' is used to print the result.
*
c) Functions without Arguments and with Return Values
In this type of user-defined function, we do not pass any arguments when we define, declare or
call a function. But, this type of function returns some value when it is called from the main()
function or any submethod in the program. In it, the data type of return value is dependent on
the return type of the declaration function. Suppose, if the return type is of 'int' then the return
value will be also of int type. Let us see an example where we will write a program to multiply
two integers without arguments and a return keyword.
#include<stdio.h>
int Multiply();
int main()
{
int Mul;
Mul = Multiply(); // no argument passed
printf("\n The multiplication of x and y is = %d \n", Mul );
return 0;
}
int Multiply()
{
int Mul, x = 5, y = 10;
Mul = x * y;
return Mul;
}
Output:
In the above example, we can see there are no arguments passed in "Multiply". But it is
returning the value as int type as "Mul".
In this type of user-defined function, we do not pass any arguments when we define, declare or
call a function. Also, this function does not return any values when it is called from
the main() function or any submethod inside the program. This type of function is used when
*
we do not expect any return value but we need some statement to print the result as output.
Since this function has no arguments and returns a value, it does not receive any data when the
function is called.
#include<stdio.h>
// Declaration
void Add();
void main()
{
Add();
}
void Add()
{
int Sum, x = 15, y = 50;
Sum = x + y;
Output:
Output
2. Call by reference
Instead of passing the value of variable, address or reference is passed and the function
operate on address of the variable rather than value.
Here formal argument is alter to the actual argument, it means formal arguments calls
the actual arguments.
Example:-
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
*
}
Output
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. The values outside of the function also. The values of
of the actual parameters do not change by the actual parameters do change by
changing the formal parameters. changing the formal parameters.
3 Actual and formal arguments are created Actual and formal arguments are created
at the different memory location at the same memory location
Recursion:
Recursion, in general, can be defined as the repetition of a process in a similar way until the
specific condition reaches. In C Programming, if a function calls itself from inside, the same
function is called recursion. The function which calls itself is called a recursive function, and
the function call is termed a recursive call. The recursion is similar to iteration but more
complex to understand. If the problem can be solved by recursion, that means it can be solved
by iteration. Problems like sorting, traversal, and searching can be solved using recursion.
While using recursion, make sure that it has a base (exit) condition; otherwise, the program
will go into the infinite loop.
Recursive case: The part of code inside the recursive function executed repeatedly while
calling the recursive function is known as the recursive case.
int main()
{
The function call inside the main function is normal call, it calls the recursive_fun() function
inside which there is another function call recursive_fun(); which is termed as recursive call
and the whole recursive_fun() function is recursive function. Base_case is the stopping
condition for the recursive function.
#include<stdio.h>
int fibonacci_01(int i) {
if (i == 0)
{
return 0;
}
if (i == 1)
*
{
return 1;
}
int main() {
int i, n;
printf("Enter a digit for fibonacci series: ");
scanf("%d", & n);
return 0;
}
Output:
#include<stdio.h>
int factorial_01(int n)
{
if(n == 0)
return 1;
else
return (factorial_01(n-1)*n);
}
int main()
{
*
int a fact;
fact = factorial_01(a);
printf("Factorial of %d = %d",a,fact);
return 0;
}
Output:
1. floor (double a)
This function returns the largest integer value not greater than ‘a’ value. It rounds a value and
returns a double as a result. It behaves differently for negative numbers, as they round to the
next negative number.
Example:
This program illustrates how to compute the floor for the declared value and rounds to the next
value 10.
#include <stdio.h>
*
#include <math.h>
int main()
double f= -9.33;
int final;
final = floor(f);
return 0;
}
2. ceil ()
Syntax:
Example:
This program explains by taking input in the float argument and returns the ceil value.
*
#include <stdio.h>
#include <math.h>
int main()
float n, ceilVal;
scanf("%f", &n);
ceilVal = ceil(n);
return 0;
}
3. Sqrt ()
This function returns the square root of a specified number.
Syntax:
sqrt( arg)
Example:
*
The below code explains the most known mathematical function sqrt() by taking ‘n’ values to
compute the square root for the different ‘n’ values.
#include <stdio.h>
#include <math.h>
int main()
double n,output;
printf("Enter a number\n");
scanf("%lf", &n);
output = sqrt(n);
4. round ()
This function rounds the nearest value of a given input. It throws out the error if the value is
too large. Other functions like lround (), llround () also rounds the nearest integer.
*
Syntax:
int round(arg)
Example:
The below code is very simple which does round off to the nearest ‘r’ value in the for loop.
#include <stdio.h>
#include <math.h>
int main ()
for(double r=110;r<=120;r+=1.1)
*
5.pow ()
This function returns to power for the given number(ab). It returns a raised to the power of b,
which has two parameters base and exponent.
Example:
In the Below source code, we are allowing a user to enter an input value to compute the power
of the given two arguments.
#include <stdio.h>
#include <math.h>
int main()
r = pow(ba, expr);
return 0;
}
*
6. trun()
This function helps in truncating the given value. It returns integer values. To truncate floating
and double values truncf (), truncl () are used.
Syntax:
double trunc(a);
Example:
Below source code takes two input values a, b to truncate the double values.
#include <stdio.h>
#include <math.h>
void main() {
double m, n, a, b;
a = 56.16;
b = 85.74;
m = trunc(a);
n = trunc(b);
*
7. fmod()
This function returns the remainder for the given two input values when m divided by n.
Syntax:
Example:
In the below example it takes two values from the user to compute the remainder using fmod()
function.
#include<stdio.h>
#include<math.h>
int main(){
double fiN;
double secN;
double n;
scanf("%lf",&fiN);
*
printf("Enter the second number : ");
scanf("%lf",&secN);
Trigonometric Functions
Below are the different functions of Trigonometric:
1. sin()
This built-in function gives sine value of the given number, calculates floating-point values.
asin() computes arc, for hyperbolic it is sinh().
Syntax:
Example:
In the following source code, I have taken two different input values to calculate sin value and
returns double.
#include <stdio.h>
*
#include <math.h>
int main()
double a;
double z;
a = 4.3;
z = sin(a);
a = -4.3;
z = sin(a);
a = 45;
z = sin(a);
return 0;
}
*
2. sinh()
This math function computes trigonometric tangent sine value for the given number.
Syntax:
double sinh(x);
Example
In the below source code Sine hyperbolic is calculated by declaring an input value.
#include <stdio.h>
#include <math.h>
#define PI 3.141592654
int main()
double gt = 3.60, z;
z = sinh(gt);
return 0;
}
*
3. cos()
This math function determines the trigonometric cosine value for the given element.
Syntax:
Example
#include <stdio.h>
#include <math.h>
#define PI 3.14
int main()
{
double cVal, rVal, dVal;
for(int i=0;i<=2;i++)
scanf("%lf", &dVal);
cVal = cos(rVal);
printf("\n");
return 0;
*
4. cosh()
It returns hyberbolic cosine for a given value.
Syntax:
double cosh(y);
Example
The below example shows it takes two different input values to compute hyperbolic.
#include <stdio.h>
#include <math.h>
int main ()
double k, r;
k = 0.6;
r = cosh(k);
*
printf("Hyperbolic cosine of %lf is = %lf\n", k, r);
k = -0.8;
r = cosh(k);
5. tan()
This math library function calculates tangent values of the angle for the mathematical
It can be declared as
double tan(arguments);
Example
In the following source code, tan value is calculated for the following angles which is
incremented using for loop.
# include <stdio.h>
# include <conio.h>
*
# include <math.h>
void main()
float z ;
int k ;
char ch ;
z = k * 3.14159 / 180 ;
getch() ;
}
*
6. tanh()
tanh() function returns hyperbolic tangent of the given value. It takes a single parameter. In
addition to find tangent for long double and float tanhl() and tanhf () are used for computation.
Syntax:
Example:
A tangent hyberbolic is calculated for ‘ j’ values using for loops. Let’s see how it works.
#include <stdio.h>
#include <math.h>
#define PI 3.141592654
int main()
double val, r;
r = tanh(j);
printf("\n");
return 0;
*
}
1. exp()
This function does computation on exponential for a given value(ex). There are also other
subtypes like frexp(), Idexp() returning mantissa and multiplied to the power of x.
Syntax:
Example:
The program takes numeric value from the user to compute the exponent for a given value and
returns double.
#include <stdio.h>
#include <math.h>
int main()
*
{
scanf("%lf", &numb);
eVal = exp(numb);
printf("\n");
return 0;
}
2. log()
This function returns the logarithm value of a given number. (to the base e. log e)
Syntax:
double log(arg);
Example:
In the following example, log value for the given number is calculated using function. User-
defined function lgm() does computation and function is called in the main function.
#include<stdio.h>
#include<math.h>
*
float lgm ( float iv );
int main ()
float q, r ;
r = lgm ( q ) ;
float exe ;
exe = log(iv);
return ( exe ) ;
}
*
List of C ctype.h Library Functions Programs
1) isalnum()
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
if (isalnum(ch))
printf("%c is an alphanumeric character.\n", ch);
else
printf("%c is not an alphanumeric character.\n", ch);
return 0;
}
Output:
First run:
Enter a character: H
H is an alphanumeric character.
Second run:
Enter a character: %
% is not an alphanumeric character.
2) isalpha()
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (isalpha(ch))
printf("%c is an alphabet.\n", ch);
else
printf("%c is not an alphabet.\n", ch);
return 0;
}
Output:
First run:
Enter a character: Y
Y is an alphabet.
Second run:
Enter a character: 9
9 is not an alphabet.
3) isdigit()
#include <stdio.h>
#include <ctype.h>
int main()
*
{
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (isdigit(ch))
printf("%c is a digit.\n", ch);
else
printf("%c is not a digit.\n", ch);
return 0;
}
Output:
First run:
Enter a character: Y
Y is not a digit.
Second run:
Enter a character: 9
9 is a digit.
4) isspace()
5) isupper()
6) islower()
*
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (isupper(ch))
printf("%c is an uppercase character.\n", ch);
else if (islower(ch))
printf("%c is an lowercase character.\n", ch);
else if (isspace(ch))
printf("%c is space.\n", ch);
else
printf("%c is none from uppercase, lowercase and space.\n", ch);
return 0;
}
Output:
First run:
Enter a character: T
T is an uppercase character.
Second run:
Enter a character: t
t is an lowercase character.
Third run:
Enter a character: main
m is an lowercase character.
Fourth run:
Enter a character:
*
is space.
Fifth run:
Enter a character: *
* is none from uppercase, lowercase and space.
7) ispunct()
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
Output:
First run:
Enter a character: !
! is a punctuation character.
Second run:
*
Enter a character: ,
, is a punctuation character.
Third run:
Enter a character: +
+ is a punctuation character.
8) isprint()
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
if (isprint(ch))
printf("%c is a printable character.\n", ch);
else
printf("%c is not a printable character.\n", ch);
return 0;
}
Output:
Enter a character: x
x is a printable character.
9) toupper()
*
This function returns character in upper case.
10) tolower()
#include <stdio.h>
#include <ctype.h>
int main()
{
char ch;
Output:
First run:
Enter a character: w
Upper case: W, Lower case: w
Second run:
Enter a character: 9
Upper case: 9, Lower case: 9
Storage Classes in C
*
Storage class in c language is a specifier which tells the compiler where and how tostore
variables, its initial value and scope of the variables in a program. Or
attributes of variable is known as storage class or in compiler point of view a variable
identify some physical location within a computer where its string of bits value can be
stored is known as storage class.
The kind of location in the computer, where value can be stored is either in the
memory or in the register. There are various storage class which determined, in
which of the two location value would be stored.
Syntax of declaring storage classes is:-
storageclass datatype variable name;
There are four types of storage classes and all are keywords:- 1 )
1)Automatic (auto)
2 ) Register (register)
3) Static (static)
4 ) External (extern)
Examples:-
auto float x; or float x;
extern int x;
register char c;
static int y;
*
how long would variable exists.
1. Automatic storage class
The keyword used to declare automatic storage class is auto. Its
features:-
Storage-memory location
Default initial value:-unpredictable value or garbage value.
Scope:-local to the block or function in which variable is defined.
Life time:-Till the control remains within function or block in which it is defined. It
terminates when function is released.
The variable without any storage class specifier is called automatic variable.
Example:-
main( )
{
auto int i;
printf(“i=”,i);
}
*
Variable stored in register storage class always access faster than, which is always
stored in the memory. But to store all variable in the CPU register is not possible
because of limitation of the register pair.
And when variable is used at many places like loop counter, then it is better todeclare it
as register class.
Example:-
main( )
{
register int i;
for(i=1;i<=12;i++)
printf(“%d”,i);
}
*
reduce( )
{
static int x=10;
printf(“%d”,x);
x++;
}
Output:-10,11,12
Declaration does not create variables, only it refer that already been created at
somewhere else. So, memory is not allocated at a time of declaration and the external
variables are declared at outside of all the function.
Example:-
int i,j;
void main( )
{
printf( “i=%d”,i );receive( ); receive ( ); reduce( );
reduce( );
}
receive( )
*
{
i=i+2;
printf(“on increase i=%d”,i);
}
reduce( )
{
i=i-1;
printf(“on reduce i=%d”,i);
}
Output:-i=0, 2,4,3,2.
When there is large program i.e divided into several files, then external variable should
be preferred. External variable extend the scope of variable.