UNIT III
Functions in C
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.
In c, there are two types of functions.
• Pre-defined functions
• User defined function.
Built in / Pre-Defined functions in C:-
These functions already exist in the libraries and we need not declare and
define these functions. We can directly call these functions by including the
header files in which these functions are present. For example, by using
stdio.h header file, we can perform scanf(), printf() functions, scanf() is used
to take input from the user and printf() is used to print the output on the
console screen.
Some of the predefined functions and their header files
S. Header
Description Functions
No file
In this header file we have printf (), scanf (), getc (), putc (),
1 stdio.h standard input and output fopen (), fclose (), remove (),
functions. fflush ().
This header file consist of
clrscr (), getch (), getche (),
2 conio.h console input and out put
textcolour (), textbackground ().
functions.
strlen (), strrev (), strcat (), strcmp
This header file consist of
3 string.h (), strchr (), strcpy (), strupr (),
string handling functions.
strlwr (), strset (), etc.
All function related to maths pow (), sqrt (), sin (), tan (), log (),
4 math.h are present in this header tanh (), sinh (), floor (), round (),
file. ceil (), etc.
setdate (), getdate (), clock (), time
Time related functions are
5 Time.h (), difftime (), strftime (), mktime (),
defined in this header file.
ctime (), asctime (), etc.
Standard Mathematical Functions in C:
Standard mathematical functions in C refer to the set of built-in
mathematical operations provided by the C programming language through
its standard library. These functions allow programmers to perform various
mathematical computations conveniently within their C programs.
1. Trigonometric Functions: These functions deal with angles and are
extensively used in geometry, physics, and engineering.
- sin(x): Computes the sine of the angle x
- cos(x): Computes the cosine of the angle x.
- tan(x): Computes the tangent of the angle x
2. Exponential and Logarithmic Functions: These functions deal with
exponential and logarithmic calculations.
- exp(x): Computes the exponential function of x (e^x).
- log(x): Computes the natural logarithm x.
- log10(x): Computes the common logarithm (base 10) of x.
- pow(x, y): Computes x raised to the power of y (xy).
- sqrt(x): Computes the square root of x.
These functions are declared in the math.h header file. Before using them,
ensure to include this header at the beginning of your C program. Standard
mathematical functions in C provide a powerful toolkit for performing
complex mathematical computations in C programs efficiently and
accurately.
For example:
#include <stdio.h>
#include <math.h>
void main( )
float x = 2.5;
float y = sin(x);
printf("sin (2.5) = %f\n", y);
Example 2:
#include <stdio.h>
#include <math.h>
void main()
float radius, area;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
area = 3.14 * pow (radius, 2);
printf("The area of the circle with radius %.f is: %f\n", radius, area);
Input output functions in C:
In C programming, input and output (I/O) operations can be categorized
into two main types: formatted and unformatted I/O functions. These two
types differ in how they handle data formatting and buffering.
Formatted Input / Output Functions: Formatted input/output functions
in C provide a structured way to read input from users and display output
to the console or files. Formatted I/O functions use format specifier and
are useful when you need precise control over the appearance of your input
and output data. They allow you to specify the format, precision, and other
formatting options for the data being processed. For example printf and
scanf are formatted input output functions
These functions are called formatted I/O functions because we can use
format specifiers in these functions and hence, we can format these
functions according to our needs.
List of some format specifiers-
S Format
Type Description
NO Specifier
.
1 %d int/signed int used for I/O signed integer value
2 %c char Used for I/O character value
3 %f float Used for I/O decimal floating-point value
Used for I/O string/group of characters
4 %s string
These functions offer precise control over the appearance and interpretation
of data, allowing developers to format data according to specific
requirements.
1. printf ( ):
Used for formatted output to the standard output stream. Allows developers
to specify placeholders in the output string for various data types, such as
%d for integers, %f for float, %s for strings, and more.
For example:
int num = 10;
printf("The value of num is %d\n", num);
Output: `The value of num is 10`
2. scanf( ):
Used for formatted input from the standard input stream (usually the
keyboard). Specifies the expected format of the input data, similar to printf(
).
For Example
int num;
printf("Enter an integer: ");
scanf("%d", &num);
This code snippet reads an integer entered by the user.
Advantages of Formatted Input/Output Functions:
- Precision: Allows precise control over data formatting, ensuring that data
is displayed or interpreted correctly.
- Flexibility: Provides a wide range of format specifiers and options to
format data in various ways.
- Portability: Formatted input/output functions are standard across
different C implementations and platforms, ensuring code portability.
Both printf() and `scanf()` are powerful functions that provide a convenient
way to interact with users through the console. However, it's crucial to
handle errors and edge cases appropriately when using them to ensure
robustness and reliability in your C programs.
Unformatted I/O Functions: Unformatted I/O functions do not use any
format specifier and are simpler and more straightforward to use compared
to formatted I/O functions. They are suitable for cases where precise
formatting is not necessary, such as reading a single character or a line of
text from the user. For example getc( ), getch ( ) etc
Unformatted I/O functions are used only for character data type or
character array/string and cannot be used for any other datatype. These
functions are used to read single input from the user at the console and it
allows to display the value at the console.
These functions are called unformatted I/O functions because we cannot
use format specifiers in these functions and hence, cannot format these
functions according to our needs.
The following are unformatted I/O functions
• getc ()
• getch()
• getche()
• getchar()
• gets()
• putc()
• putchar()
• puts()
• putch()
1. getc ():
In C programming, getc( ) is a standard library function used to read a
single character from a specified input stream. It typically takes one
argument, which is the file stream pointer from which the character is
to be read. The function returns an integer representation of the
character read, or EOF (end-of-file) if there are no more characters to
be read or if an error occurs.
syntax
int getc (FILE);
The getc() function reads the next character from the input stream
specified by stream, advances the file position indicator for the
stream, and returns the character read as an unsigned char cast to
an int. If the operation fails (e.g., if the end of the file is reached or an
error occurs), the function returns EOF.
Here's an example demonstrating the usage of `getc()` to read
characters from a file:
#include <stdio.h>
int main() {
FILE *file;
int ch;
file = fopen("example.txt", "r"); // Open file in read mode
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
// Read characters until end of file
while ((ch = getc(file)) != EOF) {
putchar(ch); // Print the character
}
fclose(file); // Close the file
return 0;
}
```
In this example, `getc()` is used to read characters from the file
`"example.txt"` until the end of the file is reached (`EOF`). Each
character is then printed to the standard output using `putchar()`.
Finally, the file is closed using `fclose()`.
2. getch():
getch() function reads a single character from the keyboard by the user but
doesn’t display that character on the console screen and immediately
returned without pressing enter key. This function is declared in
conio.h(header file). getch() is also used for hold the screen.
Syntax:
getch();
or
variable-name = getch();
Example:
#include <conio.h>
#include <stdio.h>
int main()
printf("Enter any character: ");
// Reads a character but
// not displays
getch();
return 0;
Output:
Enter any character:
3. getche():
getche() function reads a single character from the keyboard by the user and
displays it on the console screen and immediately returns without pressing
the enter key. This function is declared in conio.h(header file).
Syntax:
getche();
or
variable_name = getche();
Example:
#include <conio.h>
#include <stdio.h>
int main()
printf("Enter any character: ");
// Reads a character and
// displays immediately
getche();
return 0;
Output:
Enter any character: g
4. getchar():
The getchar() function is used to read only a first single character from the
keyboard whether multiple characters is typed by the user and this function
reads one
character at one time until and unless the enter key is pressed. This
function is declared in stdio.h(header file)
Syntax:
Variable-name = getchar();
Example:
#include <stdio.h>
int main()
char ch;
printf("Enter the character: ");
// Taking a character from keyboard
ch = getchar();
// Displays the value of ch
printf("%c", ch);
return 0;
Output:
Enter the character: a
a
putchar():
The putchar() function is used to display a single character at a time by
passing that character directly to it or by passing a variable that has already
stored a character. This function is declared in stdio.h(header file)
Syntax:
putchar(variable_name);
Example:
#include <stdio.h>
int main()
char ch;
printf("Enter any character: ");
// Reads a character
ch = getchar();
// Displays that character
putchar(ch);
return 0;
Output:
Enter any character: Z
gets():
gets() function reads a group of characters or strings from the keyboard by
the user and these characters get stored in a character array. This function
allows us to write space-separated texts or strings. This function is declared
in stdio.h(header file).
Syntax:
char str[length of string in number]; //Declare a char type variable of
any length
gets(str);
Example:
#include <conio.h>
#include <stdio.h>
int main()
// Declaring a char type array
// of length 50 characters
char name[50];
printf("Please enter some texts: ");
// Reading a line of character or
// a string
gets(name);
// Displaying this line of character
// or a string
printf("You have entered: %s",
name);
return 0;
Output:
Please enter some texts: C Programming
You have entered: C Programming
puts():
In C programming puts() function is used to display a group of characters or
strings which is already stored in a character array. This function is
declared in stdio.h(header file).
Syntax:
puts(identifier_name );
Example:
#include <stdio.h>
int main()
char name[50];
printf("Enter your text: ");
// Reads string from user
gets(name);
printf("Your text is: ");
// Displays string
puts(name);
return 0;
Output:
Enter your text: C programming
Your text is: C programming
putch():
putch() function is used to display a single character which is given by the
user and that character prints at the current cursor location. This function
is declared in conio.h(header file)
Syntax:
putch(variable_name);
Example:
#include <conio.h>
#include <stdio.h>
int main()
char ch;
printf("Enter any character:\n ");
// Reads a character from the keyboard
ch = getch();
printf("\nEntered character is: ");
// Displays that character on the console
putch(ch);
return 0;
Output:
Enter any character:
Entered character is: d
Formatted I/O vs Unformatted I/O
S Formatted I/O functions Unformatted I/O functions
No.
These functions allow us to take These functions do not allow to
1 input or display output in the user’s take input or display output in
desired format. user desired format.
These functions support format These functions do not support
2
specifiers. format specifiers.
These are used for storing data These functions are not more
3
more user friendly user-friendly.
Here, we can use only
4 Here, we can use all data types. character and string data
types.
getch(), getche(), gets() and
printf(), scanf, sprintf() and sscanf()
5 puts(), are some examples of
are examples of these functions.
these functions.
User Defined functions:
C allows you to define functions according to your need. These functions are
known as user-defined functions. For example:
areaofcircle ( ) function, swap ( ) function etc.
To use a user-defined function, we first have to understand the different
parts of its syntax. The user-defined function in C can be divided into three
parts:
• Function Declaration / Prototype
• Function Definition
• Function Call
Function Declaration / prototype: A function declaration specifies
the function’s name, function parameters, and return type. The function
declaration does not contain the body of the function. It is basically used to
inform the compiler about the existence of the user-defined function which
can be used in the later part of the program.
Syntax:
return_type function_name (type1 , type2 , ... typeN);
e.g int addnumbers (int a, int b); is function declaration which provides
the following information to the compiler:
• name of the function is addNumbers()
• return type of the function is int
• two arguments of type int are passed to the function
A function is declared before the function main().
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. A function is called inside the
function main.
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
returnType functionName(type1 argument1, type2 argument2, ...)
//body of the function
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.
For example
#include <stdio.h>
int addNumbers(int a, int b); // function declaration
int main()
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
int addNumbers (int a, int b) // function definition
int result;
result = a+b;
return result; // return statement
Passing arguments to a function
In programming, argument refers to the variable passed to the function. In
the above example, two variables n1 and n2 are passed during the function
call.
The parameters a and b accepts the passed arguments in the function
definition. These arguments are called formal parameters of the function.
Passing Argument to Function
Local and global variables are fundamental concepts in programming,
particularly in languages like C, C++, Java, and many others. They play
crucial roles in determining the scope and lifetime of variables within a
program.
Global Variables & Local Variables:
Global variables are declared outside of any function or block and can be
accessed by any function in the program. They have a global scope, meaning
they are visible throughout the entire program.
1. Scope: Global variables have program scope, meaning they are accessible
from any point in the program after their declaration.
2. Lifetime: The lifetime of a global variable is the entire duration of the
program's execution.
3. Initialization: Global variables are automatically initialized by the
compiler to a default value if not explicitly initialized by the programmer.
#include <stdio.h>
int globalVar = 20; // globalVar is a global variable
void exampleFunction( )
printf("Global variable: %d\n", globalVar);
int main()
exampleFunction();
printf("Global variable: %d\n", globalVar);
return 0;
Local variables are declared within a specific block of code, such as within
a function or a compound statement. They are accessible only within the
block in which they are declared.
1. Scope: Local variables have block scope, meaning they are accessible only
within the block in which they are defined.
2. Lifetime: The lifetime of a local variable begins when the block in which it
is declared is entered and ends when the block is exited.
#include <stdio.h>
void test( )
int p = 10; // localVar is a local variable
printf ("Local variable: %d\n", p);
int main()
int p = 50;
test( );
printf("%d\n", p); return 0;
}
Recursion in C:
Recursion is the process of a function calling itself repeatedly till the given
condition is satisfied. A function that calls itself directly or indirectly is
called a recursive function and such kind of function calls are called
recursive calls.
Recursion in C is a programming technique where a function calls itself
directly or indirectly in order to solve a problem.
Example 1:
#include <stdio.h>
int sum (int k);
int main ( )
int result = sum (10);
printf (“%d”, result);
return 0;
int sum (int k)
if (k>0)
return k + sum (k-1);
else
return 0;
Example 2
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
int main() {
int num = 5;
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
In this example, the factorial() function calls itself with a smaller argument
until it reaches the base case (n == 0 or n == 1). Then, it returns 1 to start
the unwinding process. Each recursive call builds on the result of the
smaller subproblem until the original problem is solved.