0% found this document useful (0 votes)
2 views36 pages

C Programming Class 12 Functions (1)

A function in C is a reusable block of code that enhances program modularity and readability by dividing larger programs into smaller, manageable subprograms. Functions can be categorized into standard library functions, which are built-in, and user-defined functions, which are created by the programmer. The document also outlines the advantages of using functions, their types, and provides examples of how to declare, define, and call functions in C.

Uploaded by

rajatmahaseth44
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)
2 views36 pages

C Programming Class 12 Functions (1)

A function in C is a reusable block of code that enhances program modularity and readability by dividing larger programs into smaller, manageable subprograms. Functions can be categorized into standard library functions, which are built-in, and user-defined functions, which are created by the programmer. The document also outlines the advantages of using functions, their types, and provides examples of how to declare, define, and call functions in C.

Uploaded by

rajatmahaseth44
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/ 36

What is a Function in C?

Function in C programming is a reusable block of code that makes a program


easier to understand, test and can be easily modified without changing the calling
program.
Functions divide the code and modularize the program for better and effective
results.In short, a larger program is divided into various subprograms which are
called functions.

A function can be called multiple times to provide reusability and modularity to the
C program. In other words, we can say that the collection of functions creates a
program. The function is also known as procedure or subroutine in other
programming languages.

When you divide a large program into various functions, it becomes easy to
manage each function individually.
Whenever an error occurs in the program, you can easily investigate faulty
functions and correct only those errors. You can easily call and use functions
whenever they are required which automatically leads to saving time and space.

Advantages of Function

The advantages of using functions are:

Avoid repetition of codes.


Increases program readability.

Divide a complex problem into simpler ones.

Reduces chances of error.

Modifying a program becomes easier by using a function.

Types of function
There are two types of function in C programming:

Standard library functions

User-defined functions

Standard library functions


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

Library Functions in Different Header Files

C Header Files Description

<assert.h> Program assertion functions

<ctype.h> Character type functions


<locale.h> Localization functions

<math.h> Mathematics functions

<setjmp.h> Jump functions

<signal.h> Signal handling functions

<stdarg.h> Variable arguments handling functions

<stdio.h> Standard Input/Output functions

<stdlib.h> Standard Utility functions

<string.h> String handling functions

<time.h> Date time functions

These functions are defined in header files. For 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 the stdio.h header file.
Hence, to use the printf()function, we need to include the stdio.h header file using
#include <stdio.h>.
The sqrt() function calculates the square root of a number. The function is defined
in the math.h header file.

Advantages of Using C library functions


1. They work

2. The functions are optimized for performance

3. It saves considerable development time

4. The functions are portable

Example: Square root using sqrt() function


Suppose, you want to find the square root of a number.

To compute the square root of a number, you can use the sqrt() library function.
The function is defined in the math.h header file.

#include <stdio.h>
#include <math.h>
int main()
{
float num, root;
printf("Enter a number: ");
scanf("%f", &num);

// Computes the square root of num and stores in the root.


root = sqrt(num);

printf("Square root of %f = %f", num, root);


//WAP TO FIND THE POWER OF A NUMBER USING STANDARD LIBRARY
FUNCTIONS.
#include <stdio.h>

#include <math.h>

int main()
{
float num, varibale_name, exp;
printf("Enter a number: ");//25
scanf("%f", &num); //num=25

printf("Enter the power that you want to raise of a number");


scanf("%f",&exp);

// Computes the power of num and stores in a variable .


varibale_name = pow(num,exp);

printf("Power of a given number is %f = %.2f", num, varibale_name);


return 0;
}
return 0;
}
User-defined function
You can also create functions as per your need. Such functions created by the user
are known as user-defined functions.

A function created by a user is known as a user defined function.

C programming functions are divided into three activities such as,


1. Function declaration
2. Function definition
3. Function call

Function declaration means writing the name of a function.


It is a compulsory part for using functions in code. In a function declaration, we
just specify the name of a function that we are going to use in our program like a
variable declaration. We cannot use a function unless it is declared in a program.
A function declaration is also called “Function prototype.”

