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

FuncTionS-V3

1
1. Function revision

2. Global variable and Local variable

3. Call by value and Call by reference

2
Introduction
• A function is a block of code which is used to
perform a specific task.
• It can be written once and can be reused for a
different program without having to rewrite that
piece of code.
• Functions can be put in a library. If another program
would like to use them, it will just need to include the
appropriate header file at the beginning of the
program and link to the correct library while
compiling.

3
Introduction

• Functions can be divided into two categories :


• Predefined functions (standard functions)
• Built-in functions provided by C that are used by
programmers without having to write any code for
them. i.e: printf( ), scanf( ), etc

• User-Defined functions
• Functions that are written by the programmers
themselves to carry out various individual tasks.

4
Standard Functions
• Standard functions are functions that have been pre-
defined by C and put into standard C libraries.
• Example: printf(), scanf(), pow(), ceil(), rand(), etc.

• What we need to do to use them is to include the


appropriate header files.
• Example: #include <stdio.h>, #include <math.h>

• What contained in the header files are the prototypes


of the standard functions. The function definitions (the
body of the functions) has been compiled and put into a
standard C library which will be linked by the compiler
during compilation.
5
Example-1
function prototype

function call

function definition

return statement

6
Function Definition(continued)

7
The type of
arguments
passed to a
function and
the formal
parameters
must match,
otherwise, the
compiler will
throw an error.

8
The type of
value
returned from
the function
and the
return type
specified in
the function
prototype and
function
definition
must match.

9
Difference between Parameters and
Arguments
• The parameters are what are used inside
the function.
• The arguments are the values passed when
the function is called.
• Example: If one defines the add subroutine
as def add(x, y): return x + y, then x, y are
parameters,
while if this is called as add(2, 3), then 2, 3 are
the arguments.
10
Difference between Parameters
and Arguments (continued)
• The arguments and the parameters
should match in number, type and order.
• The variables used in parameters must
be assigned values before the function
call is made.
• When a function is made, only a copy of
the values of arguments is passed into
the called function.
11
return statement
• A return statement indicates the end of an
execution of a function and has the same
semantics on both low level and high level
languages.
• A function may or may not return a value.
• A return statement returns a value to the
calling function and assigns to the variable in
the left side of the calling function.
• If a function does not return a value, the return
type in the function definition and declaration is
specified as void.
12
Category of Functions
A function depending on whether arguments are
present or not and whether a value is returned or
not, may belong to one of the following
categories.

➢ Functions with no arguments and no return


value
➢ Functions with arguments and no return value
➢ Functions with arguments and one return value
➢ Functions with no arguments but return a value
➢ Functions that return multiple values
13
C function argument
and return values

A function in C can be called either with arguments


