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

Function

C. programming. functions

Uploaded by

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

Function

C. programming. functions

Uploaded by

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

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.
You can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division is such that each function
performs a specific task.

Why do we need functions?


 Functions help us in reducing code redundancy. If functionality is performed at
multiple places in software, then rather than writing the same code, again and again,
we create a function and call it everywhere. This also helps in maintenance as we have
to change at one place if we make future changes to the functionality.
 Functions make code modular. Consider a big file having many lines of codes. It
becomes really simple to read and use the code if the code is divided into functions.
 Functions provide abstraction. For example, we can use library functions without
worrying about their internal working.

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc.

2. User-defined functions: are the functions which are created by the C programmer, so that
he/she can use it many times. It reduces the complexity of a big program and optimizes the
code.

A function declaration tells the compiler about a function's name, return type, and
parameters.

Function Declarations

A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so
the following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case, you should declare the function at the top of the
file calling the function.
Defining a Function
A function definition provides the actual body of the function.
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming consists of a function header and a function body.
Here are all the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
 Function Body − The function body contains a collection of statements that define
what the function does.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a
function, you 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, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.

Different aspects of function calling


A function may or may not accept any argument. It may or may not return any value. Based on
these facts, There are four different aspects of function calls.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value


Example 1
#include<stdio.h>
void display();
void main ()
{
printf("Hello ");
display();
}
void display ()
{
printf("Welcome to Arrow");
}

Example 2

#include<stdio.h>
#include<conio.h>
void sum(); //Function declaration
void main()
{
clrscr();
printf("\n Calculating sum:\n");
sum(); //calling function
getch();
}
void sum() //function definition
{
int a,b,c;
printf("\nEnter two numbers\t");
scanf("%d %d",&a,&b);
c=a+b;
printf("The sum is %d",c);
}

Example for Function with argument and without return value


Example 1

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers.

#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function without argument and with return value

Example 1

#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34
Example 2: program to calculate the area of the square

#include<stdio.h>
int square();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}

Output

Going to calculate the area of the square


Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and with return value

Example 1

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even
Examples of User Defined Functions:

#include<stdio.h>
#include<conio.h>
int add(int,int);
int sub(int,int);
int mul(int,int);
int div(int,int);
void main()
{
int a,b,c;
clrscr();
printf("\nEnter Two Numbers \n");
scanf("%d%d",&a,&b);
c=add(a,b);
printf("\n Addition is %d",c);
c=sub(a,b);
printf("\n Subtraction is %d",c);
c=mul(a,b);
printf("\n Multiplication is %d",c);
c=div(a,b);
printf("\n Division is %d",c);
getch();
}

int add(int a,int b)


{
return a+b;
}
int sub(int a,int b)
{
return a-b;
}
int mul(int a,int b)
{
return a*b;
}
int div(int a,int b)
{
return a/b;
}
Example 2:
//Calculate area and circumference of a circle using functions

#include<stdio.h>
#include<conio.h>
float area(float);
float circum(float);
void main()
{
float radius,a,c;
printf("Enter radius: ");
scanf("%f", &radius);
a=area(radius);
c=circum(radius);
printf("Area : %f\n",a);
printf("Circumference: %f",c);
getch();
}
/* return area of a circle */
float area(float radius)
{
return 3.14*radius*radius;
}
/* return circumference of a circle */
float circum(float radius)
{
return 2*3.14*radius;
}
Recursion

A function that calls itself is known as a recursive function. And, this technique
is known as recursion.

#include <stdio.h>
#include <conio.h>

int sum(int);

void main() {
int n, result;

printf("Enter a positive integer: ");


scanf("%d", &n);

result = sum(n);

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


getch();
}

int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}

Initially, the sum() is called from the main() function with number passed as
an argument.
Suppose, the value of n inside sum() is 3 initially. During the next function
call, 2 is passed to the sum() function. This process continues until n is equal
to 0.
When n is equal to 0, the if condition fails and the else part is executed
returning the sum of integers ultimately to the main() function.
Example 2:-

#include <stdio.h>
#include <conio.h>

int fact(int);