The function declarations (called prototype) are usually done above the main ()
function and take the general form:

return_data_type function_name (data_type arguments);

Int sum ( int a , int b);

The return_data_type: is the data type of the value function returned back to the
calling statement.
The function_name: is followed by parentheses
Arguments names with their data type declarations optionally are placed inside the
parentheses.

Function Definition
Function definition means just writing the body of a function. A body of a function
consists of statements which are going to perform a specific task. A function body
consists of a single or a block of statements.
return_type function_name (argument list)
{
function body;

Function call
A function call means calling a function whenever it is required in a program.
Whenever we call a function, it performs an operation for which it was designed.
function_name (argument_list)

Return Value

A C function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type.

Example without return value:

void hello()
{
printf("hello c");
}

If you want to return any value from the function, you need to use any data type
such as int, long, char, etc. The return type depends on the value to be returned
from the function.

Let's see a simple example of a C function that returns int value from the function.

Example with return value:

int get()
{
return 0;
}
Example

#include <stdio.h>

/* function declaration */

int max(int num1, int num2 );//formal parameters or parameters

int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b); // actual parameters or arguments
printf( "Max value is : %d\n", ret );

return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2) //num1=100 //num2=200 ( call by value) ( copy by
value)//formal parameters or parameters
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Example with program


//wap to find the maximum of two numbers using
user-defined functions
#include <stdio.h>

/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}

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

//Wap to find the square of a number using user-defined


functions

#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here

int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}

float square ( float x ) // function definition


{
float p ;
p=x*x;
return ( p ) ;
}
//Wap using a user defined function to find the greatest
among 3 numbers.

#include<stdio.h>

float large(float a, float b, float c);

int main()
{
float num1, num2, num3, largest;

printf("Enter three numbers: ");


scanf("%f %f %f", &num1, &num2, &num3);

largest = large(num1, num2, num3);


printf("Largest number = %.2f",largest);
return 0;
}

// function to find largest among three number


float large(float a, float b, float c)
{
if(a>b && a>c)
return a;
else if(b>a && b>c)
return b;
else
return c;
}

//wap to find the cube of a number using user defined


function

#include<stdio.h>
// function prototype, also called function declaration
float cube ( float x );
// main function, program starts from here

int main( )
{
float m, n ;
printf ( "\nEnter some number for finding cube \n");
scanf ( "%f", &m ) ;
// function call
n = cube ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}

float cube ( float x ) // function definition


{
float p ;
p=x*x*x;
return ( p ) ;

//return ( x*x);
}

//wap to find the area of a rectangle using user defined


function

#include<stdio.h>
// function prototype, also called function declaration
float area_of_rectangle ( float l,float w );
// main function, program starts from here

