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

CP Functions

The document discusses functions in C programming, including the differences between functions and loops, the two types of functions (library and user-defined), and the key aspects of defining and calling user-defined functions such as function prototypes, passing arguments, return statements, and examples of different types of functions.

Uploaded by

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

CP Functions

The document discusses functions in C programming, including the differences between functions and loops, the two types of functions (library and user-defined), and the key aspects of defining and calling user-defined functions such as function prototypes, passing arguments, return statements, and examples of different types of functions.

Uploaded by

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

Structured Programming Approach Prof: S.

Rathod

C Programming Functions

In programming, a function is a segment that groups code to perform a specific


task. A C program has at least one function main( ). Without main() function, there
is technically no C program.

Function and looping difference

Loop are used when we need to repeat group of instructions where as function is
contrast (which may consist loops used for evaluating tasks) can be called more
than once at a any part of program wherever required

Types of C functions

There are two types of functions in C programming:

• Library function

• User defined function

Library function

Library functions are the in-built function in C programming system.

For example:

main() The execution of every C program starts from this main() function.

printf() prinf() is used for displaying output in C.

scanf() scanf() is used for taking input in C.

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. Suppose, a
programmer wants to find factorial of a number and check whether it is prime or
not in same program. Then, he/she can create two separate user-defined functions
[202]
Structured Programming Approach Prof: S. Rathod

in that program: one for finding factorial and other for checking whether it is prime
or not.

Advantages of user defined functions

1. User defined functions helps to decompose the large program into small
segments which makes programmer easy to understand, maintain and debug.

2. If repeated code occurs in a program. Function can be used to include those


codes and execute when needed by calling that function.

3. Programmer working on large project can divide the workload by

making different functions.

I. 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 following 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.
[203]
Structured Programming Approach Prof: S. Rathod

II. 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 a following 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.

III. Function definition:


Function definition contains programming codes to perform specific task.

Syntax of function definition


return_type function_name(type(1) argument(1),..,type(n) argument(n))
{
//body of function
}

Function definition has two major components:

1. Function declarator:
Function declarator is the first line of function definition. When a function is
called, control of the program is transferred to function declarator.

Syntax of function declaratory

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

Syntax of function declaration and declarator are almost same except, there is no
semicolon at the end of declarator and function declarator is followed by
function body.
[204]
Structured Programming Approach Prof: S. Rathod

2. Function body
Function declarator is followed by body of function inside braces.

Passing arguments to functions


In programming, argument(parameter) refers to data this is passed to
function(function definition) while calling 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.

[205]
Structured Programming Approach Prof: S. Rathod

Syntax of return statement


return (expression);

For example:
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

C Programming User-defined functions

Write a C program to add two integers. Make a function add to add integers and
display sum in main() 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


[206]
Structured Programming Approach Prof: S. Rathod

printf("sum=%d",sum);

return 0;

int add(int a,int b) //function declarator

{ /* Start of function definition. */

int add;

add=a+b;

return add; //return statement of function

/* End of function definition. */

Types of User-defined Functions in C Programming

For better understanding of arguments and return type in functions, user-defined


functions can be categorized 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


[207]
Structured Programming Approach Prof: S. Rathod

4. Function with arguments and return value.

1) Function with no arguments and no return value.

#include<stdio.h>

#include<conio.h>

void add();

int main()

add();

getch();

return 0;

void add() ///no parameter

int a,b,sum;

printf(“enter two integer”);

scanf(“%d%d”,&a,&b);

sum=a+b;

printf(“sum=%d”,sum);

[208]
Structured Programming Approach Prof: S. Rathod

2) Function with no arguments but return value

#include<stdio.h>

#include<conio.h>

int add();

int main()

int sum;

sum=add();

printf(“Sum is %d”,sum);

getch();

return 0;

int add() //no parameter

int a,b,c;

printf(“enter two integer”);

scanf(“%d%d”,&a,&b);

c=a+b;

return c; //value is written

[209]
Structured Programming Approach Prof: S. Rathod

3) Function with arguments but no return value

#include<stdio.h>

#include<conio.h>

void add(int,int); ///function with parameter

int main()

int a,b;

printf(“enter two integer”);

scanf(“%d%d”,&a,&b);

add(a,b); //parameter passed to function

getch();

return 0;

void add(int x,int y) //parameter

int sum;

sum=x+y;

printf(“sum is=%d”,sum);

[210]
Structured Programming Approach Prof: S. Rathod

4) Function with arguments and return value.

#include<stdio.h>

#include<conio.h>

int add(int,int); //with parameter and return value

int main()

int a,b,sum;

printf(“enter two integer”);

scanf(“%d%d”,&a,&b);

sum=add(a,b);

printf(“Sum is %d”,sum);

