0% found this document useful (0 votes)
4 views26 pages

C Programming

The document provides an overview of functions in C programming, including their definition, advantages, types, and aspects such as declaration, definition, and calling. It explains how to pass arguments to functions, including passing by value and by reference, as well as passing arrays and pointers. Additionally, it covers the scope of variables, function prototypes, and provides examples to illustrate various function types and their usage.

Uploaded by

utkrshtata
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)
4 views26 pages

C Programming

The document provides an overview of functions in C programming, including their definition, advantages, types, and aspects such as declaration, definition, and calling. It explains how to pass arguments to functions, including passing by value and by reference, as well as passing arrays and pointers. Additionally, it covers the scope of variables, function prototypes, and provides examples to illustrate various function types and their usage.

Uploaded by

utkrshtata
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

1

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

There are the following advantages of C functions.

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:

There are three aspects of a C function.


o Function declaration A function must be declared globally in a c program to tell the
compiler about the function name, function parameters, and return type.

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.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function definition return_type function_name (argument list)


{

vkv
2

St1; //
St2;//function body;
}
3 Function call function_name (argument_list)

The syntax of creating function in c language is given below:

return_type function_name(data_type parameter...)


{
//code to be executed
}

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

Example without return value:

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.

Example with return value:

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

Scope of variables in function:


In C, variables are only accessible inside the region they are created. This is called scope.
Outside this region, we cannot access the variable, and it is treated as an undeclared identifier.

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;

// Print the variable x


printf("%d", x);
}

int main() {
myFunction();

vkv
4

printf("%d", x); // ERROR “x undeclared variable”


return 0;
}

A local variable cannot be used outside the function it belongs to.


If you try to access it outside the function, an error occurs.

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();

// We can also use x here


printf("%d", x);
return 0;
}

Function Prototype & Accessing function:


A function prototype (also called a function declaration) informs the compiler about a function's return
type, name, and parameter types before the function is actually defined. This allows the compiler to
perform type checking on function calls.

Why Are Prototypes Needed?


• Enable the compiler to check argument types and count at call sites
• Allow functions to be called before their definition appears in the code
• Essential for multi-file projects where functions are defined in separate .c files
• Typically placed in header files (.h) for sharing across source files

vkv
5

Function Access / call :

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

Category Signature Example Usage (Function call)

No args, No return void func() void greet() { greet();


printf("Hello!"); }

With args, No void func(int) void show(int n) { show(10);


return printf("%d", n); }

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 for Function without argument and without return value

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

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value


1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }

Output

Going to calculate the sum of two numbers:


Enter two numbers 10 24 The sum is 34
vkv
7

Example 2: program to calculate the area of the square

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

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 without return value

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

Going to calculate the sum of two numbers:

Enter two numbers 10 24 The sum is 34


vkv
8

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

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

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 with argument and with return value

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

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Passing Parameters in C functions:


A Parameter is the symbolic name for "data" that goes into a function. There are two ways to
pass parameters in C: Pass by Value, Pass by Reference. (call by value , call by reference)

Formal Parameter : A variable and its type as they appear in the prototype of the function
or method.

Actual Parameter : The variable or expression corresponding to a formal parameter that


appears in the function or method call in the calling environment.+

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

#include <stdio.h> int main() {


int x = 1;
// Function that takes parameters by value
void func(int val) { // Passing x by value to func()
func(x);
// Changing the value printf("%d", x);
val = 123;
printf(‘%d’,val) return 0;
} }

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

#include <stdio.h> int main() {


//Function that takes parameters by int x = 1;
//pointer
void func(int *val) { // Passing address of x
func(&x);
// Changing the value printf("%d", x);
*val = 123; return 0;
} }

Passing arrays to a function in C


In c programming, array elements can be passed in the function. It can be passed as
individual or entire elements.

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

// Passing second and third elements to display()


display(ageArray[1],ageArray[2]);
return 0;
}
Output 8 4

Ex:2

// Program to calculate the sum of array elements by passing to a function

vkv
11

#include <stdio.h>
float calculateSum(float age[]);

int main() {
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};

// age array is passed to calculateSum()


Float result = calculateSum(age);
printf("Result = %.2f", result);
return 0;
}

float calculateSum(float age[])


{

float sum = 0.0;

for (int i = 0; i < 6; ++i)


{
sum += age[i]; //sum= sum+age[i]
}

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);

Passing Pointers to function:


A Pointer in C is a variable that stores the address of another variable. It acts as a reference to the
original variable. A pointer can be passed to a function, just like any other argument is passed.
A function in C can be called in two way
 Call by Reference
 Call by Value

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.

// C program to illustrate Call by // Function to swap two variables


Reference // by references
void swapx(int* x, int* y)
#include <stdio.h> {
// Function Prototype int t;
void swapx(int*, int*); t = *x;
*x = *y;
int main() *y = t;
{ printf("x=%d y=%d\n", *x, *y);
int a = 10, b = 20; }
// Pass reference
swapx(&a, &b); Output:
printf("a=%d b=%d\n", a, b); x=20 y=10
return 0; a=20 b=10
}

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.

