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

Function

The document discusses functions in C programming. It defines what a function is, explains the need for functions, and covers function declaration, definition, types of functions, passing arguments to functions, and calling functions.

Uploaded by

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

Function

The document discusses functions in C programming. It defines what a function is, explains the need for functions, and covers function declaration, definition, types of functions, passing arguments to functions, and calling functions.

Uploaded by

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

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 can also be referred as a method or a sub-routine or a


procedure, etc.

We can divide up our code into separate functions. How we divide up


our code among different functions is up to us, but logically the
division is such that each function performs a specific task.

Example: main()
Need of Function
1. REUSABILITY.

Once a function is defined, it can be used over and over and over again.
We can invoke the same function many times in our program, which saves
our work.
Example: Imagine what programming would be like if we had to teach the
computer about square root function every time we needed to find the
square root of a number.

Another aspect of reusability is that a single function can be used in


several different (and separate) programs. When we need to write a new
program, we can go back to our old programs, find the functions we need,
and reuse those functions in your new program.

NOTE:: We can also reuse functions that somebody else has written for
us, such as the sqrt, sine and cosine functions.
Contd..
2. ABSTRACTION

In order to use a particular function we need to know the following things:


1. The name of the function.
2. What the function does.
3. What arguments you must give to the function, and
4. What kind of result the function returns.

NOTE : If we just want to use the function in our program, we don't have to
know how it works inside! We don't have to understand anything about what
goes on inside the function.

Example : It's sort of like driving a car or using a telephone. With an


automobile, we don't need to understand every detail about the engine and
drive train and wheels, if all we want to do is drive the car. Similarly, with a
telephone, we don't have to understand everything about the phone system
in order to make a call.
Contd..
• C functions are used to avoid rewriting same logic/code again and again in a
program.

• There is no limit in calling C functions to make use of same functionality


wherever required.

• We can call functions any number of times in a program and from any place
in a program.

• A large C program can easily be tracked when it is divided into functions.

• The core concept of C functions are, re-usability, dividing a big task into
small pieces to achieve the functionality and to improve understandability of
very large C programs.
Types of functions in C

There are two types of functions in C programming:


Standard Library Function
User Defined Function
Standard library functions

The standard library functions are built-in functions in C programming to


handle tasks such as mathematical computations, I/O processing, string
handling etc.

These functions are defined in the header file. When you include the header
file, these functions are available for use.

Example:
The printf() is a standard library function to send formatted output to the
screen (display output on the screen). This function is defined in "stdio.h"
header file.

There are other numerous library functions defined under "stdio.h", such as
scanf(), fprintf(), getchar() etc.
Once you include "stdio.h" in your program, all these functions are available for
use.
User-defined functions
How user-defined function works?

C allow programmers to define


functions. Such functions created by
the user are called user-defined
functions.

Depending upon the complexity and


requirement of the program, you can
create as many user-defined
functions as you want.
Advantages of user-defined function :
• The program will be easier to understand, maintain and debug.
• Reusable codes that can be used in other programs
• A large program can be divided into smaller modules. Hence, a large
project can be divided among many programmers.
Flow of program :
The execution of a C program begins from
the main() function.

When the compiler


encounters functionName(); inside the
main function, control of the program
jumps to
1
void functionName()
and, then the compiler starts executing the
codes inside the user-defined function.
2

The control of the program jumps to


statement next to functionName(); once
all the codes inside the function definition
are executed.
Function Declaration
Function declaration also called as function prototyping is a declaration statement in
the calling program.

A function declaration describes the function interface to the compiler by giving


details such as return-type, function name, argument list and terminating semicolon

SYNTAX : Return-type function-name(argument-list);

The argument-list contains the types and names of arguments that must be passed to
the function.
Example: int max(int x, int y);

NOTE:
 Each argument must be declared independently inside the parenthesis.
 In a function declaration names of arguments are dummy variables and therefore
