0% found this document useful (0 votes)
50 views15 pages

Engineering Research Project Proposal 2016

The document discusses different types of functions in C programming: 1. User-defined functions allow programmers to define reusable blocks of code to perform operations or calculations. These functions must be defined and can be called anywhere in the code. 2. There are four main types of user-defined functions: those with or without arguments, and those with or without return values. 3. Function prototypes provide metadata about functions, like argument types and return types, that allow functions to be called before they are defined.

Uploaded by

subash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views15 pages

Engineering Research Project Proposal 2016

The document discusses different types of functions in C programming: 1. User-defined functions allow programmers to define reusable blocks of code to perform operations or calculations. These functions must be defined and can be called anywhere in the code. 2. There are four main types of user-defined functions: those with or without arguments, and those with or without return values. 3. Function prototypes provide metadata about functions, like argument types and return types, that allow functions to be called before they are defined.

Uploaded by

subash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Programming with C Lecture Notes on Functions:

Topics included:

 User-Defined Functions
 Standard Library Functions
 Recursive Functions
 Comparison of Recursion and Iteration

I. User-Defined Functions:

C functions can be classified in two categories: Library functions and User defined functions.
The difference between this two functions is, Library functions are already built in and we
need not to write its code, whereas a User defined function has to be written to get it executed
during the output.

Need for User-Defined functions:


There are times when certain operation or calculation are to be repeated during a program.
For instance, we may use a factorial of a number or printing some string lines in the program.
In this situations we may repeat the code in our program .Here, user-defined functions can be
really helpful and can save our time and program space.

Syntax :

Explanation of the Syntax:

1) Function Header :
The first line in the above given syntax is known as header function. The function header
consists of three parts: function type, function name and the function parameter list.

-Function type: This may consist of the datatypes that you use. For example float, int, double.
NOTE: If datatype is not specified then C will assume it as int type. And if the function does
not return any value then use void.
Programming with C Lecture Notes on Functions:

-Function name: This may consist of any variable that is suitable for user's understanding. For
example: If you have made user defined function for factorial then use fact and if for simple
multiplication then mul.

-Parameter List: It declares the variables that are to be used in the function and that are going
to be called in the program

2) Function Body:

The function body contains the declaration statement necessary for performing the required
task. The body enclosed in braces contain three parts:

-A return statement that returns the value evaluated by the function.

-Function statement that perform the task of the function.Using void as shown below:

-Local declaration that specify the variable needed by the function.

NOTE: If function does not return any value, we can omit the return statement.
Function call :
Programming with C Lecture Notes on Functions:
A function can be called simply using the function name followed by a list of actual
parameters(or arguments), if any enclosed in parentheses. Let's take an example for
multiplication of two numbers.

When the compiler encounters a function call, the control is transferred to the function mul( ).
This function is then executed line by line as described and a value is returned when a return
statement is encountered. This value is assigned to y. This is illustrated below:

Example of user-defined function


Write a C program to add two integers. Make a function add to add integers and
display sum in main() function.

/*Program to demonstrate the working of user defined function*/


#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
}
int add(int a,int b) //function declarator
{
Programming with C Lecture Notes on Functions:
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}

Function prototype(declaration):
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype gives compiler information
about function name, type of arguments to be passed and return type.

Syntax of function prototype


return_type function_name(type(1) argument(1),....,type(n) argument(n));

In the above example,int add(int a, int b); is a function prototype which provides
following information to the compiler:

1. name of the function is add()


2. return type of the function is int.
3. two arguments of type int are passed to function.

Function prototype are not needed if user-definition function is written before main()
function.

Function call
Control of the program cannot be transferred to user-defined function unless it is called
invoked).

Syntax of function call


function_name(argument(1),....argument(n));

In the above example, function call is made using statement add(num1,num2); from main().
This make the control of program jump from that statement to function definition and
executes the codes inside that function.

Function definition
Function definition contains programming codes to perform specific task.
Programming with C Lecture Notes on Functions:
Passing arguments to functions
In programming, argument/parameter is a piece of data(constant or variable) passed from a
program to the function.

In above example two variable, num1 and num2 are passed to function during function call
and these arguments are accepted by arguments a and b in function definition.

Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type. For example:

If argument num1 was of int type and num2 was of float type then, argument variable a
should be of type int and b should be of type float,i.e., type of argument during function call
and function definition should be same.

A function can be called with or without an argument.

Return Statement
Return statement is used for returning a value from function definition to calling function.

Syntax of return statement


return (expression);
OR
return;

For example:

return;
return a;
return (a+b);

In above example, value of variable add in add() function is returned and that value is stored
in variable sum in main() function. The data type of expression in return statement should
also match the return type of function.
Programming with C Lecture Notes on Functions:

