C Programming
C Programming
UNIT IV - Function
Functions- Defining function - Accessing a function- Function Prototypes Passing arguments
to a functions- Passing arrays to a function- Passing Pointers to function- Recursion –
Dynamic memory allocation - malloc, calloc, realloc
Functions:
A function is a set of statements that take inputs, do some specific
computation and produces output.
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 procedure or subroutine in other programming languages.
Advantage of functions in C
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
Function Aspects:
o 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.
o Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
vkv
2
St1; //
St2;//function body;
}
3 Function call function_name (argument_list)
Types of Functions
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 user can use it many times.
3. As per the requirements, user can write their own instructions . It reduces the
complexity of a big program and optimizes the code.
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.
Let's see a simple example of C function that doesn't return any value from the function.
vkv
3
1. void hello()
2. {
3. printf("hello c");
4. }
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 C function that returns int value from the function.
1. int get()
2. {
3. return 10;
4. }
In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of
the method.
1. float get()
2. {
3. return 10.2;
4. }
Local Scope:
A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function:
Example
void myFunction() {
// Local variable that belongs to myFunction
int x = 5;
int main() {
myFunction();
vkv
4
Global Scope
A variable created outside of a function, is called a global variable and belongs to the global
scope. Global variables are available from within any scope, global and local:
Ex:
#include<stdio.h>
// Global variable x
int x = 5;
void myFunction() {
// We can use x here
printf("%d", x);
}
int main() {
myFunction();
vkv
5
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.
No args, With int func() int getVal() { return 42; } int x = getVal();
return
With args, With int func(int,int) int add(int a, int b) { return int s = add(3,5);
return a+b; }
Example 1
1. #include<stdio.h>
2. void printName();
3. void main ()
4. {
5. printf("Hello ");
6. printName();
7.
8. }
9. void printName()
10. {
11. printf("hi welcome");
12. }
Output
Hello hi welcome
vkv
6
Example 2
1. #include<stdio.h>
2. void sum();
3. void main()
4. {
5. printf("\nGoing to calculate the sum of two numbers:");
6. sum();
7. }
8. void sum()
9. {
10. int a,b;
11. printf("\nEnter two numbers");
12. scanf("%d %d",&a,&b);
13. printf("The sum is %d",a+b);
14. }
Output
The sum is 34
Output
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
Example 1
#include<stdio.h>
void 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); Actual
sum(a,b); Parameters
}
void sum(int c, int d)
{
printf("\nThe sum is %d",c+d); Formal
} Parameters
Output
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
Example 1
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
vkv
9
Output
Formal Parameter : A variable and its type as they appear in the prototype of the function
or method.
Pass by Value
Pass by Value, means that a copy of the data is made and stored by way of the name of
the parameter. Any changes to the parameter have NO affect on data in the calling
function.
o/p: 123
vkv
10
Pass by Reference
A reference parameter "refers" to the original data in the calling function. Thus any
changes made to the parameter are ALSO MADE TO THE ORIGINAL variable
Passing an array
#include <stdio.h>
void display(int age1, int age2)
{
printf("%d\n", age1);
printf("%d\n", age2);
}
int main()
{
int ageArray[] = {2, 8, 4, 12};
Ex:2
vkv
11
#include <stdio.h>
float calculateSum(float age[]);
int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
return sum;
}
Output
Result = 162.50
To pass an entire array to a function, only the name of the array is passed as an argument.
result = calculateSum(age);
Call by Reference:
vkv
12
To call a function by reference, you need to define it to receive the pointer to a variable in the
calling function. Here is the syntax that you would use to call a function by reference
type function_name(type *var1, type *var2, ...)
Both the actual and formal parameters refer to the same locations, so any changes made
inside the function are actually reflected in actual parameters of the caller.
Pass by reference using pointers as arguments in the function definition, and passing in
the 'address of' operator & on the variables when calling the function.
Ex: 2
#include <stdio.h> /* function declaration */
int add(int *, int *);
int main()
{
int a = 10, b = 20;
int c = add(&a, &b);
printf("Addition: %d", c);
}
int add(int *x, int *y)
{
int z = *x + *y;
return z; }
vkv
13
Call by value in C
o 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.
o In call by value method, we can not modify the value of the actual parameter by the
formal parameter.
o 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.
Recursion:
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function.
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 into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number, generating Fibonacci series, etc.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks
hi hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello
hello ………………………………………………………………….
o/p:
hi hello hello hello hello hello
vkv
15
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure given below:
vkv
16
Examples:
1. #include<stdio.h>
2. int main()
3. {
4. int n1=0,n2=1,n3,i,number;
5. printf("Enter the number of elements:");
6. scanf("%d",&number);
7. printf("\n%d %d",n1,n2);//printing 0 and 1
8. for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed {
9. n3=n1+n2;
10. printf(" %d",n3);
11. n1=n2;
12. n2=n3;
13. }
14. return 0;
15. }
vkv
17
Output:
1. #include<stdio.h>
2. void printFibonacci(int n)
3. {
4. static int n1=0,n2=1,n3;
5. if(n>0){
6. n3 = n1 + n2;
7. n1 = n2;
8. n2 = n3;
9. printf("%d ",n3);
10. printFibonacci(n-1);
11. }
12. }
13. int main(){
14. int n;
15. printf("Enter the number of elements: ");
16. scanf("%d",&n);
17. printf("Fibonacci Series: ");
18. printf("%d %d ",0,1);
19. printFibonacci(n-2);//n-2 because 2 numbers are already printed
20. return 0;
21. }
Output:
vkv
18
Output
vkv
19
#include <stdio.h>
if(num>0)
{
count++;
countDigits(num/10);
}
else
{
return count;
}
}
int main()
{
int number;
int count=0;
count=countDigits(number);
return 0;
}
Output
vkv
20
#include <stdio.h>
sum=sumDigits(number);
return 0;
}
Practice Programs:
Write C program for finding factorial of a number:
#include<stdio.h>
#include<conio.h>
void main()
{
int fact, i, n;
fact = 1;
printf("Enter the number\t");
vkv
21
scanf("%d" , &n);
for(i = 1; i <= n; i++)
{
fact = fact*i;
}
printf("Factorial of %d is %d", n , fact);
getch();
}
o/p:
Enter the number 5
Factorial of 5 is 120
int fact(int n)
{
int i,fact= 1;
for(i = 1; i <= n; i++)
{
fact = fact*i;
}
printf("Factorial of %d is %d", n , fact);
}
o/p:
vkv
22
#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
vkv
23
This C program is to find fibonacci series for first n terms using [Link] example, fibonacci
series for first 5 terms will be 0,1,1,2,3.
#include<stdio.h>
void fibo(int);
void main()
{
int n;
printf("\nEnter a number to generate fibonacci series for first n
terms\n",n);
scanf("%d",&n);
fibo(n);
}
void fibo(int n)
{
int i,c=0;
int a=0;
int b=1;
printf("Fibonacci series for %d terms:-\n",n);
for(i=0;i<n;i++)
{
printf("%d ",c);
a=b;
b=c;
c=a+b;
}
}
O/P:
Enter a number to generate fibonacci series for first n terms 6
Fibonacci series for 6 terms:- 011235
vkv
24
{
int N;
// Given number
printf("enter a number");
scanf("%d",&N);
// Function call
printf("%f ", findSQRT(N));
return 0;
}
O/P:
enter a number9
3.000000
To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and free() are used.
These functions are defined in the <stdlib.h> header file.
malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it returns
a pointer of void which can be casted into pointers of any form.
Syntax of malloc()
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes. And, the pointer ptr holds the
address of the first byte in the allocated memory
vkv
25
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr = (int *)malloc(sizeof(int) * 5);
o/p: 1 2 3 4 5
Assume that we want to create an array to store 5 integers. Since the size of int is 4 bytes, we need 5 * 4
bytes = 20 bytes of memory.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(20);
o/p: 1 2 3 4 5
In the above malloc call, we hardcoded the number of bytes we need to store 5 integers. But we know that
the size of the integer in C depends on the architecture. So, it is better to use the sizeof operator to find the
size of type you want to store.
vkv
26
calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero.
Syntax of calloc()
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr
vkv