are optional.
Example: int max(int, int);
Function Definition
A function definition provides the actual body of the function.

SYNTAX : Return-type function-name (argument-list)


{
function-body;
}

A function definition in C programming consists of a function header and a function body.

Return-type − A function may return a value. function-name − This is the actual


The return-type is the data type of the value the name of the function. The function
function returns. Some functions perform the desired name and the parameter list
operations without returning a value together constitute the function
argument − A argument/parameter is like a signature.
placeholder. When a function is invoked, you
pass a value to the parameter. This value is function-body − The function body
referred to as actual parameter or argument. containsa collection of statements
The parameter list refers to the type, order, and that define what the function does.
number of the parameters of a function.
Parameters are optional; that is, a function may
contain no parameters.
Function Definition Note: While defining a
function, there is no
A function definition provides the actual body of the function.
semicolon(;) after the
parenthesis in the
SYNTAX : Return-type function-name (argument-list)
function header, unlike
{
while declaring the
function-body;
function or calling the
}
function.
A function definition in C programming consists of a function header and a function body.

Return-type − A function may return a value. function-name − This is the actual


The return-type is the data type of the value the name of the function. The function
function returns. Some functions perform the desired name and the parameter list
operations without returning a value together constitute the function
signature.
argument − A argument/parameter is like a
placeholder. When a function is invoked, you pass a function-body − The function body
value to the parameter. This value is referred to as contains a collection of statements
actual parameter or argument. The parameter list that define what the function does.
refers to the type, order, and number of the
parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
Example
Given below is the source code for a function called max().
This function takes two parameters num1 and num2 and returns the maximum value
between the two −

/* function returning the max between two numbers */