int main( )
{
float a, b ,result;
printf ( "\nEnter the length of the rectangle \n");
scanf ( "%f", &a ) ;

printf ( "\nEnter the breadth of the rectangle \n");


scanf ( "%f", &b ) ;

// function call
result = area_of_rectangle ( a,b ) ;
printf ( "\nThe area of rectangle having length %f and breadth %f is
%f",a,b,result );
}

float area_of_rectangle ( float l,float w ) // function definition


{
float final_result ;
final_result = l*w ;
return ( final_result ) ;

//return ( x*x);
}

//Write a C program with a user-defined function to find the area of a circle


using a user-defined function.

#include<stdio.h>

// function declaration
float circleArea(float r);

int main()
{
float radius, area;

printf("Enter the radius of the circle: ");


scanf("%f", &radius);

area = circleArea(radius); //function calling


printf("Area of circle = %.2f\n",area);

return 0;
}

// function definition
float circleArea(float r)
{
float area = 3.14 * r * r;
return area; // return statement
}

//write a user-defined function to find minimum and


maximum in given three numbers using two functions.
#include<stdio.h>

// function declarations
float minimum(float a, float b, float c);
float maximum(float a, float b, float c);

int main()
{
float n1, n2, n3;

printf("Enter three numbers: ");


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

printf("Minimum number = %.2f\n",minimum(n1,n2,n3));


printf("Maximum number = %.2f\n",maximum(n1,n2,n3));

return 0;
}

// function for finding minimum of three numbers


float minimum(float a, float b, float c)
{
if(a<=b && a<=c) return a;
else if(b<=a && b<=c) return b;
else return c;
}

// function for finding maximum of three numbers


float maximum(float a, float b, float c)
{
if(a>=b && a>=c) return a;
else if(b>=a && b>=c) return b;
else return c;
}

//Find the sum of N numbers using function

#include<stdio.h>
int sum(int x);
int main()
{
int range, result;
printf("Upto which number you want to find sum: ");
scanf("%d", &range);
result = sum(range);
printf("1+2+3+….+%d+%d = %d",range-1, range, result);
}

int sum(int n)
{
int add = 0;
for(int i=1; i<=n; i++)
{
add += i;
}
return add;
}

//WAP to find the Factorial of a number using function

( First without using function)


#include <stdio.h>

int main()
{
int c, n, f = 1;

printf("Enter a number to calculate its factorial\n");


scanf("%d", &n);
for (c = 1; c <= n; c++)
f = f * c;

printf("Factorial of %d = %d\n", n, f);

return 0;
}

Using user-defined function to evaluate factorial of a number

#include <stdio.h>

int fact(int n);

void main()
{
int no,factorial;

printf("Enter a number to calculate its factorial\n");


scanf("%d",&no);
factorial=fact(no);
printf("Factorial of the num(%d) = %d\n",no,factorial);
}

int fact(int n)
{
int i,f=1;
for(i=1;i<=n;i++)
{
f=f*i;
}
return f;
}

//Fibonacci series Concept

In the Fibonacci series, the next element will be the sum of the previous two
elements. The Fibonacci sequence is a series of numbers where a number is found
by adding up the two numbers before it. Starting with 0 and 1, the sequence goes 0,
1, 1, 2, 3, 5, 8, 13, 21, 34, and so forth.

0 1 1 2 3 5 8 13 21 34 55

// WAP to Display Fibonacci series in C within a range using a


function

#include<stdio.h>

void fibonacciSeries (int range);

void main()
{
int n;

printf("Enter range upto which you want to display: ");


scanf("%d", &n);

printf("\nThe Fibonacci series is: \n");

fibonacciSeries(n);

void fibonacciSeries(int range)


{
int a=0, b=1, temp;

while (a<=range)
{
printf("%d\t", a);
temp = a+b;
a = b;
b = temp;
}

//WAP TO Display fibonacci series upto Nth term using


function

#include<stdio.h>
void fibonacciSeries(int n);
int main()
{
int term;

printf("Enter the term: ");


scanf("%d", &term);

printf("The fibonacci series is: \n");

fibonacciSeries(term);

return 0;
}

void fibonacciSeries(int n)
{
int a=0, b=1, c;
for(int i=0; i<n; i++)
{
printf("%d\t", a);
c = a+b;
a = b;
b = c;
}
}
//WAP TO Find nth term of Fibonacci series in C using
function

#include<stdio.h>

int fibonacciTerm(int n);


int main()
{
int term, result;

printf("Enter term to find: ");


scanf("%d", &term);

result = fibonacciTerm(term);

printf("The fibonacci term is: %d", result);

return 0;
}
int fibonacciTerm(int n)
{
int a=0, b=1, c;
for(int i=1; i<n; i++)
{
c = a+b;
a = b;
b = c;
}
return a;
}

//WAP to find the Power of a number using function

#include<stdio.h>
long power(int a, int b);

int main()
{
int num1, num2;
printf("Enter base and power: ");
scanf("%d %d",&num1, &num2);

long result = power(num1, num2);


printf("The result = %ld", result);

return 0;
}

// User-defined function to calculate power


long power(int a, int b)
{
long result = 1;
for(int i=1; i<=b; i++)
{
result *= a;
}
return result;
}

//Write a C program to input the radius of the circle from the


user and find diameter, circumference and area of the given
circle using the function.

#include <stdio.h>
#include <math.h> // Used for constant PI referred as M_PI

/* Function declaration */
double getDiameter(double radius);
double getCircumference(double radius);
double getArea(double radius);
int main()
{
float radius, dia, circ, area;

/* Input radius of circle from user */


printf("Enter radius of circle: ");
scanf("%f", &radius);

dia = getDiameter(radius); // Call getDiameter function


circ = getCircumference(radius); // Call getCircumference function
area = getArea(radius); // Call getArea function

printf("Diameter of the circle = %.2f units\n", dia);


printf("Circumference of the circle = %.2f units\n", circ);
printf("Area of the circle = %.2f sq. units", area);

return 0;
}

/**
* Calculate diameter of circle whose radius is given
*/
double getDiameter(double radius)
{
return (2 * radius);
}

/**
* Calculate circumference of circle whose radius is given
*/
double getCircumference(double radius)
{
return (2 * M_PI * radius); // M_PI = PI = 3.14 ...
}

/**
* Find area of circle whose radius is given
*/
double getArea(double radius)
{
return (M_PI * radius * radius); // M_PI = PI = 3.14 ...
}

//WAP TO CHECK WHETHER THE GIVEN NUMBER IS PALINDROME OR NOT


using user-defined functions

#include <stdio.h>
void check_palindrome(int num);
int main()
{
int n;
printf("Enter an integer: ");
scanf("%d", &n);
check_palindrome(n);

}
void check_palindrome(int num)
{
int reverse_num=0, remainder,temp;

temp=num;
while(temp!=0)
{
remainder=temp%10;
reverse_num=reverse_num*10+remainder;
temp=temp/10;
}

if(reverse_num==num)
printf("%d is a palindrome number",num);
else
printf("%d is not a palindrome number",num);
}

//C program to check whether the given number is prime or composite using
user-defined functions

#include<stdio.h>

void check_primeorcomposite(int num);


int main()
{
int n;
printf("Enter a number to check whether it is prime or not\n");
scanf("%d",&n);
check_primeorcomposite(n);
}
void check_primeorcomposite(int num)
{
int i,count=0;
for(i=1;i<=num;i++)
{
if(num%i==0)
{
count++;
}
}
if(count==1)
{
printf("The given number is neither prime nor composite");
}
else if(count==2)
{
printf("The given number %d is Prime Number\n",num);
}
else
{
printf("The given number %d is not Prime Number\n because The number is divisible
by\n",num);
for(i=1;i<=num;i++)
{
if(num%i==0)
{
printf("%d\n",i);
}
}
}
}

//Program to find the factors of a number using user-defined function

#include <stdio.h>
void check_factors(int num);
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
check_factors(n);
}
void check_factors(int num)
{
int i;
printf("Factors of %d are: ", num);
for (i = 1; i <= num; ++i)
{
if (num % i == 0)
{
printf("%d ", i);
}
}

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call by value
and call by reference.

Call by value in C

● In the call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is
used in the function call in the call by value method.

● In the call by value method, we can not modify the value of the actual parameter
by the formal parameter.

● In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
● The actual parameter is the argument which is used in the function call whereas
the formal parameter is the argument which is used in the function definition.

Call by value method copies the value of an argument into the formal
parameter of that function. Therefore, changes made to the parameter of the
main function do not affect the argument.

In this parameter passing method, values of actual parameters are copied to


function’s formal parameters, and the parameters are stored in different
memory locations. So any changes made inside functions are not reflected in
actual parameters of the caller.

Example To demonstrate the different memory locations of the same


variable inside the main function and print function.

#include<stdio.h>

void print(int a);

int main()

int a = 10;

printf("From Main Function ...\n");

printf("Address of a = %p\n",&a);

print(a);

return 0;

void print(int a)

{
printf("From print function ...\n");

printf("Address of a = %p\n",&a);

Output:

From Main Function ...

Address of a = 0x7ffee9fcfbd8

From the print function ...

Address of a = 0x7ffee9fcfbbc

Note:

We can observe that the address of a in the main function and the address of a in print
function are different.

So, if we change the value of a in print function, it will not affect the value of a in the
main function.

Call by Value Example: Swapping the values of the two variables

#include <stdio.h>

void swap(int , int); //prototype of the function

int main()

{
int a = 10;

int b = 20;

// printing the value of a and b in main

printf("Before swapping the values in main a = %d, b = %d\n",a,b);

swap(a,b);

// The value of actual parameters do not change

//by changing the formal parameters in call by value, a = 10, b = 20

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;
// Formal parameters, a = 20, b = 10

printf("After swapping values in function a = %d, b = %d\n",a,b);

Output:-

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 10, b = 20

Call by reference in C

● In call by reference, the address of the variable is passed into the function call as
the actual parameter.

● The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.

While calling a function, instead of passing the values of variables, we pass address
of variables(location of variables) to the function known as “Call By References.

// C program to illustrate Call by Reference

#include <stdio.h>
// Function Prototype
void swapx(int*, int*);

// Main function
int main()
{
int a = 10, b = 20;

// Pass reference
swapx(&a, &b);

printf("a=%d b=%d\n", a, b);

return 0;
}

// Function to swap two variables


// by references
void swapx(int* x, int* y)
{
int t;

t = *x;
*x = *y;
*y = t;

printf("x=%d y=%d\n", *x, *y);


}

Call by Value vs. Call by Reference


Paramete Call by value Call by reference
rs
Definition While calling a function, While calling a function, in
when you pass values by programming language instead of
copying variables, it is copying the values of variables, the
known as “Call By address of the variables is used; it
Values.” is known as “Call By References.
Argument In this method, a copy of In this method, a variable itself is
s the variable is passed. passed.

Effect Changes made in a copy Change in the variable also affects


of a variable never modify the value of the variable outside the
the value of the variable function.
outside the function.
Alteration Does not allow you to Allows you to make changes in the
of value make any changes in the values of variables by using
actual variables. function calls.
Passing of Values of variables are Pointer variables are required to
variable passed using a store the address of variables.
straightforward method.
Value Original value not The original value is modified.
modificatio modified.
n
Memory Actual and formal Actual and formal arguments
Location arguments will be created in the same
will be created in different memory location
memory location
Safety Actual arguments remain Actual arguments are not
safe as they cannot be Safe. They can be
modified accidentally modified, so you need
accidentally. to handle arguments operations
carefully.
Type of User-defined 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

1.Function with no arguments and no return value

#include<stdio.h>

void greatNum(); // function declaration

int main()
{
greatNum(); // function call
return 0;
}

void greatNum() // function definition


{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j)
{
printf("The greater number is: %d", i);
}
else
{
printf("The greater number is: %d", j);
}
}

2.Function with no arguments and a return value

#include<stdio.h>

int greatNum(); // function declaration

int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}

int greatNum() // function definition


{
int i, j, greaterNum;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
if(i > j)
{
greaterNum = i;
}
else
{
greaterNum = j;
}
// returning the result
return greaterNum;
}
3.Function with arguments and no return value

#include<stdio.h>

void greatNum(int x, int y ); // function declaration

int main()
{
int i, j;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
greatNum(i, j); // function call
return 0;
}

void greatNum(int x, int y) // function definition


{
if(x > y)
{
printf("The greater number is: %d", x);
}
else
{
printf("The greater number is: %d", y);
}
}

4.Function with arguments and a return value

#include<stdio.h>
int greatNum(int x, int y ); // function declaration

int main()
{
int i, j, result;
printf("Enter 2 numbers that you want to compare...");
scanf("%d%d", &i, &j);
result = greatNum(i, j); // function call
printf("The greater number is: %d", result);
return 0;
}

int greatNum(int x, int y) // function definition


{
if(x > y)
{
return x;
}
else
{
return y;
}
}

You might also like