or without arguments.
These function may or may not return values to the
calling functions. All C functions can be called either
with arguments or without arguments in a C
program.
Also, they may or may not return any values. Hence
the function prototype of a function in C is as below:
1. Function with no argument and no return value:
When a function has no arguments, it does not receive
any data from the calling function. Similarly when it
does not return a value, the calling function does not
receive any data from the called function.
Syntax :
2. Function with arguments but no return value:
When a function has arguments, it receive any
data from the calling function but it returns no
values.
Syntax:
3. Function with no arguments but returns a value:
There could be occasions where we may need to design
functions that may not take any arguments but returns a
value to the calling function. A example for this is getchar
function it has no parameters but it returns an integer an
integer type data that represents a character.
Syntax:
int getInteger();
int main()
{
int n, i, flag = 0;
// no argument is passed
n = getInteger();
for(i=2; i<=n/2; ++i)
{
if(n%i==0){
flag = 1; break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
// returns integer entered by the user
int getInteger()
{
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
return n;
} 19
4. Function with arguments and return value
An Example

• Assume user inputs 2 integers, n and r.

• What is the value of,

n!
NCR =
r!(n - r)!

• Remember n! = n x (n -1 ) x (n – 2) x … x 2 x 1
An Example
#include <stdio.h>

int main()
{
int N, R;
int factN = 1, factR = 1, factN_R = 1;
int result;
int i;
printf("Enter N and R\n");
scanf("%d%d",&N,&R);
for(i=1;i<=N;i++)
factN *= i;
for(i=1;i<=R;i++)
factR *= i;
for(i=1;i<=(N-R);i++)
factN_R *= i;
result = factN/(factR*factN_R);
printf("%d combination %d = %d",N,R,result);
return 0;
}
An Example
#include <stdio.h>

int main()
{
int N, R;
int factN = 1, factR = 1, factN_R = 1;
int result;
int i;
printf("Enter N and R\n");
scanf("%d%d",&N,&R);
for(i=1;i<=N;i++)
factN *= i;
You are
for(i=1;i<=R;i++)
implementing same
factR *= i;
for(i=1;i<=(N-R);i++)
logic over and over
factN_R *= i;
result = factN/(factR*factN_R);
printf("%d combination %d = %d",N,R,result);
return 0;
}
An Example
Type of output value (return type) (void if no
output)

Type and name of


Function name
Input to the function (parameters)

int factorial(int x)
{
int fact = 1, i;
for(i=1;i<=x;i++) Body of the function
fact *= i;
return fact;
}
An Example
#include <stdio.h>
int factorial(int x);
int main()
{
int N, R;
int result;
int i;
printf("Enter N and R\n");
scanf("%d%d",&N,&R);
result = factorial(N)/(factorial(R)*factorial(N-R));
printf("%d combination %d = %d",N,R,result);
return 0;
}

int factorial(int x)
{
int fact = 1, i;
for(i=1;i<=x;i++)
fact *= i;
return fact;
}
An Example
#include <stdio.h>
int factorial(int x); Function prototype
int main()
{
int N, R;
int result; Calling the function
int i;
printf("Enter N and R\n");
scanf("%d%d",&N,&R);
result = factorial(N)/(factorial(R)*factorial(N-R));
printf("%d combination %d = %d",N,R,result);
return 0;
}
int factorial(int x)
{
int fact = 1, i;
for(i=1;i<=x;i++)
fact *= i;
Function implementation
return fact;
}
Top Down Design
• Analyze the problem
• Break it into smaller sub-problems
• Solve the smaller problems as Functions
• Put them together in the main() function
An argument is referred to the values that are passed
within a function when the function is called.
These values are generally the source of the function
that require the arguments during the process of
execution.
These values are assigned to the variables in the
definition of the function that is called.
The type of the values passed in the function is the
same as that of the variables defined in the function
definition.
These are also called Actual arguments or Actual
Parameters.
28
Example: Supp
ose a sum()
function is
needed to be
called with two
numbers to add. OUTPUT
These two 30
numbers are
referred to as
the arguments
and are passed
to the sum()
when it called
from
somewhere else.
29
The parameter is referred to as the variables
that are defined during a function declaration or
definition.
These variables are used to receive the
arguments that are passed during a function
call.
These parameters within the function prototype
are used during the execution of the function for
which it is defined.
These are also called Formal arguments or
Formal Parameters.

30
Example:
Suppose a Mult()
function is
needed to be
defined to Output:
multiply two The multiplication
is 200
numbers. These
two numbers are
referred to as the
parameters and
are defined while
defining the
function Mult().

31
Functions with Multiple Parameter
• A function can have any number of parameters (zero or
more)
• We have seen functions with no parameter (recall draw)
void draw_rectangle()
{
printf(" ****** \n");
printf(" * * \n");
printf(" * * \n");
printf(" * * \n");
printf(" ****** \n");
}
• We have seen function with one parameter
int factorial(int x)
{
int fact = 1, i;
for(i=1;i<=x;i++)
fact *= i;
return fact;
}
Functions with Multiple Parameter

• Say we want to write a function that calculates


ab, where both a and b are positive integers.
Functions with Multiple Parameter

#include <stdio.h>
int power(int a, int b);
int main()
{
int x = 2, y = 8, z;
z = power(x, y);
printf("%d\n",z);
return 0;
}
int power(int a, int b)
{
int i, result = 1;
for(i=1; i<=b; i++)
{
result *= a;
}
return result;
}
Scopes
#include <stdio.h>
void power(int a, int b);
int main()
{
int x = 2, y = 8, z;
power(x, y); Can we do this?
printf("%d\n", result);
return 0;
}
void power(int a, int b)
{
int i, result = 1; No, result is defined
for(i=1; i<=b; i++) here (local to the power
{
function), not inside main
result *= a;
}
}
Scopes
#include <stdio.h>
void power(int a, int b);
int main()
{
int x = 2, y = 8, z;
power(x, y);
printf("%d\n",result); Different
return 0; scopes.
}
Variable from
void power(int a, int b)
one scope is
{
not visible
int i, result = 1;
for(i=1; i<=b; i++)
inside
{ another
result *= a;
}
} Local
variable
Scopes

#include <stdio.h>
void power(int a, int b);
int result;
int main ()
{
int x = 2, y = 8, z; How about this?
power(x, y);
printf("%d\n",result);
return 0;
}
void power(int a, int b)
{
int i;
for(i=1, result=1; i<=b; i++)
{
result *= a;
}
}
Scopes

#include <stdio.h>
void power(int a, int b);
int result;
int main ()
{
int x = 2, y = 8, z; How about this?
power(x, y);
printf("%d\n",result);
return 0;
}
void power(int a, int b)
{
int i; Yes, this works.
for(i=1, result=1; i<=b; i++)
{
result *= a;
}
}
Scopes

#include <stdio.h>
int power(int a, int b); Global variable (declared in
//int result; the global scope) is visible in
int main () both scopes
{
int x = 2, y = 8, sum;
sum=power(x, y);
printf("%d\n“,sum);
return 0;
}
int power(int a, int b)
{
int i;
for(i=1, result=1; i<=b; i++)
{
result *= a;
}
} return result;
Global and Local 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.
41
Global and Local 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.
42
Local Variable

- 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.
43
Local Variable
#include<stdio.h>
int a = 100;
int main()
{
{
/*variable a declared in this block is completely different
from variable declared outside.*/
Output:
int a = 10;
printf("Inner a = %d\n", a); Inner a = 10
} Outer a = 100
printf("Outer a = %d\n", a);
// signal to operating system everything works fine
return 0;
}

44
Global Variable
- 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.

45
Global Variable
#include <stdio.h>
/* global variable declaration */
int g;
int main ()
{ Output:
/* local variable declaration */ a = 10
int a, b; b = 20
/* actual initialization */ g = 30
a = 10; b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g =
%d\n", a, b, g);
return 0;
}
46
Global Variable
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>
/* global variable declaration */
int g = 35; Output:
int main ()
a = 10
{
/* local variable declaration */
b = 20
int a, b; g = 30
/* 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;
}
47
#include<stdio.h>
int a = 100;
int main()
{
{
/* variable a declared in this block is completely
different from variable declared outside. */
//int a = 10;
Output:
printf("Inner a = %d\n", a);
Inner a = 100
} Outer a = 100
printf("Outer a = %d\n", a);
return 0;
}
48
Formal Parameters
• Formal parameters are treated as:
- local variables with-in a function and
they take precedence over global variables.
An example is in next slide −

49
#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);
}
/* 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; } 50
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
/* local variable declaration in main function */
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);
}
/* 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; } 51
#include<stdio.h>
void func_1();
void func_2();
int a, b = 10; // declaring and initializing global variables
int main()
{
printf("Global a = %d\n", a);
printf("Global b = %d\n\n", b);

func_1();
func_2();
}
void func_1()
{
printf("From func_1() Global a = %d\n", a);
printf("From func_1() Global b = %d\n\n", b);
}
void func_2()
{
int a = 5;
printf("Inside func_2() a = %d\n", a);
}
52
A Static variable is able to retain its value between different function
calls. The static variable is only initialized once, if it is not initialized,
then it is automatically initialized to 0. Here is how to declare a static
variable.
#include<stdio.h>
void func_1();
int a, b = 10;
int main()
{
func_1();
func_1();
func_1();
}
void func_1()
{
int a = 1;
static int b = 100;
printf("a = %d\n", a);
printf("b = %d\n\n", b);
a++;
b++;
} 53
A Static variable is able to retain its value between different function
calls. The static variable is only initialized once, if it is not initialized,
then it is automatically initialized to 0. Here is how to declare a static
variable.
#include<stdio.h>
void func_1();
int a, b = 10;
int main()
{
func_1();
func_1();
func_1();
}
void func_1()
{
//int a = 1;
static int b;
printf("a = %d\n", a);
printf("b = %d\n\n", b);
a++;
b++;
} 54
Last but not Least
#include <stdio.h>
/*global variables*/
int a,b; /*function to set values to the global variables*/
void setValues(void)
{
a=100; b=200;
}
int main()
{
int x,y; x=10; y=20; /*local variables*/
setValues();
printf("a=%d, b=%d\n",a,b);
printf("x=%d, y=%d\n",x,y);
return 0;
} 55
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.

56
Call by value in C
• 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.

• In call by value method, we can not modify the value


of the actual parameter by the formal parameter.

• 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.

• 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.
57
Call by value in C
#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;
}
58
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 actual parameters do not change by changing the formal parameters in call by value, 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 parameters, a = 20, b =
10
}
59
An Example
• Lets find if N is a prime number, where N will be provided
by the user

