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

User Defined Functions

The document discusses different types of functions in C programming. It states that there are two main categories of functions - library functions and user-defined functions. Library functions are predefined in C libraries and user-defined functions are defined by the user. It then provides more details on the components of user-defined functions, including function declaration, definition, call. It also lists the four categories of user-defined functions based on whether they have arguments and return values or not. Benefits of using functions like modularity and reusability are also mentioned.

Uploaded by

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

User Defined Functions

The document discusses different types of functions in C programming. It states that there are two main categories of functions - library functions and user-defined functions. Library functions are predefined in C libraries and user-defined functions are defined by the user. It then provides more details on the components of user-defined functions, including function declaration, definition, call. It also lists the four categories of user-defined functions based on whether they have arguments and return values or not. Benefits of using functions like modularity and reusability are also mentioned.

Uploaded by

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

C functions can be classified into two categories,

1. Library functions
2. User-defined functions

Library functions are those functions which are already defined in


C library, example printf(), scanf(), strcat() etc. You just need to
include appropriate header files to use these functions. These are
already declared and defined in C libraries.

A User-defined functions on the other hand, are those functions


which are defined by the user at the time of writing program. These
functions are made for code reusability and for saving time and
space.

A function is a block of code that performs a specific task. C allows


you to define functions according to your need.
These functions are known as user-defined functions

There are many situations where we might need to write same line
of code for more than once in a program. This may lead to
unnecessary repetition of code, bugs and even becomes boring for
the programmer. So, C language provides an approach in which
you can declare and define a group of statements once in the form
of a function and it can be called and used whenever required.

These functions defined by the user are also know as User-


defined Functions

Benefits of Using Functions

1. It provides modularity to your program's structure.


2. It makes your code reusable. You just have to call the
function by its name to use it, wherever required.
3. In case of large programs with thousands of code lines,
debugging and editing becomes easier if you use functions.
4. It makes the program more readable and easy to
understand.
Components/Element of user defined function
In order to make use of a user defined function, we need to establish
three elements of user defined functions which are as follows

1. Function Declaration
2. Function Definition
3. Function call

Function Declaration

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

Example :-

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 Definition

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
return statement
}

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

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

Function call
When a function is called, control of the program gets transferred to
the function.

functionName(argument1, argument2,...);

Example : - add(a,b);
categories of functions in c

There can be 4 different types of user-defined functions, they are:

1. Function with no arguments and no return value.


2. Function with no arguments and a return value.
3. Function with arguments and no return value.
4. Function with arguments and a return value.

To understand the above four categories we will see the example of addition
Function with no arguments and no Function with no arguments and a return
return value. value

int Add()
void Add() {
{ int Sum, a = 10, b = 20;
int Sum, a = 10, b = 20; Sum = a + b;
Sum = a + b;
return (sum);
printf("%d",Sum); }
}

void main()
void main() {
{ int z;
Add(); // Function call z=Add(); // Function call
} printf(“%d”,z);
}

Function with arguments and no return Function with arguments and a return
value. value.
int Add(int x, int y )
void Add(int x, int y ) {
{ int Sum;
int Sum; Sum = x + y;
Sum = x + y;
return (Sum);
printf("%d",Sum); }
}

void main()
void main() {
{ int z, a = 10, b = 20;
int a = 10, b = 20 z=Add(a,b); // Function call
Add(a,b); // Function call printf(“%d”,z);
} }
Example :-
Printing n Natural numbers (Identify the category of function ? )

#include< stdio.h>
#include< conio.h>
void nat( int);
void main()
{
int n;
clrscr();
printf("\n Enter n value:");
scanf("%d",&n);
nat(n);
getch();
}

void nat(int n)
{
int i;
for(i=1;i<=n;i++)
printf("%d\t",i);
}
Output:
Enter n value: 5
12345
Example :-
#include< stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n;
clrscr();
printf("\n Enter n:");
scanf("%d",&n);
printf("\n Factorial of the number : %d", fact(n));
getch();
}

int fact(int n)
{
int i,f;
for(i=1,f=1;i<=n;i++)
f=f*i;
return(f);
}
#include< stdio.h>
#include< conio.h>
int sum();
void main()
{
int s;
clrscr();
printf("\n Enter number of elements to be added :");
s=sum();
printf("\n Sum of the elements :%d",p);
getch();
}

int sum()
{
int a[20], i, s=0,n;
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i< n; i++)
scanf("%d",& a[i]);
for(i=0;i< n; i++)
s=s+a[i];
return s;
}
Write a Program That print answer of following series using nested
function :-

12 + 22 +32 …………….n2
Recursion :-

void recursion()
{
recursion(); /* function calls itself */
}

int main()
{
recursion();
}
Factorial of a Number Using Recursion

#include <stdio.h>
long int multiplyNumbers(int n);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
passing array to the function in c