void main() {
int n, result;
clrscr();
printf("Enter a positive integer: ");
scanf("%d", &n);
result = fact(n);
printf("Factorial = %d", result);
getch();
}

int fact(int n) {
if (n > 1)
// sum() function calls itself
return n * fact(n-1);
else
return n;
}
Example 3: Fibonacci Series

#include<stdio.h>
#include<conio.h>
int fibonacci(int);
void main()
{
int n, i;
printf("Enter the number of element you want in series :\n");
scanf("%d",&n);
printf("fibonacci series is : \n");
for(i=0;i<n;i++)
{
printf("%d ",fibonacci(i));
}
getch();
}
int fibonacci(int i)
{
if(i==0)
return 0;
else if(i==1)
return 1;
else return (fibonacci(i-1)+fibonacci(i-2));
}
1. Library functions under stdio.h

This function is used to print the character, string, float, integer, octal
printf() and hexadecimal values onto the output screen

This function is used to read a character, string, numeric data from


scanf() keyboard.

getc() It reads character from file

putc() writes a character to file

fopen Open File

fclose Close File

2. Library functions under conio.h


a) clrscr() -This function is used to clear the output screen.
b) getch():
Use this function to read characters from the keyboard. This function is also used to hold
the output screen until the user enters any character. If you don’t use this function then the
output screen closes within a fraction of a second.
c) getche():
This function is similar to getch() function. The only difference is that this function also
prints the value entered by the user in the output window.

3. C library math.h functions

No. Function Description

1) ceil(number) rounds up the given number. It returns the integer value which is
greater than or equal to given number.

2) floor(number) rounds down the given number. It returns the integer value which
is less than or equal to given number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.


Code example: ceil, floor, and fabs
#include <stdio.h>
#include<conio.h>
#include <math.h>
void main() {
float x = 3.5, y=-3.6;
printf("ceil value of %f is %f \n", x, ceil(x));
printf("floor value of %f is %f \n", x, floor(x));
printf("absolute value of %f is %f \n", x, fabs(y));
getch();
}

Code example: sqrt, exp, and pow


#include <stdio.h>
#include<conio.h>
#include <math.h>
void main() {
float x = 4.0;
printf("square root of %f is %f. \n", x, sqrt(x));
printf("squared value of %f is %f. \n", x, pow(x,2));
printf("exp of %f is %f \n", x, exp(x));
getch();
}
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
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
By default, C programming uses call by value to pass arguments. In general, it means the
code within a function cannot alter the arguments used to call the function

#include<stdio.h>
void change(int);
int main()
{
int x=100;
printf("Before function call value of x in main=%d \n", x);
change(x);//passing value in function
printf("After function call value of x in main=%d \n", x);
return 0;
}
void change(int num)
{
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
Write a program to swap two numbers using call be value.
#include<stdio.h>
#include<conio.h>
void swap(int, int);
void main()
{
int no1, no2;
clrscr();
printf("Enter the 2 numbers");
scanf("%d%d",&no1,&no2);
printf("Numbers before swapping no1=%d and no2= %d",no1, no2);
swap(no1,no2);
getch();
}
void swap(int a, int b) {
int temp;
temp=a;
a=b;
b=temp;
printf("Numbers after swapping no1=%d and no2=%d",a,b);
}

Call by reference in C

o In call by reference, the address of the variable is passed into the function call as the
actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters
and actual parameters. All the operations in the function are performed on the value
stored at the address of the actual parameters, and the modified value gets stored at
the same address.

#include<stdio.h>
void change(int *);
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
void change(int *num) {
*num=*num+10;
printf("After adding value inside function num=%d \n", *num);
}

Scope of Variable:
A scope of variable defines an area in which the variable is accessible.
There are three places where variables can be declared in C programming language −
 Inside a function or a block which is called local variables.
 Outside of all functions which is called global variables.
 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>
#include<conio.h>
void main () {

/* local variable declaration */


int a, b;
int c;

/* actual initialization */
a = 10;
b = 20;
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>

/* global variable declaration */


int g;

int main () {

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}
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;

int main () {

/* local variable declaration */


int g = 10;

printf ("value of g = %d\n", g);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of g = 10
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.

You might also like