int max(int num1, int num2)
{
int result; /* local variable declaration */
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Return type: int


Function Name: max
Parameter : num1, num2
Calling a function
 While creating a C function, we give a definition of what the function has
to do. To use a function, we will have to call that function to perform the
defined task.

 When a program calls a function, the program control is transferred to the


called function.

 A called function performs a defined task and when its return statement is
executed or when its function-ending closing brace is reached, it returns
the program control back to the main program.

 To call a function, we simply need to pass the required parameters along


with the function name, and if the function returns a value, then we can
store the returned value.

Example: int res=max(1,2);


Passing arguments to a function

Function Declaration

Function Calling

Function Defining
Passing arguments to a function
• In programming, argument refers to the variable
passed to the function. In the given example, two
variables n1 and n2 are passed during function
call.

• The parameters a and b accepts the passed


arguments in the function definition. These
arguments are called formal parameters of the
function.

• The type of arguments passed to a function and


the formal parameters must match, otherwise the
compiler throws error.

• If n1 is of char type, a also should be of char type.


If n2 is of float type, variable b also should be of
float type.

• A function can also be made without passing any


argument by leaving argument place blank
Return Statement
• The return statement terminates the
execution of a function and returns a value
to the calling function.

• The program control is transferred to the


calling function after return statement.

• The type of value returned from the


function and the return type specified in
function prototype and function definition
must match.

• Syntax : return (expression);

• In the given example, the value of


variable result is returned to the
variable sum in the main() function, both
should be of the same data type.
Arguments
Argument: An argument is an expression which is passed to a function by its
caller in order for the function to perform its task.
It is an expression in the comma-separated list bound by the parentheses in a
function call expression
Function Arguments

Actual Arguments Formal Arguments

 The formal arguments are the parameters/


 The arguments that are
arguments in a function declaration.
passed in a function call
 The scope of formal arguments is local to the
are called actual
function definition in which they are used.
arguments.
 Formal arguments belong to the called
 These arguments are
function.
defined in the calling
 Formal arguments are a copy of the actual
function
arguments.
 A change in formal arguments would not be
reflected in the actual arguments.
Example

Actual Argument

Formal
Argument
Types of User-defined Functions
Function with no arguments and no return value
//checks whether it is a prime number or not and displays it on the screen.
#include <stdio.h>
void checkPrimeNumber();
int main()
{
checkPrimeNumber(); // no argument is passed to prime()
return 0;
}
/*return type of the function is void no value is returned from the function */
void checkPrimeNumber() {
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
{ flag = 1; break; }
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
Function with no arguments and no return value

#include <stdio.h>
void checkPrimeNumber();
int main() { •The checkPrimeNumber() function
// no argument is passed to prime() takes input from the user, checks
checkPrimeNumber(); whether it is a prime number or not
return 0; } and displays it on the screen.
/*return type of the function is void
no value is returned from the function */
void checkPrimeNumber() •The empty parentheses in
{ int n, i, flag=0; checkPrimeNumber(); statement
printf("Enter a positive integer: "); inside the main() function indicates
scanf("%d",&n); that no argument is passed to the
for(i=2; i <= n/2; ++i) { function.
if(n%i == 0) { flag = 1; break; }
} •The return type of the function
if (flag == 1) is void. Hence, no value is returned
printf("%d is not a prime number.", n);
from the function.
else
printf("%d is a prime number.", n);
}
No arguments passed but a return value
#include <stdio.h> int getInteger() {
int getInteger(); int n;
int main() { printf("Enter a positive integer: ");
int n, i, flag = 0; scanf("%d",&n);
n = getInteger(); return n;
for(i=2; i<=n/2; ++i) }
{
if(n%i==0)
{ The empty parentheses in n = getInteger();
flag = 1; statement indicates that no argument is
break; passed to the function and, the value
} returned from the function is assigned to n.
}
if (flag == 1) Here, the getInteger() function takes
printf("%d is not a prime number.", n); input from the user and returns it.
else
printf("%d is a prime number.", n);
return 0;
}
Argument passed but no return value
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main()
{ int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
checkPrimeAndDisplay(n); // n is passed to the function
return 0;
}
// void indicates that no value is returned from the function
void checkPrimeAndDisplay(int n) {
int i, flag = 0;
for(i=2; i <= n/2; ++i) {
if(n%i == 0) {
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Argument passed but no return value
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main() {
int n;
The integer value entered by the user is
printf("Enter a positive integer: ");
passed to checkPrimeAndDisplay()
scanf("%d",&n);
function.
checkPrimeAndDisplay(n);
Here, the checkPrimeAndDisplay()
return 0;
function checks whether the argument
}
passed is a prime number or not and
void checkPrimeAndDisplay(int n) {
displays the appropriate message.
int i, flag = 0;
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
{ flag = 1; break; }
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Argument passed and a return value
#include <stdio.h>
int checkPrimeNumber(int n);
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
flag = checkPrimeNumber(n); // n is passed to the checkPrimeNumber() function the value
returned from the function is assigned to flag variable
if(flag==1)
printf("%d is not a prime number",n);
else printf("%d is a prime number",n);
return 0;
}
int checkPrimeNumber(int n) { // integer is returned from the function
int i; /* Integer value is returned from function checkPrimeNumber() */
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
return 1;
}
return 0; }
Argument passed and a return value
#include <stdio.h>
int checkPrimeNumber(int n);
int main() { •The input from the user is passed to
int n, flag; checkPrimeNumber() function.
•The checkPrimeNumber() function
printf("Enter a positive integer: ");
checks whether the passed argument
scanf("%d",&n); is prime or not.
flag = checkPrimeNumber(n); •If the passed argument is a prime
if(flag==1) number, the function returns 0.
printf("%d is not a prime number",n); •If the passed argument is a non-prime
number, the function returns 1.
else printf("%d is a prime number",n);
•The return value is assigned to flag
return 0; } variable.
int checkPrimeNumber(int n) { •Then, the appropriate message is
int i; displayed from the main() function.
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
return 1; }
return 0; }
Argument passing in function
While calling a function, there are two ways in which arguments can be
passed to a function −
1. Call by value
2. Call by reference
Call by Value
• In call by value method, the value of the variable is passed to the
function as parameter.
• The value of the actual parameter can not be modified by formal
parameter.
• Different Memory is allocated for both actual and formal parameters.
Because, value of actual parameter is copied to formal parameter.
• Note:
• Actual parameter – This is the argument which is used in function
call.
• Formal parameter – This is the argument which is used in function
definition
Example
 In this program, the values of the variables “a” and “b” are passed to the function “swap”.
 These values are copied to formal parameters “x” and “y” in swap function and used.

#include<stdio.h>
int swap(int , int); //Declaration of function
int main( )
{
int a = 10, b = 20 ; // a and b are actual parameters
swap(a,b); // call by value
printf ( "\n a = %d b = %d", a, b ) ;
} Output:
int swap( int x, int y ) // x and y are formal parameters x=20 y=10
{ a=10 b=20
int t ;
t=x;
x=y;
y=t;
printf ( "\nx = %d y = %d", x, y ) ;
}
Call by Reference
• In call by reference method, the address of the variable is passed to the
function as parameter.
• The value of the actual parameter can be modified by formal parameter.
• Same memory is used for both actual and formal parameters since only
address is used by both parameters.

EXAMPLE (USING CALL BY REFERENCE):


• In this program, the address of the variables “m” and “n” are passed to the
function “swap”.
• These values are not copied to formal parameters “a” and “b” in swap
function.
• Because, they are just holding the address of those variables.
• This address is used to access and change the values of the variables.
Example
#include<stdio.h>
int swap(int * , int *); //Declaration of function
main( )
{
int a = 10, b = 20 ; // a and b are actual parameters
swap(&a,&b); // call by reference
printf ( "\n a = %d b = %d", a, b ) ;
}
int swap( int *x, int * y ) // x and y are formal parameters Output:
{ x=20 y=10
int t ; a=20 y=10
t =* x ;
*x = *y ;
*y = t ;
printf ( "\nx = %d y = %d", *x, *y ) ;

}
Scope of variables
 A scope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable it cannot be accessed

 There are three places where variables can be declared in C programming


language −
I. Inside a function or a block which is called local variables.
II. Outside of all functions which is called global variables.
III. In the definition of function parameters which are called formal
parameters.
Local Variables
 Variables that are declared inside a function or block are called local
variables.
 They can be used only by statements that are inside that function or block of
code.
 Local variables are not known to functions outside their own.
 The following example shows how local variables are used. Here all the
variables a, b, and c are local to main() function.

include <stdio.h>
int main () {
int a, b,c; /* local variable declaration */
a = 10; b = 20; /* actual initialization */
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Global Variables
 Global variables are defined outside a function, usually on top of the
program.
 Global variables hold their values throughout the lifetime of your program
and they can be accessed inside any of the functions defined for the
program.
 A global variable can be accessed by any function. That is, a global variable
is available for use throughout your entire program after its declaration.
 The following program show how global variables are used in a program.

#include <stdio.h>
int g; /* global variable declaration */
int main ()
{
int a, b; /* local variable declaration */
a = 10; b = 20; /* actual initialization */
g=a+b
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Local and Global Variables
 A program can have same name for local and global variables but the value of
local variable inside a function will take preference.
 Here is an example −

#include <stdio.h>
/* global variable declaration */
int g = 20;
Output:
int main () { value of g = 10
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
return 0;
}
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they
take precedence over global variables.
Following is an example −

#include <stdio.h>
int a = 20; /* global variable declaration */
int main ()
{
int a = 10; int b = 20; int c = 0; /* local variable declaration in main */
printf ("value of a in main() = %d\n", a);
c = sum( a, b); /* a & b are actual parameter */
printf ("value of c in main() = %d\n", c);
return 0;
}
int sum(int a, int b) /* function to add two integers */
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
Formal Parameters
#include <stdio.h>
int a = 20;
int main ()
{
int a = 10; int b = 20; int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
Initializing Local and Global Variables
 When a local variable is defined, it is not initialized by the system, you must
initialize it yourself.
 Global variables are initialized automatically by the system when you define them
as follows:

Data Type Initial Default Value


int 0
char '\0'
float 0
double 0
pointer NULL

 It is a good programming practice to initialize variables properly, otherwise your


program may produce unexpected results, because uninitialized variables will take
some garbage value already available at their memory location.
Storage class specifier
Storage class specifiers in C language tells the compiler where to store a
variable, how to store the variable, what is the initial value of the variable
and life time of the variable.

Syntax: storage-specifier datatype variable _name;

TYPES OF STORAGE CLASS SPECIFIERS IN C:


There are 4 storage class specifiers available in C language.
1. auto
2. extern
3. static
4. register
Auto
 Auto variables are stored in CPU Memory.

 Initial/default value of the variable is garbage value.

 All variables defined within a function or block by default belong to


automatic storage class if no storage class is mentioned.

 Auto variables have local scope ie. can be accessed within the
function or block it is declared.

 It has function life only.

 Variables having automatic storage class are local to the block which
they are defined in, and get destroyed on exit from the block.
Example

Output:
0000
Extern
 Extern variables are stored in CPU Memory.
 Initial/default value of the variable is 0.
 Extern variables have global scope ie. Can be accessed from anywhere in
the program.
 It exists till the end of the main program. Variable definition might be
anywhere in the C program.
 The principal use of extern is to specify that a variable is declared
with external linkage elsewhere in the program.
 When extern specifier is used with a variable declaration then no storage is
allocated to that variable and it is assumed that the variable has already been
defined elsewhere in the program.
 When we use extern specifier the variable cannot be initialized because
with extern specifier variable is declared, not defined.
Example

Output:
The value of x is 10
The value of y is 50
Static
 Static variables are stored in CPU Memory.
 Initial/default value of the variable is 0.
 Static variables have local scope ie. Can be accessed within the function or
block it is declared.
 Retains the value of the variable between different function calls.
 It has program lifetime.
 The static specifier gives the declared variable static storage class. Static
variables can be used within function or file.
 Unlike global variables, static variables are not visible outside their function
or file, but they maintain their values between calls.
 The static specifier has different effects upon local and global variables.
When static specifier is applied to a local variable inside a function or block,
the compiler creates permanent storage for it, much as it creates storage for
a global variable but static local variable remains visible only to the function
or block in which it is defined.
 In simple terms, a static local variable is a local variable that retains its
value between function calls.
Example

Output:
0123
Register
 The register specifier declares a variable of register storage class.
Register variables are stored in register Memory.
 Initial/default value of the variable is garbage value.
 Register variables have local scope ie. Can be accessed within the function
or block it is declared.
 Variables belonging to register storage class are local to the block which
they are defined in, and get destroyed on exit from the block.
 It has function lifetime.
 A register declaration is equivalent to an auto declaration, but hints
that the declared variable will be accessed frequently; therefore they
are placed in CPU registers, not in memory.
 Only a few variables are actually placed into registers, and only certain
types are eligible; the restrictions are implementation-dependent.
 However, if a variable is declared register, the unary & (address of)
operator may not be applied to it, explicitly or implicitly.
Note
 For faster access of a variable, it is better to go for register specifiers rather
than auto specifiers.

 Because, register variables are stored in register memory whereas auto


variables are stored in main CPU memory.

 Only few variables can be stored in register memory. So, we can use
variables as register that are used very often in a C program.

 But, only limited variables can be used as register since register size is very
low. (16 bits, 32 bits or 64 bits)
Example
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Passing Array to function
 In C programming, a single array element or an
entire array can be passed to a function.
 This can be done for both one-dimensional array or a
multi-dimensional array.
 If we want to pass a single-dimension array as an
argument in a function, we would have to declare a
formal parameter in one of following three ways.
 All three declaration methods produce similar results
because each tells the compiler that an integer pointer
is going to be received.
 Similarly, we can pass multi-dimensional arrays as
formal parameters
Way 1
Formal parameters as a pointer −
void myFunction(int *param)
{.....
.....
.....
}
Way 2
Formal parameters as a sized array −

void myFunction(int param[10])


{ ......
.......
.... ..
}
Way 3
Formal parameters as an unsized array −

void myFunction(int param[])


{......
. . . . .. .
. . . … ..
}
Example
Passing One-Element of Array In Function
Single element of an array can be passed in similar manner as passing variable
to a function.

#include <stdio.h>
void display(int age)
{
printf("%d", age);
}
int main()
{
int ageArray[] = { 2, 3, 4 };
display(ageArray[2]);
return 0;
}
Example
Passing an entire one-dimensional array to a function
Now, consider the following function, which takes an array as an argument
along with another argument and based on the passed arguments, it returns the
average of the numbers passed through the array as follows −

#include <stdio.h>
double getAverage(int arr[], int size);
int main () {
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage( balance, 5 ) ;
printf( "Average value is: %f ", avg );
return 0; }
double getAverage(int arr[], int size) {
int i; double avg; double sum = 0;
for (i = 0; i < size; ++i)
{ sum += arr[i]; }
avg = sum / size; return avg;
}
Example
Passing an entire one-dimensional array to a function
While passing arrays as arguments to the function, only the name of the array is
passed (,i.e, starting address of memory area is passed as argument).

#include <stdio.h>
float average(float age[]);
int main()​
{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age);
printf("Average age=%.2f", avg);
return 0;
}
float average(float age[]) {
int i; float avg, sum = 0.0;
for (i = 0; i < 6; ++i)
{ sum += age[i]; }
avg = (sum / 6);
return avg; }
Example
Passing Multi-dimensional Arrays to Function :To pass two-dimensional array to a
function as an argument, starting address of memory area reserved is passed as in one
dimensional array.

#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]);
displayNumbers(num);
return 0; }
void displayNumbers(int num[2][2])
{ int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
for (j = 0; j < 2; ++j)
printf("%d\n", num[i][j]); }

Note : displayNumbers(int num[][2]) is also valid


Recursion
 The process in which a function calls itself directly or indirectly is
called recursion and the corresponding function is called as
recursive function.
 Recursion in computer science is a method where the solution to a
problem depends on solutions to smaller instances of the same
problem (as opposed to iteration).
 The approach can be applied to many types of problems,
and recursion is one of the central ideas of computer science.
 Using recursive algorithm, certain problems can be solved quite
easily.
 Examples of such problems are Towers of HanoiTOH),
Inorder/Preorder/Postorder Tree Traversals, searching of Graph, etc.
Contd..
void recurfunc()
{ ... .. ...
•The recursion continues until some
recurfunc(); 2 condition is met to prevent it.
... .. ... 1 •To prevent infinite recursion,
if...else statement (or similar
} approach) can be used where one
int main() branch makes the recursive call
and other doesn't.
{ .. .. ...
recurfunc();
... .. ...
}
Example
#include <stdio.h>
int sum(int n); •Initially, the sum() is called from the
main() function with number
int main() { passed as an argument.
int number, result; •Suppose, the value of num is 3 initially.
printf("Enter a positive integer: "); During next function call, 2 is
scanf("%d", &number); passed to the sum()function.
•This process continues until num
result = sum(number);
is equal to 0.
printf("sum=%d", result); } •When num is equal to 0, the if
int sum(int num) { condition fails and the else part is
if (num!=0) executed returning the sum of
// sum() function calls itself else integers to the main() function.
return num + sum(num-1);
return num;
}

You might also like