Unit 4
Unit 4
DEFINITION OF FUNCTION:
A function is a set of statements that take inputs, do some specific computation and produces
output. A function is a group of statements that together perform a task.
The idea is to put some commonly or repeatedly done task together and make a function so that
instead of writing the same code again and again for different inputs
Every C program has at least one function, which is main(), and all the most trivial programs can
define additional functions.
You can divide up your code into separate functions. How you divide up your code among different
functions is up to you, but logically the division is such that each function performs a specific task.
In the C programming language, the function is divided into two parts: the built-in/ library function
and the user-defined function.
A library function is predefined functions, and its tasks are also defined in the C header files. So, it
does not require writing the code of the particular function; instead, it can be called directly in a
program whenever it is required.
Example: printf(), scanf(), getch(), etc., are the predefined function in the C library, and the meaning
of these functions cannot be changed.
User-defined Function
Function Declaration
A function declaration defines the name and return type of a function in a program. Before using the
function, we need to declare it outside of a main() function in a program.
Syntax:
return_data_type function_name ( data_type arguments) ;
Function Definition
It defines the actual body of a function inside a program for executing their tasks in C.
Syntax:
In the above syntax, a function definition contains the three parts as follow:
1. Return Data_Type: It defines the return data type of a value in the function. The return data
type can be integer, float, character, etc.
2. Function Name: It defines the actual name of a function that contains some parameters.
3. Parameters/ Arguments: It is a parameter that passed inside the function name of a
program. Parameters can be any type, order, and the number of parameters.
4. Function Body: It is the collection of the statements to be executed for performing the
specific tasks in a function.
int min (int n1, int n2); // min() is the name of a function that contains n1 and n2 parameters
{
// declaration of the local variable.
int out;
if ( n1 > n2)
out = n1; // return n1 when n1 is greater than n2.
else
out = n2; // return n2 when n2 is greater than n1.
return out;
}
Function Calling:
A function call is an important part of the C programming language. It is called inside a program
whenever it is required to call a function. It is only called by its name in the main() function of a
program. We can pass the parameters to a function calling in the main() function.
Syntax:
Add.c
#include <stdio.h>
int add(int a, int b);
void main()
{
int sum;
int a, b;
printf(" Enter the first and second number \n");
scanf("%d %d", &a, &b);
sum = add(a, b); // call add() function
printf( "The sum of the two number is %d", sum);
}
int add(int n1, int n2) // pass n1 and n2 parameter
{
int c;
c = n1 + n2;
return c;
}
Output:
CATEGORIES OF FUNCTIONS
Depending on whether arguments are present or not and whether a value is returned or not, functions
are categorized into −
Example:
#include<stdio.h>
main ()
{
void sum ();
clrscr ();
sum ();
}
void sum ()
{
int a,b,c;
printf("enter 2 numbers:\n");
scanf ("%d%d", &a, &b);
c = a+b;
printf("sum = %d",c);
}
Output:
Enter 2 numbers:
3
5
Sum=8
Example
#include<stdio.h>
int sum ( int,int);
main ()
{
int a,b,c;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
c= sum (a,b);
printf ("sum=%d", c);
}
int sum ( int a, int b )
{
int c;
c= a+b;
return c;
}
Output
Enter two numbers 10 20
Sum=30
#include <stdio.h>
int sum (int n);
void main()
{
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
a = sum(a);
printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int n)
{
n = n + 20;
printf("\n Value of 'n' in the called function is = %d", n);
return n;
}
Output:
The value of 'a' before the calling function is = 5
Value of 'n' in the called function is = 25
The value of 'a' after calling the function is = 25
2. Call by reference
• Here, the address of the variables are passed by the calling function to the called function.
• The address which is used inside the function is used to access the actual argument used in
the call.
• If there are any changes made in the parameters, they affect the passed argument.
•For passing a value to the reference, the argument pointers are passed to the functions just
like any other value.
Example: Call by reference
#include <stdio.h>
int sum (int *n);
void main()
{
int a = 5;
printf("\n The value of 'a' before the calling function is = %d", a);
sum(&a);
printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int *n)
{
*n = *n + 20;
printf("\n Value of 'n' in the called function is = %d", n);
}
Output:
The value of 'a' before the calling function is = 5
Value of 'n' in the called function is = -1079041764
The value of 'a' after calling the function is = 25
Naming As in this type the value of On other hand in this type the reference
1 Convention parameter is get passed for of parameter is get passed for invoking
function invocation hence it the function so it is named as Call by
is named as Call by Value. Reference.
Scope of a Variable:
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.
#include <stdio.h>
int main ()
{
/* local variable declaration */ int a, b;
int c;
/* actual initialization */ a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0;
}
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.
#include <stdio.h>
/* global variable declaration */ int g;
int main ()
{
/* local variable declaration */ int a, b;
/* actual initialization */ a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0;
}
A program can have same name for local and global variables but the value of local variable
inside a function will take preference. Here is an example –
#include <stdio.h>
value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a function and they take precedence over
global variables. Following is an example −
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
When the above code is compiled and executed, it produces the following result –
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Int 0
Char '\0'
Float 0
Double 0
Pointer NULL
It is a good programming practice to initialize variables properly, otherwise your program may
produce unexpected results, because uninitialized variables will take some garbage value already
available at their memory location.
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
m = 10
n = 20
After Swapping:
m = 20
n = 10
CommandLine Arguments:
It is possible to pass some values from the command line to your C programs when they are
executed. These values are called command line arguments and many times they are important for
your program especially when you want to control your program from outside instead of hard
coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to
the program. Following is a simple example which checks if there is any argument supplied from
the command line and take action accordingly –
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following
result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with a two arguments, it produces the following
result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the
first command line argument supplied, and *argv[n] is the last argument. If no arguments are
supplied, argc will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space
then you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us
re-write above example once again where we will print program name and we also pass a command
line argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("Program name %s\n", argv[0]);
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but inside
double quotes, it produces the following result.
$./a.out "testing1 testing2"
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
When you have multiple files and you define a global variable or function, which will also be used in
other files, then extern will be used in another file to provide the reference of defined variable or
function. Just for understanding, extern is used to declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files sharing the same
global variables or functions as explained below.
Here, extern is being used to declare count in the second file, where as it has its definition in the first
file, main.c. Now, compile these two files as follows −
It will produce the executable program a.out. When this program is executed, it produces the
following result −
count is 5
Recursion
Definition:
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a
null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold
the null character at the end of the array, the size of the character array containing the string is one
more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
If you follow the rule of array initialization then you can write the above statement as follows −
char greeting[] = "Hello";
Following is the memory presentation of the above defined string in C−
Actually, you do not place the null character at the end of a string constant. The C compiler
automatically places the '\0' at the end of the string when it initializes the array. Let us try to print
the above mentioned string −
main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message:
%s\n", greeting ); return 0;
}
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
String processing with and without functions:
When the above code is compiled and executed, it produces the following result −
Examples: Refer observation for programs with out using built-in functions
String Library functions
The predefined functions which are designed to handle strings are available in the library “string.h”.
They are −
• strlen ()
• strcmp ()
• strcpy ()
• strncmp ()
• strncpy ()
• strrev ()
• strcat ()
• strstr ()
• strncat ()
The variable name of the string str holds the address of the first element of the array i.e., it points at
the starting memory address.
So, we can create a character pointer ptr and store the address of the string str variable in it. This
way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the pointer ptr.
To access and print the elements of the string we can use a loop and check for the \0 null character.
In the following example we are using while loop to print the characters of the string variable str.
#include <stdio.h>
int main(void)
{
// string variable
char str[6] = "Hello";
// pointer variable
char *ptr = str;
// print the string
while(*ptr != '\0')
{
printf("%c", *ptr);
// move the ptr pointer to the next memory location
ptr++;
}
return 0;
}