Unit 3 Functions and Program Structure-1-1
Unit 3 Functions and Program Structure-1-1
Basics of functions
C Functions :
● A function is a block of code which only runs when it is called.
● You can pass data, known as parameters, into a function.
● Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
● We can divide a large program into the basic building blocks known as
functions.
● 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.
● By using functions, we can avoid rewriting same logic/code again and
again in a program.
● We can call C functions any number of times in a program and from any
place in a program.
● We can track a large C program easily when it is divided into multiple
functions.
● Reusability is the main achievement of C functions.
● However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
● 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.
● 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.
● 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.
C function Syntax
SN aspects
1 Function return_type function_name (parameter list);
declaration
2 Function return_type function_name (parameter
definition list)
{
// function body
}
3 Function call function_name (parameter_list)
Types of Functions
Header files:
● The list of mostly used header files is given in the following table
Header file Description
2. User-defined functions:
● User defined functions are the functions which are created by the
C programmer, so that he/she can use it many times.
● It reduces the complexity of a big program and optimizes the code.
Create a Function
● To create (often referred to as declare) your own function, specify the
name of the function, followed by parentheses () and curly brackets {}
● Syntax
void myFunction() {
// code to be executed
}
Example Explained
● myFunction() is the name of the function
● void means that the function does not have a return value. You will learn
more about return values later in the next chapter
● Inside the function (the body), add code that defines what the function
should do
Call a Function
Declared functions are not executed immediately. They are "saved for later
use", and will be executed when they are called.
To call a function, write the function's name followed by two parentheses () and
a semicolon ;
In the following example, myFunction() is used to print a text (the action), when
it is called.
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
A function can be called multiple times:
Example
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
//output
// I just got executed!
// I just got executed!
// I just got executed!
C Function Parameters
● Information can be passed to functions as a parameter.
● Parameters act as variables inside the function.
● Parameters are specified after the function name, inside the
parentheses.
● You can add as many parameters as you want, just separate them with
a comma.
● Syntax :
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years old.\n", name, age);
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Hello Liam. You are 3 years old.
// Hello Jenny. You are 14 years old.
// Hello Anja. You are 30 years old.
Note that when you are working with multiple parameters, the function call
must have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.
Function Argument:
When calling a function in C, arguments can be passed in two ways, by calling
by value and by calling by reference. This tutorial guides you about these two
ways to pass parameters to a function and demonstrates them with examples.
Type Description
Call by ● The actual parameter is passed to a function.
Value ● A new memory area created for the given
parameters can be used only within the function.
● The actual parameters cannot be modified here.
Return Values
The void keyword, indicates that the function should not return a value. If you
want the function to return a value, you can use a data type (such as int or
float, etc.) instead of void, and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
printf("Result is: %d", myFunction(3));
return 0;
}
// Outputs 8 (5 + 3)
This example returns the sum of a function with two parameters:
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
You can also store the result in a variable:
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
Syntax:
return_type function_name ( parameter1, parameter2, ... )
{
// body of Statement ;
}
Example :
void function_name ( )
{
// body of Statement ;
}
● Here, the 'void' keyword is used as the return type to indicate that the
function does not return any value.
● A void function can be called in the same way as other functions, by simply
using the function name followed by empty parentheses:
function_name ( );
● Example:
#include<stdio.h>
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
int main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
return 0;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers 10
24
The sum is 34
Function without argument and with return value
● In C programming, a function that does not take any arguments but returns a value is
called a non-void function.
● The syntax for defining a non-void function is as follows
○ Syntax :
return_type function_name ( ) // Function Definition
{
// body of Statement ;
return value;
}
● Here, the return_type specifies the data type of the value that the function will return. The
function_name is the name of the function and the value is the value that the function
returns.
● A non-void function can be called in the same way as other functions, by simply using the
function name followed by empty parentheses:
○ variable = function_name();
#include<stdio.h>
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
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
Function with argument and without return value
● In C programming, a function that takes one or more arguments but does not
return a value is called a void function. The syntax for defining a void function
with arguments is as follows:
● Syntax :
return_type function_name ( data_type argument1, data_type argument2,
... ) // Function Definition
{
// body of Statement ;
}
○ Here, the 'void' keyword is used as the return type to indicate that the
function does not return any value. The function_name is the name of
the function, and the argument1, argument2, ... are the input
parameters that the function takes.
○ A void function with arguments can be called by providing the values for
the arguments in the function call:
Syntax :
return_type function_name ( data_type argument1, data_type argument2, ... ) //
Function Definition
{
// body of Statement ;
}
● Here, the return_type specifies the data type of the value that the function will return. The
function_name is the name of the function, and the argument1, argument2, ... are the
input parameters that the function takes. The value is the value that the function returns.
● A non-void function with arguments can be called by providing the values for the
arguments in the function call:
#include<stdio.h>
int add(int,int);
int main()
{
int a,b;
printf("\nEnter The Value of A & B : ");
scanf("%d%d",&a,&b);
a=add(a,b);
printf("\nTotal : %d",a);
return 0;
}
int add(int x,int y)
{
return x+y;
}
Recursion:
C is a powerful programming language having capabilities like an iteration of a
set of statements 'n' number of times. The same concepts can be done using
functions also. In this tutorial, you will learn about the concept of recursion
and how it can be used in C programs.
Recursion can be defined as the technique of repeating or doing an activity,
which calls itself repeatedly, and the process continues until a specific
condition reaches. In the programming world, when your program lets you call
that specific function from inside that function, then this concept of calling the
function from itself can be termed recursion. The function that makes this
possible is called the recursive function. Here's an example of how recursion
works in a program:
void rec_prog(void) {
rec_prog(); //function calls itself
}
int main(void) {
rec_prog();
return 0;
}
C program allows you to do the such calling of function within another
function, i.e., recursion. But when you implement this recursion concept, you
have to be cautious in defining an exit or terminating condition from this
recursive function, or else it will continue to an infinite loop, so make sure that
the condition is set within your program.
Example :
#include <stdio.h>
int factorial(int i) {
if(i <= 1) {
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 3;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0;
}
External variable:
External variables are also known as global variables. These variables are
defined outside the function. These variables are available globally throughout
the function execution. The value of global variables can be modified by the
functions. “extern” keyword is used to declare and define the external
variables.
Scope − They are not bound by any function. They are everywhere in the
program i.e. global.
Default value − Default initialized value of global variables are Zero.
Lifetime − Till the end of the execution of the program.
Here are some important points about extern keyword in C language,
● External variables can be declared a number of times but defined only
once.
● “extern” keyword is used to extend the visibility of a function or variable.
● By default the functions are visible throughout the program, there is no
need to declare or define extern functions. It just increases the
redundancy.
● Variables with “extern” keyword are only declared not defined.
● Initialization of extern variable is considered as the definition of the
extern variable.
Here is an example of extern variable in C language
Example
#include <stdio.h>
// declaring a variable with extern variable
extern int var;
int main(){
// defining the extern variable
int var=10;
printf("%d",var);
return 0;
}
Scope rule in C :
Scope = Lifetime
A scope in any programming is a region of the program where a defined
variable can have its existence and beyond that variable it cannot be accessed.
There are three places where variables can be declared in C programming
language −
● Inside a function or a block which is called local variables.
● Outside of all functions which is called global variables.
● In the definition of function parameters which are called formal
parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Local variables are not known to functions outside their own. The
following example shows how local variables are used. Here all the variables a,
b, and c are local to main() function.
Global Variables
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and
they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.
Error Handling in C
C language does not provide any direct support for error handling. However a
few methods and variables defined in error.h header file can be used to point
out error using the return statement in a function. In C language, a function
returns -1 or NULL value in case of any error and a global variable errno is set
with the error code. So the return value can be used to check error while
programming.
What is errno?
Whenever a function call is made in C language, a variable named errno is
associated with it. It is a global variable, which can be used to identify
which
type of error was encountered while function execution, based on its value.
Below we have the list of Error numbers and what does they mean.
C language uses the following functions to represent error messages associated
with errno:
● perror(): returns the string passed to it along with the textual
represention of the current errno value.
● strerror() is defined in string.h library. This method returns a pointer to
the string representation of the current errno value.
Example:
#include <errno.h>
#include <stdio.h>
int main()
{
// If a file is opened which does not exist,
// then it will be an error and corresponding
// errno value will be set
FILE* fp;
// opening a file which does not exist
fp = fopen("GeeksForGeeks.txt", "r");
printf("Value of errno: %d\n", errno);
return 0;
}
Division by Zero
There are some situation where nothing can be done to handle the error. In C
language one such situation is division by zero. All you can do is avoid doing
this, becasue if you do so, C language is not able to understand what
happened, and gives a runtime error.
Best way to avoid this is, to check the value of the divisor before using it in the
division operations. You can use if condition, and if it is found to be zero, just
display a message and return from the function.
// C program to check and rectify
// divide by zero condition
#include<stdio.h>
#include <stdlib.h>
void function(int);
int main()
{
int x = 0;
function(x);
return 0;
}
void function(int x)
{
float fx;
if (x==0)
{
printf("Division by Zero is not allowed");
fprintf(stderr, "Division by zero! Exiting...\n");
exit(EXIT_FAILURE);
}
else
{
fx = 10 / x;
printf("f(x) is: %.5f", fx);
}
}