Programming in c - Unit_IV
Programming in c - Unit_IV
Syllabus:
Functions: The form of C functions, return values and types, calling a function,
categories of functions, Nested functions, Recursion, functions with arrays, call by
value, call by reference, storage classes-character arrays and string functions.
function
A function in C is a set of statements that when called perform some specific task. It
is the basic building block of a C program that provides modularity and code
reusability. The programming statements of a function are enclosed within { }
braces, having certain meanings and performing certain operations. They are also
called subroutines or procedures in other languages.
Syntax of Functions in C
1. Function Declaration
2. Function Definition
3. Function Calls
Function Declarations
In a function declaration, we must provide the function name, its return type, and the
number and type of its parameters. A function declaration tells the compiler that there
is a function with the given name defined somewhere else in the program.
Syntax
The parameter name is not mandatory while declaring functions. We can also declare
the function without using the name of the data variables.
Example
1
int sum(int a, int b); // Function declaration with parameter names
int sum(int , int); // Function declaration without parameter names
Function Declaration
Function Definition
The function definition consists of actual statements which are executed when the
function is called (i.e. when the program control comes to the function).
A C function is generally defined and declared in a single step because the function
definition always starts with the function declaration so we do not need to declare it
explicitly. The below example serves as both a function definition and a declaration.
2
Function Definition in C
Function Call
A function call is a statement that instructs the compiler to execute the function. We
use the function name and parameters in the function call.
In the below example, the first sum function is called and 10,30 are passed to the sum
function. After the function call sum of a and b is returned and control is also
returned back to the main function of the program.
3
Working of function in C
Note: Function call is neccessary to bring the program control to the function
definition. If not called, the function statements will not be executed.
In C, functions can return values to the calling code. Here's a breakdown of return
values and types:
Return Types:
Return Statement:
• The return statement is used to send a value back from the function to the
calling code.
• If the function has a void return type, the return statement can be used without
an expression to simply exit the function.
4
Example:
#include <stdio.h>
return a + b;
int main() {
return 0;
Explanation:
• The add function takes two integer arguments and returns their sum.
• The add function calculates the sum and returns it using the return statement.
Important Points:
The data type of the expression in the return statement must match the return type
declared in the function definition.
If no return type is specified, C assumes a default return type of int. However, it's
good practice to always explicitly specify the return type.
5
• Multiple Return Statements:
A function can have multiple return statements, but only one will be executed during
a single function call.
Calling a function
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. 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.
There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.
6
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 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.
Example:
#include <stdio.h>
int temp = a;
a = b;
b = temp;
int main() {
7
printf("Before swap: x = %d, y = %d\n", x, y);
// Call by value
swap(x, y);
return 0;
Output:
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.
Example:
#include <stdio.h>
*b = temp;
int main() {
// Call by reference
swap(&x, &y);
return 0;
OUTPUT:
9
With this method, the changes made to With this method, using addresses we
the dummy variables in the called would have an access to the actual
function have no effect on the values of variables and hence we would be able to
actual variables in the calling function. manipulate them.
A copy of the value is passed into the An address of value is passed into the
function function
Actual and formal arguments are created Actual and formal arguments are created
at the different memory location at the same memory location
Categories of Functions
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.
10
1. Library Function
A library function is also referred to as a “built-in function”. A compiler package
already exists that contains these functions, each of which has a specific meaning and
is included in the package. Built-in functions have the advantage of being directly
usable without being defined, whereas user-defined functions must be declared and
defined before being used.
For Example:
pow(), sqrt(), strcmp(), strcpy() etc.
Advantages of C library functions
• C Library functions are easy to use and optimized for better performance.
• C library functions save a lot of time i.e, function development time.
• C library functions are convenient as they always work.
Example:
// C program to implement
// the above approach
#include <math.h>
#include <stdio.h>
// Driver code
int main()
{
double Number;
Number = 49;
11
printf("The Square root of %.2lf = %.2lf",
Number, squareRoot);
return 0;
}
Output
The Square root of 49.00 = 7.00
User Defined Functions
A user-defined function is one that is defined by the user when writing any program,
as we do not have library functions that have predefined definitions. To meet the
specific requirements of the user, the user has to develop his or her own functions.
Such functions must be defined properly by the user. There is no such kind of
requirement to add any particular library to the program.
Different Types of User-defined Functions in C
There are four types of user-defined functions divided on the basis of arguments they
accept and the value they return:
1. Function with no arguments and no return value
2. Function with no arguments and a return value
3. Function with arguments and no return value
4. Function with arguments and with return value
1. Function with No Arguments and No Return Value
Functions that have no arguments and no return values. Such functions can either be
used to display information or to perform any task on global variables.
Syntax
// void return type with no arguments
void function_name()
{
// no return value
return;
}
Example
12
// C program to use function with
// no argument and no return values
#include <stdio.h>
void sum()
{
int x, y;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
printf("Sum of %d and %d is: %d", x, y, x + y);
}
// Driver code
int main()
{
// function call
sum();
return 0;
}
Output
Enter x and y
Sum of 4195522 and 0 is: 4195522
Explanation
In the above program, function sum does not take any arguments and has no return
values. It takes x and y as inputs from the user and prints them inside the void
function.
2. Function with No Arguments and With Return Value
13
Functions that have no arguments but have some return values. Such functions are
used to perform specific operations and return their value.
Syntax
return_type function_name()
{
// program
return value;
}
Example
// C program to use function with
// no argument and with return values
#include <stdio.h>
int sum()
{
int x, y, s = 0;
printf("Enter x and y\n");
// Driver code
int main()
{
// function call
printf("Sum of x and y is %d", sum());
return 0;
14
}
Output
Enter x and y
Sum of x and y is 4195536
Explanation
In the above program, function sum does not take any arguments and has a return
value as an integer type. It takes x and y as inputs from the user and returns them.
3. Function With Arguments and No Return Value
Functions that have arguments but no return values. Such functions are used to
display or perform some operations on given arguments.
Syntax
void function_name(type1 argument1, type2 argument2,...typeN argumentN)
{
// Program
return;
}
Example
// C program to use function with
// argument and no return values
#include <stdio.h>
// Driver code
int main()
{
15
int x, y;
printf("Enter x and y\n");
// function call
sum(x, y);
return 0;
}
Output
Enter x and y
Sum of 0 and 0 is: 0
Explanation
In the above program, function sum does take x and y as arguments and has no return
value. The main function takes x and y as inputs from the user and calls the sum
function to perform the print operation on the given arguments.
4. Function With Arguments and With Return Value
Functions that have arguments and some return value. These functions are used to
perform specific operations on the given arguments and return their values to the
user.
Syntax
return_type function_name(type1 argument1, type2 argument2,...typeN argumentN)
{
// program
return value;
}
Example
// C program to use function with
// argument and with return values
16
#include <stdio.h>
// Driver code
int main()
{
int x, y;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
// function call
printf("Sum of %d and %d is: %d", x, y, sum(x, y));
return 0;
}
Output
Enter x and y
Sum of 0 and 0 is: 0
Explanation
In the above program, function sum takes two arguments as x and y, and has a return
value as an integer type. The main function takes input x and y from the user and
calls the sum function to perform a specific operation on the given arguments and
returns the value.
17
Nested functions in C
• Nested functions in C refer to the ability to define functions within the scope
of other functions.
• Unlike many other programming languages, C traditionally doesn't support
nested functions.
• However, some compilers, such as GNU Compiler Collection (GCC), offer an
extension to the C language that enables nested functions.
• With nested functions, you can declare a function inside another function's
body.
• The nested function has access to all variables in the enclosing function's
scope, including local variables and parameters.
• This feature allows for more modular and readable code by encapsulating
related functionality within the context where it's needed.
Example
#include <stdio.h>
void outerFunction() {
int x = 10;
void innerFunction() {
printf("Inner function: %d\n", x);
}
innerFunction();
}
int main() {
outerFunction();
return 0;
}
Output
Inner function: 10
18
• In this example, outerFunction() is defined with a nested function
innerFunction() inside it.
• x is a local variable of outerFunction(). innerFunction() is called within
outerFunction().
• Inside innerFunction(), it prints the value of x.
Recursion in C
• Recursion is a programming technique where a function calls itself directly or
indirectly to solve a problem.
• In C, recursion is supported and commonly used for problems that can be
broken down into smaller, similar subproblems, such as calculating factorial,
Fibonacci series, or performing tree traversals.
• Base Case: Every recursive function must have a condition to stop the
recursion. This is known as the base case. Without a base case, the function
will recurse infinitely, leading to a stack overflow.
• Recursive Case: The part of the function where it calls itself with a modified
argument, moving closer to the base case
Example:
#include <stdio.h>
// Recursive function to calculate factorial
int factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! = 1
} else {
return n * factorial(n - 1); // Recursive case: n! = n * (n-1)!
}
}
int main() {
int num;
19
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Output:
Enter a number: 5
Factorial of 5 is 120
• The function factorial calls itself with the argument n-1 until it reaches the
base case where n == 0.
• Once the base case is reached, the recursion starts unwinding, multiplying the
results of the recursive calls.
STORAGE CLASSES IN C
In C programming, storage classes define the scope, visibility, and lifetime of
variables or functions. There are four main storage classes in C:
1. auto
• Scope: Local to the function in which it is declared.
• Lifetime: Exists only while the function is executing.
• Default: This is the default storage class for local variables.
• Example:
#include <stdio.h>
void example() {
auto int a = 10; // 'auto' is optional for local variables
printf("Value of a: %d\n", a);
}
int main() {
example();
return 0;
}
20
OUTPUT:
Value of a: 10
2. register
• Scope: Local to the function in which it is declared.
• Lifetime: Exists only while the function is executing.
• Optimization: Suggests to store the variable in a CPU register for faster
access (though this is not guaranteed).
• Example:
#include <stdio.h>
void example() {
register int counter = 0; // Stores counter in a CPU register (if
possible)
counter++;
printf("Value of counter: %d\n", counter);
}
int main() {
example();
return 0;
}
OUTPUT:
Value of counter: 1
3. static
• Scope:
o Local static variables: Scope is local to the function/block, but the value
persists across function calls.
o Global static variables or functions: Scope is restricted to the file in
which they are declared.
• Lifetime: Exists throughout the program's execution.
• Example:
#include <stdio.h>
21
void example() {
static int count = 0; // Value is retained between function calls
count++;
printf("Value of count: %d\n", count);
}
int main() {
example(); // count = 1
example(); // count = 2
example(); // count = 3
return 0;
}
OUTPUT:
Value of count: 1
Value of count: 2
Value of count: 3
4. extern
• Scope: Global, visible to all functions across different files (as long as it's
declared).
• Lifetime: Exists throughout the program's execution.
• Usage: Used to declare a global variable or function defined in another file.
• Example:
// file1.c
#include <stdio.h>
int x = 10; // Global variable definition
void printX() {
printf("Value of x in file1: %d\n", x);
}
// file2.c
#include <stdio.h>
22
extern int x; // Declare the variable defined in file1
void printX() {
printf("Value of x in file2: %d\n", x);
}
int main() {
printX(); // Uses x from file1
return 0;
}
These storage classes help control how and where variables are stored and accessed
in memory.
• auto: Default for local variables, limited to block scope.
• register: Suggests storing the variable in a CPU register.
• static: Retains value between function calls (local) or restricts scope to the file
(global).
• extern: Declares variables/functions defined in other files for global access.
23
Character Arrays
In C programming, character arrays are used to store a sequence of characters,
which is often referred to as a string. A string in C is simply an array of characters
terminated by a null character ('\0'). This null character marks the end of the string.
Declaring a Character Array
You can declare a character array like this:
char str[10];
This defines a character array str that can hold up to 9 characters (the 10th position is
for the null character \0).
Initializing a Character Array
1. At the time of declaration:
char str[] = "Hello";
Here, str will be a character array with 6 elements: H, e, l, l, o, and \0 (the null
character automatically added at the end).
2. Element by element:
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
This way, you manually assign the characters along with the null terminator.
Accessing Elements of a Character Array
You can access each character in the array just like you would in a normal array:
char str[] = "Hello";
printf("%c", str[1]); // Output: e
Reading and Printing Strings
You can use the scanf and printf functions for input and output of strings.
1. Using scanf and printf:
char name[20];
scanf("%s", name); // Reads input string
printf("Name: %s", name); // Prints the string
Note: scanf does not read spaces. To read strings with spaces, functions like gets() or
fgets() should be used (but gets() is unsafe and should be avoided).
24
2. Using fgets:
fgets(name, sizeof(name), stdin);
fgets reads a line of text, including spaces, until a newline or the size limit is reached.
Common Operations with Character Arrays
1. String Copy (strcpy):
char str1[] = "Hello";
char str2[10];
strcpy(str2, str1);
2. String Concatenation (strcat):
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // str1 now contains "Hello, World!"
3. String Length (strlen):
char str[] = "Hello";
int length = strlen(str); // length will be 5
• A character array is used to store a string in C.
• Strings are null-terminated, meaning they end with the \0 character.
• Functions like scanf, printf, strcpy, strcat, and strlen help in manipulating
strings.
String Functions
1. strlen()
• Purpose: Returns the length of a string (excluding the null terminator).
• Syntax: size_t strlen(const char *str);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Length of string: %lu\n", strlen(str));
25
return 0;
}
2. strcpy()
• Purpose: Copies a source string to a destination string.
• Syntax: char *strcpy(char *dest, const char *src);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
3. strncpy()
• Purpose: Copies up to n characters from the source string to the destination.
• Syntax: char *strncpy(char *dest, const char *src, size_t n);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[10];
strncpy(destination, source, 5);
destination[5] = '\0'; // Manually add null character
printf("Copied string: %s\n", destination);
return 0;
26
}
4. strcat()
• Purpose: Concatenates two strings, appending the source string to the
destination string.
• Syntax: char *strcat(char *dest, const char *src);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello, ";
char src[] = "World!";
strcat(dest, src);
printf("Concatenated string: %s\n", dest);
return 0;
}
5. strncat()
• Purpose: Concatenates up to n characters from the source string to the
destination string.
• Syntax: char *strncat(char *dest, const char *src, size_t n);
Example:
#include <stdio.h>
#include <string.h>
int main() {
char dest[20] = "Hello, ";
char src[] = "World!";
strncat(dest, src, 3); // Concatenates only "Wor"
printf("Concatenated string: %s\n", dest);
return 0;
}
27
6. strcmp()
• Purpose: Compares two strings lexicographically.
• Return Value:
o 0 if the strings are equal.
o A negative value if the first string is less than the second.
o A positive value if the first string is greater than the second.
• Syntax: int strcmp(const char *str1, const char *str2);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal\n");
} else if (result < 0) {
printf("str1 is less than str2\n");
} else {
printf("str1 is greater than str2\n");
}
return 0;
}
7. strncmp()
• Purpose: Compares up to n characters of two strings.
• Syntax: int strncmp(const char *str1, const char *str2, size_t n);
• Example:
#include <stdio.h>
28
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "Helium";
int result = strncmp(str1, str2, 3); // Compare first 3 characters
if (result == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
8. strchr()
• Purpose: Finds the first occurrence of a character in a string.
• Syntax: char *strchr(const char *str, int ch);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strchr(str, 'W');
if (ptr != NULL) {
printf("Character found: %s\n", ptr);
} else {
printf("Character not found\n");
}
return 0;
29
}
9. strrchr()
• Purpose: Finds the last occurrence of a character in a string.
• Syntax: char *strrchr(const char *str, int ch);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strrchr(str, 'o');
if (ptr != NULL) {
printf("Last occurrence of 'o': %s\n", ptr);
} else {
printf("Character not found\n");
}
return 0;
}
10. strstr()
• Purpose: Finds the first occurrence of a substring in a string.
• Syntax: char *strstr(const char *haystack, const char *needle);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
char *ptr = strstr(str, "World");
if (ptr != NULL) {
printf("Substring found: %s\n", ptr);
30
} else {
printf("Substring not found\n");
}
return 0;
}
11. strtok()
• Purpose: Splits a string into tokens based on a set of delimiters.
• Syntax: char *strtok(char *str, const char *delim);
• Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World! Welcome to C programming.";
char *token = strtok(str, " ");
strlen()
Returns the length of a string
strcpy()
Copies one string to another
strncpy()
Copies up to n characters of a string
strcat()
Concatenates two strings
strrchr()
Finds the last occurrence of a character
strstr()
Finds a substring within a string
34