Types of User-defined Functions(Function Designs) in C:


For better understanding of arguments and return in functions, user-defined functions can be
categorised as:

1. Function with no arguments and no return value


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

Let's take an example to find whether a number is prime or not using above 4 cateogories of
user defined functions.

Function with no arguments and no return value.

/*C program to check whether a number entered by user is prime or not using
function with no arguments and no return value*/
#include <stdio.h>
void prime();
int main(){
prime(); //No argument is passed to prime().
return 0;
}
void prime(){
/* There is no return value to calling function main(). Hence, return type
of prime() is void */
int num,i,flag=0;
printf("Enter positive integer enter to check:\n");
scanf("%d",&num);
for(i=2;i<=num/2;++i){
if(num%i==0){
flag=1;
}
}
if (flag==1)
printf("%d is not prime",num);
else
Programming with C Lecture Notes on Functions:
printf("%d is prime",num);
}

Function prime() is used for asking user a input, check for whether it is prime of not and
display it accordingly. No argument is passed and returned form prime() function.

Function with no arguments but return value

/*C program to check whether a number entered by user is prime or not using
function with no arguments but having return value */
#include <stdio.h>
int input();
int main(){
int num,i,flag;
num=input(); /* No argument is passed to input() */
for(i=2,flag=i;i<=num/2;++i,flag=i){
if(num%i==0){
* printf("%d is not prime",num);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime",num);
return 0;
}
int input(){ /* Integer value is returned from input() to calling
function */
int n;
printf("Enter positive enter to check:\n");
scanf("%d",&n);
return n;
}

There is no argument passed to input() function But, the value of n is returned from
input() to main() function.

Function with arguments and no return value

/*Program to check whether a number entered by user is prime or not using


function with arguments and no return value */
#include <stdio.h>
void check_display(int n);
int main(){
int num;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
check_display(num); /* Argument num is passed to function. */
return 0;
}
void check_display(int n){
/* There is no return value to calling function. Hence, return type of
function is void. */
int i,flag;
for(i=2,flag=i;i<=n/2;++i,flag=i){
Programming with C Lecture Notes on Functions:
if(n%i==0){
printf("%d is not prime",n);
++flag;
break;
}
}
if(flag==i)
printf("%d is prime",n);
}

Here, check_display() function is used for check whether it is prime or not and display it
accordingly. Here, argument is passed to user-defined function but, value is not returned from
it to calling function.

Function with argument and a return value

/* Program to check whether a number entered by user is prime or not using


function with argument and return value */
#include <stdio.h>
int check(int n);
int main(){
int num,num_check=0;
printf("Enter positive enter to check:\n");
scanf("%d",&num);
num_check=check(num); /* Argument num is passed to check() function. */
if(num_check==1)
printf("%d in not prime",num);
else
printf("%d is prime",num);
return 0;
}*
int check(int n){
/* Integer value is returned from function check() */
int i;
for(i=2;i<=n/2;++i){
if(n%i==0)
return 1;
}
return 0;
}

Here, check() function is used for checking whether a number is prime or not. In this
program, input from user is passed to function check() and integer value is returned from it.
If input the number is prime, 0 is returned and if number is not prime, 1 is returned.

II. The Standard Library Functions


Some of the "commands" in C are not really "commands" at all but are functions. For
example, we have been using printf and scanf to do input and output, and we have used
rand to generate random numbers - all three are functions.

A list of the most common libraries and a brief description of the most useful functions they
contain follows:
Programming with C Lecture Notes on Functions:
1. stdio.h: I/O functions:
1. getchar() returns the next character typed on the keyboard.
2. putchar() outputs a single character to the screen.
3. printf() as previously described
4. scanf() as previously described

2. string.h: String functions

1. strcat() concatenates a copy of str2 to str1


2. strcmp() compares two strings
3. strcpy() copys contents of str2 to str1
3. ctype.h: Character functions

1. isdigit() returns non-0 if arg is digit 0 to 9


2. isalpha() returns non-0 if arg is a letter of the alphabet
3. isalnum() returns non-0 if arg is a letter or digit
4. islower() returns non-0 if arg is lowercase letter
5. isupper() returns non-0 if arg is uppercase letter
4. math.h: Mathematics functions

1. acos() returns arc cosine of arg


2. asin() returns arc sine of arg
3. atan() returns arc tangent of arg
4. cos() returns cosine of arg
5. exp() returns natural logarithim e
6. fabs() returns absolute value of num
7. sqrt() returns square root of num
5. time.h: Time and Date functions

1. time() returns current calender time of system


2. difftime() returns difference in secs between two times
3. clock() returns number of system clock cycles since program execution
6. stdlib.h:Miscellaneous functions

1. malloc() provides dynamic memory allocation, covered in future sections


2. rand() as already described previously
3. srand() used to set the starting point for rand()

stdio.h

In the C Programming Language, the Standard Library Functions are divided into several
header files.

The following is a list of functions found within the <stdio.h> header file:
Programming with C Lecture Notes on Functions:
Formatted Input/Output functions
fprintf Formatted File Write

fscanf Formatted File Read

printf Formatted Write

scanf Formatted Read

sprintf Formatted String Write

sscanf Formatted String Read

File Operation functions


fclose Close File

fflush Flush File Buffer

fopen Open File

freopen Reopen File

remove Remove File

rename Rename File

Character Input/Output functions


fgetc Read Character from File

fgets Read String from File

fputc Write Character to File

fputs Write String to File

getc Read Characters from File

getchar Read Character

gets Read String


Programming with C Lecture Notes on Functions:
putc Write Character to File

putchar Write Character

puts Write String

ungetc Unread Character

File Positioning functions


fgetpos Get File Position

fseek File Seek

fsetpos Set File Position

ftell Determine File Position

rewind Rewind File

III. Recursive Functions


A function that calls itself is known as recursive function and the process in which a function
calls itself is known as recursion in C programming.

Example of recursion in C programming


Write a C program to find sum of first n natural numbers using recursion. Note: Positive
integers are known as natural number i.e. 1, 2, 3....n

#include <stdio.h>
int sum(int n);
int main(){
int num,add;
printf("Enter a positive integer:\n");
scanf("%d",&num);
add=sum(num);
printf("sum=%d",add);
}
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1); /*self call to function sum() */
}

