C Unit 4
C Unit 4
What is a Function?
A function is a named block of code that performs a specific task. A function can take inputs
(called parameters), execute a block of statements, and optionally return a result.
A function allows you to write a piece of logic once and reuse it wherever needed in the
program.
This helps keep your code clean, organized, easier to understand and manage.
Why Do We Need Functions?
Source: [Link]
Function Syntax
Return type: Specifies the type of value the function will return. Use void if the function
does not return anything.
Function name: A unique name that identifies the function. It follows the same naming
rules as variables.
Parameter list: A set of input values passed to the function. If the function takes no
inputs, this can be left empty or written as void.
Function body: The block of code that runs when the function is called. It is enclosed in
curly braces { }.
Example:
Without using function With using functiom
printf("Hello\n"); void printHello()
printf("Hello\n"); { Function
printf("Hello\n"); printf("Hello\n"); definition
}
Function A declaration tells the compiler about the int add(int a, int b);
Declaration function's name, return type, and
parameters before it is actually used. It
does not contain the function's body. This
is often placed at the top of the program
or in a header file.
The declaration introduces the function to
the compiler, and the definition explains
what it actually does.
Function A definition provides the actual int add(int a, int b)
Definition implementation of the function. It includes {
the full code or logic that runs when the return a + b;
function is called. }
Once a function is defined, you can use it #include <stdio.h>
by simply calling its name followed by // Function definition
Calling a parentheses. This tells the program to int add(int a, int b)
Function execute the code inside that function. {
return a + b;
}
int main()
{
// Function call
int result = add(5, 3);
printf("The sum is: %d", result);
return 0;
}
Types of Functions:
[Link] Functions:
Library functions in C provides a wide range of functionalities and features including string
manipulation,input/output operations , mathematical calculations, file handling, memory
management and more. These functions are typically declared in header files and can be
accessed in the program by including the appropriate header file in your C program.
2. User-defined functions:
Example:
#include <stdio.h>
Output: The sum is: 8
void addition(int x, int y)
{
int tot = x + y;
printf("The sum is: %d\n", tot);
}
int main()
{
int x = 5,y=3;
addition(x, y);
return 0;
}
printf("%d", num);
return 0;
}
Type 4: Arguments and Return Value (Most Important)
✔ Takes input
✔ Returns value
Syntax Example
return_type functionName(type var1, type #include <stdio.h>
var2) int add(int a, int b)
{ {
return value; return a + b;
} }
int main()
{
int result;
result = add(10, 20);
printf("Sum = %d", result);
return 0;
}
Use of return Keyword in C
The return keyword is used to:
1. Send a value back to the calling function.
2. Terminate (end) the execution of a function.
Why Do We Use return?
To give output from a function.
To stop function execution.
To transfer control back to main() or calling function.
}
int main()
{
printf("%d", x); // Error: x not declared
}
Characteristics of Local Variables:
Declared inside function
Scope limited to that function
Created when function starts
Destroyed when function ends
Global Variables
A global variable is declared outside all functions.
It can be accessed by all functions in the program.
#include <stdio.h> Output:
int x = 100; // Global variable x = 100
void display() x = 100
{
printf("x = %d\n", x);
}
int main()
{
display();
printf("x = %d", x);
return 0;
}
Characteristics of Global Variables
Declared outside functions
Accessible throughout program
Lifetime is entire program execution
Stored in global memory area
Combined example of local and global variable:
#include <stdio.h>
int x = 50; // Global variable
void test() Output:
{ Global x = 50
int y = 20; // Local variable Local y = 20
printf("Global x = %d\n", x); Global x in main = 50
printf("Local y = %d\n", y);
}
int main()
{
test();
printf("Global x in main = %d", x);
return 0;
}
Exercise:
// Program to Find Square of a Number Using
Function
#include <stdio.h>
// Function declaration
int square(int a);
int main()
{
int num, result;
printf("Enter a number: ");
scanf("%d", &num);
result = square(num); // Function call
printf("Square = %d", result);
return 0;
}
// Function definition
int square(int a)
{
return a * a;
}
7 prepared by: yogita k
8
// Function definition
float simpleInterest(float p, float r, float t) {
return (p * r * t) / 100;
}
int main() {
int num;
return 0;
}
// Function definition
void checkPrime(int n) {
int i, flag = 0;
if(n <= 1) {
printf("Not Prime");
return;
}
flag = 1;
break;
}
}
if(flag == 0)
printf("Prime Number");
else
printf("Not Prime");
}
Program to Swap Two Numbers Using Function (Call by
Value)
#include <stdio.h>
// Function declaration
void swap(int a, int b);
int main() {
int x, y;
return 0;
}
// Function definition
void swap(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
// Function call
checkOddEven(number);
return 0;
}
// Function definition
void checkOddEven(int num) {
if (num % 2 == 0)
printf("%d is Even.\n", num);
else
printf("%d is Odd.\n", num);
}
#include <stdio.h> 10 is Even.
// Function declaration 5 is Odd.
void checkOddEven(int num); 14 is Even.
int main()
{
// Passing value to function (Call by Value)
checkOddEven(10);
checkOddEven(5);
checkOddEven(14);
return 0;
}
// Function definition
void checkOddEven(int num) {
if (num % 2 == 0)
printf("%d is Even.\n", num);
else
printf("%d is Odd.\n", num);
}
#include <stdio.h> Factorial of 5 is 120
// Function declaration
long int factorial(int n);
int main()
{
int number = 5; // Value assigned directly
long int result;
// Function call
result = factorial(number);
printf("Factorial of %d is %ld\n", number, result);
return 0;
}
// Function definition
long int factorial(int n)
{
int i;
long int fact = 1;
for(i = 1; i <= n; i++) {
fact = fact * i;
}
return fact;
}
C String Functions
C language provides various built-in functions that can be used for various operations and
manipulations on strings. These string functions make it easier to perform tasks such as
string copy, concatenation, comparison, length, etc.
The <string.h> header file contains these string functions.
strlen()
The strlen() function is used to find the length of a string. It returns the number of
characters in a string, excluding the null terminator ('\0').
#include <stdio.h> 11
#include <string.h>
int main() {
char s[] = "vidyalankar";
// Finding and printing length of string s
printf("%lu", strlen(s));
return 0;
}
strcpy()
The strcpy() function copies a string from the source to the destination. It copies the entire
string, including the null terminator.
#include <stdio.h> Hello
#include <string.h>
int main() { Hello
char src[] = "Hello";
char dest[20];
// Copies "Hello" to dest
strcpy(dest, src);
printf("%s", src);
printf("\n%s", dest);
return 0;
}
strcat()
The strcat() function is used to concatenate (append) one string to the end of another. It
appends the source string to the destination string, replacing the null terminator of the
destination with the source string’s content.
#include <stdio.h> Hello, IF2K-A
#include <string.h>
int main() {
char s1[30] = "Hello, ";
char s2[] = "IF2K-A";
int main() {
char s1[] = "Apple";
char s2[] = "Applet";
// Compare two strings
// and print result
int res = strcmp(s1, s2);
if (res == 0)
printf("s1 and s2 are same");
else if (res < 0)
printf("s1 is lexicographically "
"smaller than s2");
else
printf("s1 is lexicographically "
"greater than s2");
return 0;
}
return 0;
}
strrev()
strrev() is a function used to reverse a string. It changes the original string into reverse
order.
Syntax: strrev(string_name);
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter a string: ");
scanf("%s", str);
strrev(str);
printf("Reversed String: %s", str);
return 0;
}
Note: strrev() is not a standard C function.
It is available in Turbo C
Output:
int main()
{
char str[50];
int i, len;
len = strlen(str);
return 0;
}
Math Function in C
Math functions in C are predefined library functions used to perform mathematical
operations such as square root, power, logarithm, trigonometric calculations, rounding, etc.
All mathematical functions are declared in the <math.h> header file.
Common Math Functions are:
Function Syntax Description Header File
sqrt() sqrt(x) Square root of x <math.h>
pow() pow(x,y) x raised to power y <math.h>
ceil() ceil(x) Rounds value upward <math.h>
}
Summary of getchar() and putchar()
Line Meaning
#include <stdio.h> Used for input/output functions like printf()
#include <stdlib.h> Used for memory functions like malloc() and free()
int *ptr; Declares a pointer variable to store address of integer
memory
malloc(3 * sizeof(int)) Allocates memory for 3 integer values dynamically
(int*) Typecasting to integer pointer
ptr == NULL Checks whether memory allocation failed
printf("Memory not allocated"); Executes if allocation fails
printf("Memory allocated Executes if allocation succeeds
successfully");
free(ptr); Releases allocated memory
return 0; Ends program successfully
calloc()
calloc() is used to allocate memory for multiple elements and initializes them to zero.
17 prepared by: yogita k
18
Line Explanation
#include <stdio.h> Used for input/output functions like printf()
#include <stdlib.h> Required for memory functions like calloc() and free()
int *ptr; Declares a pointer variable to store address of allocated memory
calloc(3, sizeof(int)) Allocates memory for 3 integer elements
(int*) Typecasting to integer pointer
3 Number of elements to allocate
sizeof(int) Size of each integer element
ptr == NULL Checks if memory allocation failed
free(ptr); Frees (releases) allocated memory
return 0; Ends the program successfully
Summary of malloc() and calloc()
Recursive functions
A recursive function in C is a function that calls itself. A recursive function is used when a
certain problem is defined in terms of itself. Although it involves iteration, using iterative
approach to solve such problems can be tedious. Recursive approach provides a very concise
solution to seemingly complex problems.
Syntax:
void recursive_function()
{
recursion(); // function calls itself
}
int main(){
recursive_function();
}
Examples:
Sum of Natural Numbers without recursion Sum of Natural Numbers with recursion
#include <stdio.h> #include <stdio.h>
int main() int sum(int n)
{ {
int n = 6; if(n == 1) // base condition
int sum = 0; return 1;
int i; else
for(i = 1; i <= n; i++) return n + sum(n - 1); // recursive call
{ }
sum = sum + i; int main()
} {
printf("Sum = %d", sum); int num = 6;
return 0; printf("Sum = %d", sum(num));
} return 0;
}
Output:
Sum = 21 Output:
Sum = 21
Explanation
Memory Representation
Main Function
x = 10 y = 20
copy copy
Function swap()
a = 10 b = 20
2. Call by Reference
Definition
In Call by Reference, the address of variables is passed to the function using pointers.
The function works with the original memory location, so changes inside the function
affect the original variable.
Key Point