Passing array elements to a function is similar to passing variables to a function.

Example :1

#include <stdio.h>
void display(int age1, int age2)
{
printf("%d\n", age1);
printf("%d\n", age2);
}
int main()
{
int ageArray[] = {2, 8, 4, 12};
// Passing second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}
Passing arrays to functions

#include <stdio.h>
float calculateSum(float age[]);
int main()
{
float result, age[ ] = {23.4, 55, 22.6, 3, 40.5, 18};
// age array is passed to calculateSum()
result = calculateSum(age);
printf("Result = %f", result);
return 0;
}
float calculateSum(float age[ ])
{
float sum = 0.0;
for (int i = 0; i < 6; ++i)
{
sum += age[i];
}
return sum;
}
Passing two-dimensional arrays

#include <stdio.h>
void displayNumbers(int num[2][2]);
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
scanf("%d", &num[i][j]);
// passing multi-dimensional array to displayNumbers function
displayNumbers(num);
return 0;
}

void displayNumbers(int num[2][2])


{
// Instead of the above line,
// void displayNumbers(int num[][2]) is also valid
int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]);
}
Output

Enter 4 numbers:

Displaying:

5
Passing Strings to Functions
Strings can be passed to a function in a similar way as
arrays.

#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
gets(str);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
Storage Classes in C

auto: This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can
be only accessed within the block/function they have been declared and not outside them (which
defines their scope).

extern: Extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used. Basically, the value is assigned to it in a different block
and this can be overwritten/changed in a different block as well. So an extern variable is nothing
but a global variable initialized with a legal value where it is declared in order to be used elsewhere

static: This storage class is used to declare static variables which are popularly used while
writing programs in C language. Static variables have a property of preserving their value even
after they are out of their scope! Hence, static variables preserve the value of their last use in their
scope. So we can say that they are initialized only once and exist till the termination of the
program.

register: This storage class declares register variables which have the same functionality as
that of the auto variables. The only difference is that the compiler tries to store these variables in
the register of the microprocessor if a free register is available. This makes the use of register
variables to be much faster than that of the variables stored in the memory during the runtime of
the program. If a free register is not available, these are then stored in the memory only.
// A C program to demonstrate different storage
// classes
#include <stdio.h>

// declaring the variable which is to be made extern


// an intial value can also be initialized to x
int x;

void autoStorageClass()
{

printf("\nDemonstrating auto class\n\n");

// declaring an auto variable (simply


// writing "int a=32;" works as well)
auto int a = 32;

// printing the auto variable 'a'


printf("Value of the variable 'a'"
" declared as auto: %d\n",
a);

printf("--------------------------------");
}

void registerStorageClass()
{

printf("\nDemonstrating register class\n\n");

// declaring a register variable


register char b = 'G';

// printing the register variable 'b'


printf("Value of the variable 'b'"
" declared as register: %d\n",
b);

printf("--------------------------------");
}

void externStorageClass()
{

printf("\nDemonstrating extern class\n\n");

// telling the compiler that the variable


// z is an extern variable and has been
// defined elsewhere (above the main
// function)
extern int x;
// printing the extern variables 'x'
printf("Value of the variable 'x'"
" declared as extern: %d\n",
x);

// value of extern variable x modified


x = 2;

// printing the modified values of


// extern variables 'x'
printf("Modified value of the variable 'x'"
" declared as extern: %d\n",
x);

printf("--------------------------------");
}

void staticStorageClass()
{
int i = 0;

printf("\nDemonstrating static class\n\n");

// using a static variable 'y'


printf("Declaring 'y' as static inside the loop.\n"
"But this declaration will occur only"
" once as 'y' is static.\n"
"If not, then every time the value of 'y' "
"will be the declared value 5"
" as in the case of variable 'p'\n");

printf("\nLoop started:\n");

for (i = 1; i < 5; i++) {

// Declaring the static variable 'y'


static int y = 5;

// Declare a non-static variable 'p'


int p = 10;

// Incrementing the value of y and p by 1


y++;
p++;

// printing value of y at each iteration


printf("\nThe value of 'y', "
"declared as static, in %d "
"iteration is %d\n",
i, y);

// printing value of p at each iteration


printf("The value of non-static variable 'p', "
"in %d iteration is %d\n",
i, p);
}

printf("\nLoop ended:\n");

printf("--------------------------------");
}

int main()
{

printf("A program to demonstrate"


" Storage Classes in C\n\n");

// To demonstrate auto Storage Class


autoStorageClass();

// To demonstrate register Storage Class


registerStorageClass();

// To demonstrate extern Storage Class


externStorageClass();

// To demonstrate static Storage Class


staticStorageClass();

// exiting
printf("\n\nStorage Classes demonstrated");

return 0;
}

You might also like