// C program to illustrate call by value


}
#include <stdio.h>
// Swap functions that swapstwo values
// Function Prototype void swapx(int x, int y)
void swapx(int x, int y); {
int main() int t;
{ t = x;
int a = 10, b = 20; x = y;
y = t;
// Pass by Values printf("x=%d y=%d\n", x, y);
swapx(a, b); }

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


x=20 y=10
return 0; a=10 b=20

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

1. #include <stdio.h> 2. int f1();


vkv
14

3. int main() 9. int f1()


4. { 10. {
5. printf ("hi"); 11. printf("hello");
6. f1(); 12. f1();
7. return 0; 13. return 0;
8. } 14. }

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

Recusive fuction with proper exit condition:

#include <stdio.h> Static int n=0;


int f1(); n++;
int main()
{ if(n!=5)
printf("hi"); {
f1(); printf("hlo");
return 0; f1();
} }

int f1() return 0;


{ }

o/p:
hi hello hello hello hello hello

vkv
15

In the following example, recursion is used to calculate the factorial of a number.

1. #include <stdio.h> 13. if (n==0)


2. int fact (int); 14. {
3. int main() 15. return 1;
4. { 16. }
5. int n,f; 17. else if ( n == 1)
6. printf("Enter the number whose factorial you want to 18. {
calculate?"); 19. return 1;
7. scanf("%d",&n); 20. }
8. f = fact(n); 21. else
9. printf("factorial = %d",f); 22. {
10. } 23. return n*fact(n-1);
11. int fact(int n) 24. }
12. {
25. }

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

Sum of n-Natural Numbers Using Recursion }


int sum(int n) {
#include <stdio.h> if (n != 0)
int sum(int n); // sum() function calls itself
return n + sum(n-1);
int main() { else
int number, result; return n;
}
printf("Enter a positive integer: ");
scanf("%d", &number); Output
result = sum(number); Enter a positive integer:3
sum = 6
printf("sum = %d", result);
return 0;

Examples:

Fibonacci Series in C without recursion

Let's see the fibonacci series program in c without recursion.

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:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Fibonacci Series using recursion in C

Let's see the fibonacci series program in c using recursion.

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:

Enter the number of elements:15


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

vkv
18

Calculate power of a number program using recursion.


/*C program to calculate power of any number using recursion*/
1
2 #include <stdio.h>
3
4 //function for calculating power
5
6 long int getPower(int b,int p)
7 {
8 long int result=1;
9 if(p==0)
10 { return result; }
11 result=b*(getPower(b,p-1)); //call function again
12 }
13 int main()
14 {
15 int base,power;
16 long int result;
17
18 printf("Enter value of base: ");
19 scanf("%d",&base);
20
21 printf("Enter value of power: ");
22 scanf("%d",&power);
23
24 result=getPower(base,power);
25
26 printf("%d to the power of %d is: %ld\n",base,power,result);
27
28 return 0;
}

Output

Enter value of base: 10


Enter value of power: 4
10 to the power of 4 is: 10000

vkv
19

Program to count digits in C using recursion


/*C program to count digits using recursion.*/

#include <stdio.h>

//function to count digits


int countDigits(int num)
{
static int count=0;

if(num>0)
{
count++;
countDigits(num/10);
}
else
{
return count;
}
}
int main()
{
int number;
int count=0;

printf("Enter a positive integer number: ");


scanf("%d",&number);

count=countDigits(number);

printf("Total digits in number %d is: %d\n",number,count);

return 0;
}

Output

Enter a positive integer number: 123


Total digits in number 123 is: 3

Write a program to Sum of digits of a number using recursion.

vkv
20

/*C program to find sum of all digits using recursion.*/

#include <stdio.h>

//function to calculate sum of all digits


int sumDigits(int num)
{
static int sum=0;
if(num>0)
{
sum+=(num%10); //add digit into sum
sumDigits(num/10);
}
else
{
return sum;
}
}
int main()
{
int number,sum;

printf("Enter a positive integer number: ");


scanf("%d",&number);

sum=sumDigits(number);

printf("Sum of all digits are: %d\n",sum);

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

Write C program for finding factorial of a number using function:


#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
int n;
printf("Enter the number\t");
scanf("%d" , &n);
fact(n);
getch();
}

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

Enter the number 5


Factorial of 5 is 120

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

vkv
23

C program to find fibonacci series for first n terms using function

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

C program to find square root of a given number:


#include <math.h>
#include <stdio.h>
// Function to find the square-root of N
double findSQRT(double N)
{
return sqrt(N);
}
int main()

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

Dynamic Memory Allocation in C


Dynamic memory allocation allows a programmer to allocate, resize, and free memory at runtime.
Sometimes the size of the array you declared may be insufficient. To solve this issue, you can allocate
memory manually during run-time. This is known as dynamic memory allocation in C programming.

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()

ptr = (castType*) malloc(size);

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);

// Populate the array


for (int i = 0; i < 5; i++)
ptr[i] = i + 1;

// Print the array


for (int i = 0; i < 5; i++)
printf("%d ", ptr[i]);
return 0;
}

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);

// Populate the array


for (int i = 0; i < 5; i++)
ptr[i] = i + 1;

// Print the array


for (int i = 0; i < 5; i++)
printf("%d ", ptr[i]);
return 0;
}

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()

ptr = (castType*)calloc(n, size);


Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of type float.

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

You might also like