getch();

return 0;

int add(int x,int y) // parameter

int z;

z=x+y;

return z; //value is written

[211]
Structured Programming Approach Prof: S. Rathod

WAP to accept nos and display same.

#include<conio.h>

void main()

int n;

void display (int n);

clrscr();

printf("Enter a number: ");

scanf("%d",&n);

display(n);

getch();

void display (int n)

int i;

for(i=1;i<=n;i++)

printf("%d\n",i);

[212]
Structured Programming Approach Prof: S. Rathod

Write a program to calculate average of three numbers using function.

#include<stdio.h>

#include<conio.h>

void main()

int n1,n2,n3;

void avg (int a, int b, int c);

clrscr();

printf("Enter three numbers:");

scanf("%d %d %d",&n1,&n2,&n3);

avg(n1,n2,n3);

getch();

void avg (int a, int b, int c)

float average;

average=(a+b+c)/3.0;

printf("Average=%f",average);

[213]
Structured Programming Approach Prof: S. Rathod

Write a program to find factorial of a number using user defined function.

#include<stdio.h>

#include<conio.h>

void main()

int no,factorial;

int fact (int no);

clrscr();

printf("Enter a number:");

scanf("%d",&no);

factorial=fact(no);

printf("Factorial=%d",factorial);

getch();

int fact (int no)

int i,ans;

for(i=1,ans=1;i<=no;i++)

ans=ans*i;

return ans;
[214]
Structured Programming Approach Prof: S. Rathod

Write a program to generate multiplication table of N number when value of


N is given by user.

#include<stdio.h>

#include<conio.h>

void main()

int i,n;

void mul(int n);

clrscr();

printf("Enter a number: ");

scanf("%d",&n);

mul(n);

getch();

void mul(int n)

int i;

for(i=1;i<=10;i++)

printf("%d X %d = %d\n",n,i,(n*i));

[215]
Structured Programming Approach Prof: S. Rathod

Write a program which displays all ODD numbers up to N when value of N is


entered by user.

#include<stdio.h>

#include<conio.h>

void main()

int n;

void odd(int n);

clrscr();

printf("Enter a number: ");

scanf("%d",&n);

odd(n);

getch();

void odd(int n)

int i;

for(i=0;i<=n-1;i++)

[216]
Structured Programming Approach Prof: S. Rathod

printf("%d\n",2*i+1);

Write a program to check whether the entered number is prime or not Using
Function.

#include<stdio.h>

#include<conio.h>

void main()

int n;

void prime(int n);

clrscr();

printf("Enter a number:");

scanf("%d",&n);

prime(n);

getch();

void prime(int n)

int i=2;

while(n%i!=0)

[217]
Structured Programming Approach Prof: S. Rathod

i++;

if(n==i)

printf("Prime Number");

else

printf("Not a prime number");

/* Program for GCD and LCM using functions. */


#include<stdio.h>
#include<conio.h>
int GCD (int no1, int no2);
int LCM (int no1, int no2);
void main()
{
int no1,no2,gcd,lcm;
clrscr();

printf("Enter two numbers : ");


scanf("%d%d",&no1,&no2);

gcd = GCD(no1,no2);
if(gcd==1)
[218]
Structured Programming Approach Prof: S. Rathod

printf("\nGCD doesnt exist");


else
printf("\nGCD = %d",gcd);

lcm = LCM(no1,no2);
printf("\nLCM = %d",lcm);
getch();
}
int GCD (int no1, int no2)
{
int gcd;
if(no1<no2)
gcd=no1;
else
gcd=no2;
while(no1%gcd!=0 || no2%gcd!=0)
{
gcd--;
}
return gcd;
}
int LCM (int no1, int no2)
{
int lcm;
if(no1>no2)
lcm=no1;
else
lcm=no2;
while(lcm%no1!=0 || lcm%no2!=0)
{
lcm++;
}
return lcm;

[219]
Structured Programming Approach Prof: S. Rathod

}
/* OUTPUT :
Enter two numbers : 16 24

GCD = 8
LCM = 48

*/

Program for nPr and nCr.