Output
Programming with C Lecture Notes on Functions:
Enter a positive integer:
5
15

In, this simple C program, sum() function is invoked from the same function. If n is not equal
to 0 then, the function calls itself passing argument 1 less than the previous argument it was
called with. Suppose, n is 5 initially. Then, during next function calls, 4 is passed to function
and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0,
the value of n is returned which is the sum numbers from 5 to 1.

For better visualization of recursion in this example:

sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15

Every recursive function must be provided with a way to end the recursion. In this example
when, n is equal to 0, there is no recursive call and recursion ends.

Advantages and Disadvantages of Recursion


Recursion is more elegant and requires few variables which make program clean. Recursion
can be used to replace complex nesting code by dividing the problem into same problem of
its sub-type.

In other hand, it is hard to think the logic of a recursive function. It is also difficult to debug
the code containing recursion.

IV. Comparison of Recursion and iteration


The differences between recursion and iteration cab be stated as below:

Recursion Vs. Iteration


Recursion Iteration

Recursion is the term given to the mechanism of Iteration is the block of statement executed
defining a set or procedure in terms of itself. repeatedly using loops.

A conditional statement is required in the body The iteration control statement itself contains
of the function for stopping the function statement for stopping the iteration. At every
Programming with C Lecture Notes on Functions:

Recursion Vs. Iteration


Recursion Iteration

execution. execution, the condition is checked.

At some places, use of recursion generates extra All problems can be solved with iteration.
overhead. Hence, better to skip when easy
solution is available with iteration.

Recursion is expensive in terms of speed and Iteration does not create any overhead. All the
memory. programming languages support iteration.

The C programming language supports recursion, i.e., a function to call itself. But while
using recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go in infinite loop.

Recursive function are very useful to solve many mathematical problems like to calculate
factorial of a number, generating Fibonacci series, etc.

Number Factorial
Following is an example, which calculates factorial for a given number using a recursive
function:

#include <stdio.h>

int factorial(unsigned int i)


{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}

When the above code is compiled and executed, it produces the following result:

Factorial of 15 is 2004310016

Iterative version to find factorial of a number.

/* Iterative Version */
unsigned int iter_factorial(int n)
{
Programming with C Lecture Notes on Functions:
int f = 1;
int i;
for(i = 1; i <= n; i++)
{
f *= i;
}
return f;
}

Fibonacci Series
Following is another example, which generates Fibonacci series for a given number using a
recursive function:

#include <stdio.h>

int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}

int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t%n", fibonaci(i));
}
return 0;
}

When the above code is compiled and executed, it produces the following result:

0 1 1 2 3 5 8 13 21 34

Iterative version to find Fibonacci series

int Fibonacci(int n)
{
int f1 = 0;
int f2 = 1;
int fn;
for ( int i = 2; i < n; i++ )
Programming with C Lecture Notes on Functions:
{
fn = f1 + f2;
f1 = f2;
f2 = fn;
}
}

-----------------------------------------------------END---------------------------------------------------------------------------

You might also like