int is_prime(int a)
{
int i;
for(i=2; i<a; i++)
{
if(a%i == 0)
return 0;
}
return 1;
} https://www.javatpoint.com/call-by-value-and-
call-by-reference-in-c
Another Example
Take a number N as input from the user and print this pyramid of asterisk.
N is the number of asterisk in the last row (you can assume that N will
always be a positive odd number).

*
***
*****
*******
*********
Another Example

void pyramid(int n)
{
int i, j;
for(i=1; i<=n; i+=2)
{
for(j=1; j<=i; j++)
{
printf("*");
}
printf("\n");
}
return 1;
}
Another Example
Will it work?
void pyramid(int n)
{
int i, j;
for(i=1; i<=n; i+=2)
{
for(j=1; j<=i; j++)
{
printf("*");
}
printf("\n");
}
return 1;
}
Another Example
Will it work?
void pyramid(int n)
{
int i, j;
for(i=1; i<=n; i+=2)
{
for(j=1; j<=i; j++)
{
printf("*");
}
printf("\n"); Output for n = 9:
} *
return 1; ***
*****
}
*******
*********
Another Example
Will it work?
void pyramid(int n)
{
int i, j; We should print
for(i=1; i<=n; i+=2) spaces before doing
this
{
for(j=1; j<=i; j++)
{
printf("*");
}
printf("\n"); Output for n = 9:
} *
return 1; ***
*****
}
*******
*********
Another Example
void pyramid(int n)
{
int i, j;
for(i=1; i<=n; i+=2)
{
for(j=1; j<=(n-i)/2; j++)
{
printf(" ");
}
for(j=1; j<=i; j++)
{
printf("*");
}
printf("\n");
}
return 1;
}
Another Example
void pyramid(int n)
{
int i, j;
for(i=1; i<=n; i+=2)
{
for(j=1; j<=(n-i)/2; j++)
{
printf(" ");
}
for(j=1; j<=i; j++)
Output for n = 9:
{ *
printf("*"); ***
} *****
printf("\n"); *******
} *********
return 1;
}
Yet Another Example
Take a number N as input from the user and print this diamond of asterisk. N
is the number of asterisk in the last row (you can assume that N will always
be a positive odd number).
*
***
*****
*******
*********
*********
*******
*****
***
*
Yet Another Example

void upper_pyramid(int n) void lower_pyramid(int n)


{ {
int i, j; int i, j;
for(i=1; i<=n; i+=2) for(i=n; i>=1; i-=2)
{ {
for(j=1; j<=(n-i)/2; j++) for(j=1; j<=(n-i)/2; j++)
{ {
printf(" "); printf(" ");
} }
for(j=1; j<=i; j++) for(j=1; j<=i; j++)
{ {
printf("*"); printf("*");
} }
printf("\n"); printf("\n");
} }
return 1; return 1;
} }
Yet Another Example

void upper_pyramid(int n) void lower_pyramid(int n)


{ {
int i, j; int i, j;
for(i=1; i<=n; i+=2) for(i=n; i>=1; i-=2)
{ {
for(j=1; j<=(n-i)/2; j++) for(j=1; j<=(n-i)/2; j++)
{ {
printf(" "); printf(" ");
} }
for(j=1; j<=i; j++) for(j=1; j<=i; j++)
{ {
printf("*"); printf("*");
} }
printf("\n"); printf("\n");
} }
return 1; return 1;
} }

You might also like