#include<stdio.h>
#include<conio.h>
int fact (int no);
void main()
{
int n, r, ncr, npr;
clrscr();

printf("Enter the values of n and r : ");


scanf("%d%d", &n, &r);

ncr = fact(n) / (fact(r) * fact(n-r));


printf("\n nCr = %d", ncr);

npr = fact(n) / fact(n-r);


printf("\n nPr = %d", npr);
getch();
}
int fact (int no)
{

int i,ans;

for(i=1,ans=1;i<=no;i++)

[220]
Structured Programming Approach Prof: S. Rathod

ans=ans*i;

return ans;

/* OUTPUT :
Enter the values of n and r : 8 2

nCr = 28
nPr = 56

Call by value and reference

Call by value

1) While Passing Parameters using call by value , xerox copy of original


parameter is created and passed to the called function.
2) Any update made inside user defined function will not affect the original value
of variable in calling function.
3) As their scope is limited to only function so they cannot alter the values inside
main function.

Example:

#include<stdio.h>

#include<conio.h>

void swap(int,int); //prototype

int main()

{
[221]
Structured Programming Approach Prof: S. Rathod

int a=5,b=7;

printf(“value before call a=%d and b=%d\n”,a,b);

swap(a,b); //calling a and b are actual parameter

printf(“value after call a=%d and b=%d\n”,a,b);

getch()

return 0;

void swap(int p,int q)

int temp;

temp=p;

p=q;

q=temp;

printf(“value after swapping p=%d and q=%d\n”,p,q);

OUTPUT:

Value before call a=5 and b=7

Value after swapping p=7 and q=5

Value after a call a=5 and b=7

[222]
Structured Programming Approach Prof: S. Rathod

Call by reference

1) While passing parameter using call by address scheme , we are passing the
actual address of the variable to the called function.
2) Any updates made inside the called function will modify the original copy
since we are directly modifying the content of the exact memory location.

Example:

#include<stdio.h>

#include<conio.h>

void swap(int *,int *); //prototype

int main()

int a=5,b=7;

printf(“value before call a=%d and b=%d\n”,a,b);

swap(&a,&b); //calling a and b with address passed

printf(“value after call a=%d and b=%d\n”,a,b);

getch()

return 0;

void swap(int *p,int *q)

int temp;

temp=*p;

*p=*q;
[223]
Structured Programming Approach Prof: S. Rathod

*q=temp;

OUTPUT:

Value before call a=5 and b=7

Value after a call a=7 and b=5

MORE ADVANCE FEATURE:

1) Passing array as a parameter


Like an variable an entire array can be passed as parameter in same
manner,but we must have to understand some hidden fact collectively about
function,array and pointer.

The name of array in fact itself is a pointer which holds the address of
first location of an array. This is base address

Example:int x[5];

x is name of array it hold first address called base address i.e x[0]

x=&x[0];

WAP to find sum of the elements of array.Define function for summation.

#include<stdio.h>

#include<conio.h>

int sum(int []); //equivalent to int sum(int *);

int main()

{
[224]
Structured Programming Approach Prof: S. Rathod

int a[]={3,9,6,12,10};

int result;

clrscr();

result=sum(a); //passing array as a parameter equivalent to result=sum(&a[0])

printf(“Sum of elements is =%d”,result);

getch();

return 0;

int sum(int x[5]) //equivalent to int sum(int *x)

int c=0,i;

for(i=0;i<5;i++)

c=c+x[i];

return c;

OUTPUT:

Sum of element=40

[225]
Structured Programming Approach Prof: S. Rathod

2) Function as a parameter to function:

#include<stdio.h>

#include<conio.h>

int max(int,int);

int main()

int a,b,c,d,g;

clrscr();

printf(“enter four unequal no”);

scanf(“%d%d%d%d”,&a,&b,&c,&d);

g=max(max(a,b),max(c,d));

printf(“largest number is %d”,g);

getch();

return 0;

int max(int m,int n)

return (m>n)?m:n;

enter four unequal no

7,9,15,12

Largest number is 15
[226]
Structured Programming Approach Prof: S. Rathod

C Programming Recursion

A function that calls itself is known as recursive function and this technique is
known as 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

[227]
Structured Programming Approach Prof: S. Rathod

return n+sum(n-1); /*self call to function sum() */

Output

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

[228]
Structured Programming Approach Prof: S. Rathod

=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.

C program to Calculate Factorial of a Number Using Recursion

#include<stdio.h>

#include<conio.h>

int factorial(int n);

int main()

int n;

printf("Enter an positive integer: ");

[229]
Structured Programming Approach Prof: S. Rathod

scanf("%d",&n);

printf("Factorial of %d = %ld", n, factorial(n));

return 0;

int factorial(int n)

if(n!=1)

return n*factorial(n-1);

Output:

Enter an positive integer: 6

Factorial of 6 = 72

Write a Program for Fibonacci series using recursive function.

Algorithm:

main()

Step 1: START

Step 2: PRINT “Enter no. of elements : ”

Step 3: INPUT n

Step 4: PRINT “Fibonacci Series : ”

Step 5: INITIALIZE i = 1
[230]
Structured Programming Approach Prof: S. Rathod

Step 6: IF i <= n, THEN GOTO Step 7, ELSE GOTO Step 10.

Step 7: term = CALL fibo(i)

Step 8: PRINT term

Step 9: INCREMENT i by 1, AND GOTO Step 6.

Step 10: STOP

fibo(int f)

Step 1: START

Step 2: IF f == 1, GOTO Step 3, ELSE GOTO Step 4.

Step 3: RETURN 0.

Step 4: IF f == 2, GOTO Step 5, ELSE GOTO Step 6.

Step 5: RETURN 1.

Step 6: next = (fibo(f-1) + fibo(f-2))

Step 7: RETURN next.

main()

[231]
Structured Programming Approach Prof: S. Rathod

fibo (int f)

[232]
Structured Programming Approach Prof: S. Rathod

Program for Fibonacci series using recursive function.

#include<stdio.h>

#include<conio.h>

int fibo (int);

void main()

{ int n, i, term;

clrscr();

printf("Enter the number of elements : ");

scanf("%d",&n);

printf("\nFibonacci Series");

for(i=1; i<=n; i++)

{ term = fibo(i);

printf("\n %d", term);


[233]
Structured Programming Approach Prof: S. Rathod

getch();

int fibo (int f)

int next = 0 ;

if(f == 1)

return 0;

else if(f == 2)

return 1;

else

next = fibo(f-1) + fibo(f-2);

return next;

OUTPUT:

Enter the number of elements : 6

Fibonacci Series:

011235

[234]
Structured Programming Approach Prof: S. Rathod

Program for x^y using recursive function.

#include<stdio.h>

#include<conio.h>

int power(int x,int y);

void main()

int p,x,y;

clrscr();

printf(“enter x and y”);

scanf(“%d%d”,&x,&y);

p=power(x,y);

printf(“\n the value x raised to y is=%d”,p);

getch();

int power(int x,int y)

if(y==0)

return 1;

else if(y==1)

return x;

else

return (x* power(x,y-1));


[235]
Structured Programming Approach Prof: S. Rathod

OUTPUT:

enter x and y 3 4

the value x raised to y is =81

TYPES OF VARIABLE:

variable is just a named area of storage that can hold a single value (numeric or
character). The C language demands that you declare the name of each variable
that you are going to use and its type, or class, before you actually try to do
anything with it.
The Programming language C has two main variable types

● Local Variables
● Global Variables

Local Variables:

● Local variables scope is confined within the block or function where it is


defined. Local variables must always be defined at the top of a block.
● When a local variable is defined - it is not initialized by the system, you
must initialize it yourself.
● When execution of the block starts the variable is available, and when the
block ends the variable 'dies'.

Global variable :

● Global variable is defined at the top of the program file and it can be visible
and modified by any function that may reference it.
● Global variables are initialized automatically by the system when you define
them!

[236]
Structured Programming Approach Prof: S. Rathod

Data Type Initialser

int 0

char '\0'

float 0

pointer NULL

STORAGE CLASSES

A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have
four different storage classes in a C program −
Auto
Register
Static
extern

Automatic variables:

● A variable declared inside a function without any storage class


specification, is by default an automatic variable.
● They are created when a function is called and are destroyed automatically
when the function exits.
● Automatic variables can also be called local variables because they are local
to a function.
● By default they are assigned garbage value by the compiler.Since, variable
inside a function is automatic by default, keyword auto are rarely used.

[237]
Structured Programming Approach Prof: S. Rathod

Example:
void main()
{
int detail;
or
auto int detail; //Both are same
}

Register variables:
Keyword to declare register variable
register
Example
register int a;

● Register variables are similar to automatic variable and exists inside that
particular function only.
● If the compiler encounters register variable, it tries to store variable in
microprocessor's register rather than memory.
● Value stored in register are much faster than that of memory.
● Register variable not store the address of variable

Static variables:

A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and
goes out of scope, static is initialized only once and remains into existence till the
end of program. A static variable can either be internal or external depending upon
the place of declaration. Scope of internal static variable remains inside the
function in which it is defined. External static variables remain restricted to scope
of file in each they are declared.
They are assigned 0 (zero) as default value by the compiler.

[238]
Structured Programming Approach Prof: S. Rathod

void test(); //Function declaration (discussed in next topic)

main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
output :
1 2 3

extern variables:

● External variable can be accessed by any function. They are also known as
global variables. Variables declared outside every function are external
variables.
● In case of large program, containing more than one file, if the global variable
is declared in file 1 and that variable is used in file 2 then, compiler will
show error. To solve this problem, keyword extern is used in file 2 to
indicate that, the variable specified is global variable and declared in another
file.

#include<stdio.h>

void Check();
int a=5; /* a is global variable because it is outside every function */

int main()
{
a+=4;
Check();
[239]
Structured Programming Approach Prof: S. Rathod

return 0;
}

void Check()
{
++a;
printf("a=%d\n",a);
}

Output:
a=10

[240]

You might also like