FYBCA Sem 2 C Lang Unit 1 - Functions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Unit-1 Functions

In c, we can divide a large program into the basic building blocks known as
function. 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 procedureor subroutinein other
programming languages.
Advantage of functions in C
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and
again in a program.
o We can call C functions any number of times in a program and from any
place in a program.
o We can track a large C program easily when it is divided into multiple
functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
o 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.
o 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.
o 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.

SN C function aspects Syntax


1 Function declaration return_type function_name (argument list);
2 Function call function_name (argument_list)
3 Function definition return_type function_name (argument list) {function
body;}
The syntax of creating function in c language is given below:
return_type function_name(data_type parameter...){
//code to be executed
}
Scope of variables

Prashant M. Savdekar Page 1


The scope is the region in any program where the defined variable has its
existence. It cannot be accessed beyond this scope.

The three places where the variables can be declared are:

1. Local variables which are inside a function or a block.


2. Global variables which are outside all the functions.
3. Formal parameters which are defined in the function parameters.
Local variables
• Local variables are the ones that are declared inside the function or the block.
• Only the statements which are inside this block are able to access these
variables.
• They are not known to the functions outside.

Example: Declaration of local variables


void main()
{
int x,y;
int c;
}
Global variables
• The variables which are defined outside a function or block generally on top of
the program are known as Global variables.
• The value of the variable is held throughout the program.
• They can be accessed anywhere in the program and in any function.
Example: Declaration of global variable
int n;
int main()
{
code;
}
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 sum(int a, int b); // forward declaration of function
void main ()
{
/* local variable declaration in main function */
int a = 10;

Prashant M. Savdekar Page 2


int b = 20;
int c = 0;
printf ("value of 'a' in main() = %d\n", a);
c = sum(a, b); //function call
printf ("value of c in main() = %d\n", c);
getch();
}
/* function to add two integers */
int sum(int a, int b) // function defination or called function
{
printf ("value of 'a' in sum() = %d\n", a);
printf ("value of 'b' in sum() = %d\n", b);
return a + b;
}
output
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

Different aspects of function calling


A function may or may not accept any argument. It may or may not return any
value. Based on these facts, There are four different aspects of function calls.
o function without arguments and without return value
o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and return value

Example 1
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Javatpoint");

Prashant M. Savdekar Page 3


}
Output
Hello Javatpoint

Example 2
#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example for Function without argument and with return value

Example 1
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;

Prashant M. Savdekar Page 4


printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the area of the square


#include<stdio.h>
int sum();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}
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

Example for Function with argument and without return value


Example 1
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");

Prashant M. Savdekar Page 5


scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers.


#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}
Output
Going to calculate the average of five numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Prashant M. Savdekar Page 6


Example for Function with argument and with return value
Example 1
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd


#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{ printf("\nThe number is odd");
}
else
{ printf("\nThe number is even");
}
}
int even_odd(int n)

Prashant M. Savdekar Page 7


{
if(n%2 == 0)
{ return 1;
}
else
{ return 0;
}
}
Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even

Call by value and Call by reference in C


There are two methods to pass the data into the function in C language, i.e., call
by value and call by reference.

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 In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into 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.

Prashant M. Savdekar Page 8


Let's try to understand the concept of call by value in c language by the example
given below:
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by Value Example: Swapping the values of the two variables


#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing
the value of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of a
ctual parameters do not change by changing the formal parameters in call by val
ue, a = 10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;

Prashant M. Savdekar Page 9


printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal par
ameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20

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.
o In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function are
performed on the value stored at the address of the actual parameters, and
the modified value gets stored at the same address.

Consider the following example for the call by reference.


#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Call by reference Example: Swapping the values of the two variables


#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()

Prashant M. Savdekar Page 10


{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing
the value of a and b in main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of
actual parameters do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal p
arameters, a = 20, b = 10
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10

Difference between call by value and call by reference in c


No. Call by value Call by reference
1 A copy of the value is passed into the An address of value is passed into
function the function
2 Changes made inside the function is Changes made inside the function
limited to the function only. The validate outside of the function also.
values of the actual parameters do The values of the actual parameters
not change by changing the formal do change by changing the formal
parameters. parameters.
3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory location
location

What is Recursion?
The process in which a function calls itself directly or indirectly is called
recursion and the corresponding function is called a recursive function. Using a
recursive algorithm, certain problems can be solved quite easily. Examples of
such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree
Traversals, DFS of Graph, etc. A recursive function solves a particular problem

Prashant M. Savdekar Page 11


by calling a copy of itself and solving smaller subproblems of the original
problems.

Need of Recursion
Recursion is an amazing technique with the help of which we can reduce the
length of our code and make it easier to read and write. It has certain
advantages over the iteration technique which will be discussed later. A task
that can be defined with its similar subtask, recursion is one of the best
solutions for it. For example; The Factorial of a number.
Properties of Recursion:
• Performing the same operations multiple times with different inputs.
• In every step, we try smaller inputs to make the problem smaller.
• Base condition is needed to stop the recursion otherwise infinite loop will
occur.
Program:
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{ return 0;
}
else if ( n == 1)
{ return 1;
}
else
{ return n*fact(n-1);
}
}
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure
given below:

Prashant M. Savdekar Page 12


Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory
location, and initial value of a variable. There are four types of storage classes in
C
o Automatic
o External
o Static
o Register
Storage Storage Default Scope Lifetime
Classes Place Value
auto RAM Garbage Local Within function
Value
extern RAM Zero Global Till the end of the main program Maybe
declared anywhere in the program
static RAM Zero Local Till the end of the main program,
Retains value between multiple
functions call
register Register Garbage Local Within the function
Value
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they
are defined.
The scope of the automatic variables is limited to the block in which they
are defined.

Prashant M. Savdekar Page 13


o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from
the block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Ex.
int mount;
auto int month;

Example 1
#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic varia
bles a, b, and c.
return 0;
}
Output:
garbage garbage garbage
Static
o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which
they are defined.
o A same static variable can be declared many times but can be assigned at
only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.
Ex.
static int count = 5;
Example 1
#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()

Prashant M. Savdekar Page 14


{
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be p
rinted.
}
Output:
0 0 0.000000 (null)

Register
o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use
&operator for the register variable.
o The access time of the register variables is faster than the automatic
variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the
CPU register. However, it is compiler?s choice whether or not; the variables
can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address
of a variable.
o Static variables can not be stored into the register since we can not use
more than one storage specifier for the same variable.
Ex.
register int miles;
Example 1
#include <stdio.h>
int main()
{
register int a;
// variable a is allocated memory in the CPU register. The initial default value of
a is 0.
printf("%d",a);
}
Output:
0
External
o The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere
in the program.

Prashant M. Savdekar Page 15


o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize
the external variable within any block or method.
o An external variable can be declared many times but can be initialized at
only once.
o If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be extern or
static. If it is not, then the compiler will show an error.
Ex.
extern int count;
Example 1
#include <stdio.h>
int main()
{
extern int a;
printf("%d",a);
}
Output
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status

Prashant M. Savdekar Page 16

You might also like