Unit 4
Unit 4
C Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. 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 procedureor subroutinein other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
By using functions, we can avoid rewriting same logic/code again and again in a program.
We can call C functions any number of times in a program and from any place in a program.
We can track a large C program easily when it is divided into multiple functions.
Reusability is the main achievement of C functions.
However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same number
of functions as it is declared in the function declaration.
Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
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.
C Function
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common
place called the library. Such functions are used to perform some specific operations. For
example, printf is a library function used to print on the console. The library functions are
created by the designers of compilers. All C standard library functions are defined inside
the different header files saved with the extension .h. We need to include these header files
in our program to make use of the library functions defined in such header files. For
example, To use the library functions such as printf/scanf we need to include stdio.h in our
program which is a header file that contains all the library functions regarding standard
input/output.
The list of mostly used header files is given in the following table.
SN Header file Description
1 stdio.h This is a standard input/output header file. It contains all the library
functions regarding standard input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(),
calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like
sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.
User-defined function
You can also create functions as per your need. Such functions created by the user are
known as user-defined functions.
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
The execution of a C program begins from the main() function.
void functionName()
And, the compiler starts executing the codes inside functionName().
The control of the program jumps back to the main() function once code inside the function
definition is executed.
Working of C Function
Note, function names are identifiers and should be unique.
This is just an overview of user-defined functions. Visit these pages to learn more on:
C User-defined functions
In this tutorial, you will learn to create user-defined functions in C programming with the
help of an example.
C allows you to define functions according to your need. These functions are known as
user-defined functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color. You
can create two functions to solve this problem:
createCircle() function
color() function
Example: User-defined function
Here is an example to add two integers. To perform this task, we have created an user-
defined addNumbers().
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
return 0;
}
Function prototype
A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used
in the program.
In the above example, int addNumbers(int a, int b); is the function prototype which
provides the following information to the compiler:
Calling a function
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call
functionName(argument1, argument2, ...);
In the above example, the function call is made using addNumbers(n1, n2); statement
inside the main() function.
Function definition
Function definition contains the block of code to perform a specific task. In our example,
adding two numbers and returning it.
Syntax of function definition
When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.
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 the return
statement.
In the above example, the value of the result variable is returned to the main function.
The sum variable in the main() function is assigned this value.
Syntax of return statement
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in the function
prototype and function definition must match.
#include <stdio.h>
void checkPrimeNumber();
int main() {
checkPrimeNumber(); // argument is not passed
return 0;
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
The checkPrimeNumber() function takes input from the user, checks whether it is a prime
number or not, and displays it on the screen.
The empty parentheses in checkPrimeNumber(); inside the main() function indicates that
no argument is passed to the function.
The return type of the function is void. Hence, no value is returned from the function.
#include <stdio.h>
int getInteger();
int main() {
int n, i, flag = 0;
// no argument is passed
n = getInteger();
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
return n;
}
int main() {
int n;
return 0;
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
The integer value entered by the user is passed to the checkPrimeAndDisplay() function.
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a
prime number or not and displays the appropriate message.
int main() {
int n, flag;
if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
int i;
return 0;
}
The input from the user is passed to the checkPrimeNumber() function.
The checkPrimeNumber() function checks whether the passed argument is prime or not.
If the passed argument is a prime number, the function returns 0. If the passed argument is
a non-prime number, the function returns 1. The return value is assigned to
the flag variable.
Depending on whether flag is 0 or 1, an appropriate message is printed from
the main() function.
C Recursion
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
int main()
{
... .. ...
recurse();
... .. ...
}
Working of Recursion
The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used where
one branch makes the recursive call, and other doesn't.
int main() {
int number, result;
result = sum(number);
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.
Sum of Natural Numbers
C Pointers
In this tutorial, you'll learn about pointers; what pointers are, how do you use them and the
common mistakes you might face when working with them with the help of examples.
Pointers are powerful features of C and C++ programming. Before we learn pointers, let's
learn about addresses in C programming.
Address in C
If you have a variable var in your program, &var will give you its address in the memory.
We have used address numerous times while using the scanf() function.
scanf("%d", &var);
Here, the value entered by the user is stored in the address of var variable. Let's take a
working example.
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
Output
var: 5
address of var: 2686778
C Pointers
Pointers (pointer variables) are special variables that are used to store addresses
rather than values.
Pointer Syntax
int* p;
int *p1;
int * p2;
int* pc, c;
c = 5;
pc = &c;
To get the value of the thing pointed by the pointers, we use the * operator. For
example:
int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc); // Output: 5
Here, the address of c is assigned to the pc pointer. To get the value stored in that
address, we used *pc .
Note: In the above example, pc is a pointer, not *pc . You cannot and should not do
something like *pc = &c ;
By the way, * is called the dereference operator (when working with pointers). It
operates on a pointer and gives the value stored in that pointer.
int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc); // Ouptut: 1
printf("%d", c); // Output: 1
int* pc, c, d;
c = 5;
d = -15;
#include <stdio.h>
int main()
{
int* pc, c;
c = 22;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 22
c = 11;
printf("Address of pointer pc: %p\n", pc);
printf("Content of pointer pc: %d\n\n", *pc); // 11
*pc = 2;
printf("Address of c: %p\n", &c);
printf("Value of c: %d\n\n", c); // 2
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of c: 2686784
Value of c: 2
2. c = 22;
This assigns 22 to the variable c . That is, 22 is stored in the memory location of
variable c .
3. pc = &c;
4. c = 11;
5. *pc = 2;
This change the value at the memory location pointed by the pointer pc to 2.
Common mistakes when working with pointers
int c, *pc;
#include <stdio.h>
int main() {
int c = 5;
int *p = &c;
printf("%d", *p); // 5
return 0;
}
int *p = &c;
is equivalent to
int *p:
p = &c;
In both cases, we are creating a pointer p (not *p ) and assigning &c to it.
To avoid this confusion, we can use the statement like this:
int* p = &c;
In this tutorial, you'll learn about the relationship between arrays and pointers in C
programming. You will also learn to access array elements using pointers.
Before you learn about the relationship between arrays and pointers, be sure to check
these two topics:
C Arrays
C Pointers
An array is a block of sequential data. Let's write a program to print addresses of array
elements.
#include <stdio.h>
int main() {
int x[4];
int i;
for(i = 0; i < 4; ++i) {
printf("&x[%d] = %p\n", i, &x[i]);
}
return 0;
}
Output
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448
From the above example, it is clear that &x[0] is equivalent to x. And, x[0] is equivalent
to *x.
Similarly,
#include <stdio.h>
int main() {
return 0;
}
Enter 6 numbers: 2
3
4
4
12
4
Sum = 29
Here, we have declared an array x of 6 elements. To access elements of the array, we have
used pointers.
In most contexts, array names decay to pointers. In simple words, array names are
converted to pointers. That's the reason why you can use pointers to access elements of
arrays. However, you should remember that pointers and arrays are not the same.
There are a few cases where array names don't decay to pointers.
#include <stdio.h>
int main() {
return 0;
}
*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2
In this example, &x[2], the address of the third element, is assigned to the ptr pointer.
Hence, 3 was displayed when we printed *ptr.
And, printing *(ptr+1) gives us the fourth element. Similarly, printing *(ptr-1) gives us the
second element.
In this tutorial, you'll learn to pass addresses and pointers as arguments to functions with
the help of examples.
To accept these addresses in the function definition, we can use pointers. It's because
pointers are used to store addresses. Let's take an example:
#include <stdio.h>
void swap(int *n1, int *n2);
int main()
{
int num1 = 5, num2 = 10;
num1 = 10
num2 = 5
The address of num1 and num2 are passed to the swap() function using swap(&num1,
&num2);.
Pointers n1 and n2 accept these arguments in the function definition.
When *n1 and *n2 are changed inside the swap() function, num1 and num2 inside
the main() function are also changed.
Inside the swap() function, *n1 and *n2 swapped. Hence, num1 and num2 are also
swapped.
Notice that swap() is not returning anything; its return type is void.
#include <stdio.h>
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
Here, the value stored at p, *p, is 10 initially.
We then passed the pointer p to the addOne() function. The ptr pointer gets this address
in the addOne() function.
Inside the function, we increased the value stored at ptr by 1 using (*ptr)++;.
Since ptr and p pointers both have the same address, *p inside main() is also 11.
Let's understand call by value and call by reference in c language one by one.
Call by value in C
In 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 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 formal
parameter is the argument which is used in the function definition.
Let's try to understand the concept of call by value in c language by the example given
below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
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
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.
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
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 = 20, b = 10
1 A copy of the value is passed into the An address of value is passed into the
function function
2 Changes made inside the function is Changes made inside the function validate
limited to the function only. The values outside of the function also. The values of
of the actual parameters do not change the actual parameters do change by
by changing the formal parameters. changing the formal parameters.
3 Actual and formal arguments are Actual and formal arguments are created
created at the different memory
location at the same memory location
Output
Enter elements: 1
2
3
5
4
You entered:
1
2
3
5
4