0% found this document useful (0 votes)
38 views

R Functions

The document discusses functions in C programming. It defines what a function is and explains the need for functions. It covers function declaration, definition, types of functions including library functions and user-defined functions. It also explains call by value and call by reference as well as recursion. The document provides examples of different types of functions based on whether they have arguments and return values or not.

Uploaded by

Ashish Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

R Functions

The document discusses functions in C programming. It defines what a function is and explains the need for functions. It covers function declaration, definition, types of functions including library functions and user-defined functions. It also explains call by value and call by reference as well as recursion. The document provides examples of different types of functions based on whether they have arguments and return values or not.

Uploaded by

Ashish Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Functions in C

1. Through this lecture, students will understand


Learning the need of functions, how to declare and
Outcomes define functions in C.
2. Students will learn the two methods of function
calling – call by value and call by reference.
3. Students will be acquainted with the concept of
recursion, their declaration and definition.
Contents
• What is Function?
• Need of Function
• Types of function
• Function declaration and definition
• Call by value and call by reference
• Recursion
Functions

Also called subroutine


Self contained block
in some other
of code that performs
languages like php,
a specific task
python

It is independent
which can perform its
task without
A function is named
interference from or
interfering with other
parts of the program.

A function is defined
Every C program has using its predefined
at least one function, syntax, and are called
which is main() from elsewhere in
your program.
Why Functions?

Improves the
readability of
code

Debugging of
Avoid
code is easier,
duplicating
errors are easy
codes
to be traced.

Improve Reduces the


Modularity size of the code
C Functions: General Form
Types of functions
Library Functions User-defined
1.Built-in functions to handle tasks Functions
such as mathematical computations,
1.Users or programmers define a
I/O processing, string handling etc.
function according to their
2.Defined in the header file requirement.
3.printf() : function to send formatted 2.The main() function is also a user-
output to the screen : defined defined function because the
in "stdio.h" header file. statements inside the main function
4. Some other library functions are is defined by the user, only the
scanf() to read input from the function name is defined in a
screen, getchar() to return library.
characters typed on screen,
putchar() to output a single
character to the screen, fopen() to
open a file, fclose() to close a file
etc.
User Defined Functions
”What you have to do when I call you“
A programmer can define their own sets of code inside a function and use it
for n number of times using its function name.
Function Declaration
•A declaration merely provides a function prototype.
•It tells the compiler about a function's name, return type, and parameters.
Function header :
Includes the return type and the list of parameters

Syntax:
return_type function_name( arg-typ name-1,...,arg-typ name-n);

Example:
int hex(int val);
int max(int num1, int num2);

Note: 1. Parameter names are not important in function declaration only


their type is required, so int max(int, int); is also a valid declaration
2. Function declaration is required when you define a function in one
source file and you call that function in another file.
Function Definition
The definition of a function includes both the function prototype and
the function body, i.e. its implementation.
Syntax : return_type function_name (argument list)
{
Set of statements – Block of code
}

function_na Block of
• Can be of me • Contains code
any data variables names
• Advised to have along with their • Set of C
type such as a meaningful statements,
data types
int, double, name • Kind of inputs which will be
char, void, • Easy to for the function executed
short etc. understand the argument whenever a
return_type purpose of call will be
list
function seeing made to the
it’s name function.
Calling a function
By creating a C To use a function,
function, we give a we will have to call
definition of what that function to
the function has to perform the defined
do. task.

When a program
calls a function, the
program control is
transferred to the
called function
which performs a
When its return defined task
statement is To call a function,
executed or when you simply need to
its closing brace is pass the required
reached, it returns parameters along
the program control with the function
back to the main name.
program.

If the function
returns a value,
Illustration of
working of
Functions in C
Example of functions

#include <stdio.h>
int main()
{ //main function definition
int a = 5, b = 10;
int sum;
printf("The value of a and b : %d %d ", a, b);
sum = add(a, b); //function call The value of a
printf("\nsum = %d ", sum); and b : 5 10
} sum = 15
//function definition
int add(int a, int b)
{
int c;
c = a + b;
return c; //returns a integer value to the calling function
}
Classification of user defined functions into four
types, according to parameters and return value

Functions wit Functions wit
hout hout
arguments bu arguments an
t with return d without
values return values

Functions wit Functions wit
h h
arguments bu arguments an
t without d with return
return values values
Functions Without Arguments Without Return Values

The calling function will not send parameters to the called function
and called function will not pass the return value to the calling function.

#include <stdio.h>
void add(); //function declaration
int main()
{ //main function definition
add(); //function call without passing arguments
}
//function definition
void add()
The value of a and b :
{ int a = 5, b = 10; 5 10
int c; sum = 15
printf(" The values of a and b : %d %d ", a, b);
c = a + b;
printf(" \nsum : %d ", c); //no return values to the calling function
}
Functions With Arguments Without Return Values

The calling function will pass parameters to the called function but
called function will not pass the return value to the calling function.
#include <stdio.h>
void add(int,int); //function declaration
int main()
{ //main function definition
int sum;
int a = 5, b = 10;
printf(" The values of a and b : %d %d ", a, b);
add(a, b); //function call with passing arguments to called function }
// function definition
void add(int a, int b) The value of a and b :
5 10
{
sum = 15
int c;
c = a + b;
printf(" \nsum : %d ", c); //no return values to the calling function
main
}
Functions Without Arguments With Return Values

The calling function will not pass parameters to the called function but
called function will pass the return value to the calling function.
#include <stdio.h>
int add(); //function declaration
int main()
{ //main function definition
int sum;
sum = add(); //function call without passing arguments to called
function
printf(" \nsum = %d ", sum);
}
// function definition The value of a and b :
int add() 5 10
sum = 15
{ int c;
int a = 5, b = 10;
printf(" The values of a and b : %d %d ", a, b);
c = a + b;
return c; //passing return values to the calling function main }
Functions With Arguments With Return Values

The calling function will pass parameters to the called function and
called function also pass the return value to the calling function
#include <stdio.h>
int add(int, int); //function declaration
int main()
{ //main function definition
int sum;
int a = 5, b = 10;
printf(" The values of a and b : %d %d ", a, b);
sum = add( a, b); //function call with passing arguments
printf(" \nsum = %d ", sum);
}
// function definition The value of a and b :
int add(int a, int b) 5 10
{ int c; sum = 15
c = a + b;
return c; //passing return values to the calling function main
}
Function Parameters
There are two types of function parameters:
Formal parameters:
Appear in a declaration or a definition of a function.

Actual parameters:
Appear in a call to the function.

Examples:
int f(int x); here x is a formal parameter

i = f(3); here 3 is the actual parameter


corresponding to the formal parameter.
Demonstrating difference between actual and formal
arguments
#include <stdio.h>  
int addTwoInts(int, int); /* Prototype */  
int main() /* Main function */
{
int n1 = 10, n2 = 20, sum;  
/* n1 and n2 are actual arguments. They are the source of data. Caller
program supplies the data to called function in
form of actual arguments. */
sum = addTwoInts(n1, n2); /* function call */  
printf("Sum of %d and %d is: %d \n", n1, n2, sum);

int addTwoInts(int a, int b)
/* a and b are formal parameters. They receive the values from actual
arguments when this function is called. */
{ return (a + b); }  

OUTPUT ====== Sum of 10 and 20 is: 30


Difference between Actual and Formal Parameters

Actual vs Formal Parameters

The Formal Parameters are the


The Actual parameters are the values
variables defined by the function that
that are passed to the function when it
receives values when the function is
is invoked.
called.

 Related Function

The actual parameters are passed by The formal parameters are in the called
the calling function. function.

Data Types

In actual parameters, there is no


In formal parameters, the data types of
mentioning of data types. Only the
the receiving values should be included.
value is mentioned.
Two ways of passing arguments to a function
Call by Value Call by Reference

1. While calling a function, instead of


1. While calling a function, we pass
passing the values of variables, we
values of variables to it. Such
pass address of variables(location of
functions are known as “Call By
variables) to the function known as
Values”.
“Call By References”.
2. In this method, the value of each 2. In this method, the address of actual
variable in calling function is copied variables in the calling function are
into corresponding dummy variables copied into the dummy variables of
of the called function. the called function.
3. With this method, the changes made
3. With this method, using addresses we
to the dummy variables in the called
would have an access to the actual
function have no effect on the values
variables and hence we would be
of actual variables in the calling
able to manipulate them
function.
Call by Value Call by Reference

4. Thus actual values of a and b remain 4. Thus actual values of a and b get
unchanged even after exchanging the changed after exchanging values of x
values of x and y. and y.

5. In call by values we cannot alter the


5. In call by reference we can alter the
values of actual variables through
values of variables through function calls.
function calls.

6. Pointer variables are necessary to


6. Values of variables are passed by
define to store the address values of
Simple technique.
variables.

7. A copy of the original variables are 7. No copy of the variables are created
created in memory stack. on the memory stack.

8. The pass by value approach creates


8. The pass by reference method creates
two or more copies of the original
only a single copy, thereby,
variables and, hence it is not memory
providing memory efficiency.
efficient.

9. The changes are visible only in


9. The changes are visible in every
a particular method where the
function.
arguments are passed.
// C program to illustrate call by value   
#include <stdio.h>   
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{    int a = 10, b = 20;
     // Pass by Values
    swapx(a, b); Output: x=20
    printf("a=%d b=%d\n", a, b); y=10 a=10 b=20
    return 0; }
// Swap functions that swaps two values
void swapx(int x, int y)
{     int t;
    t = x;
    x = y;
    y = t;
      printf("x=%d y=%d\n", x, y); }
// C program to illustrate call by reference   
#include <stdio.h>   
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{    int a = 10, b = 20;
     // Pass by Reference
Output: x=20
    swapx(&a, &b); y=10 a=20
    printf("a=%d b=%d\n", a, b); b=10
    return 0; }
// Swap functions that swaps two values
void swapx(int* x, int* y)
{     int t;
    t = *x;
    *x = *y;
    *y = t;
      printf("x=%d y=%d\n", *x, *y); }
Program to check prime numbers between two integers
#include <stdio.h>
int checkPrimeNumber(int n);
int main()
{ int n1, n2, i, flag;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("Prime numbers between %d and %d are: ", n1, n2);
for(i=n1+1; i<n2; ++i) {
// i is a prime number, flag will be equal to 1 Enter two positive
flag = checkPrimeNumber(i); integers: 12 30
if(flag == 1) printf("%d ",i); } Prime numbers
return 0; } between 12 and 30
// user-defined function to check prime number are: 13 17 19 23 29
int checkPrimeNumber(int n)
{ int j, flag = 1;
for(j=2; j <= n/2; ++j)
{ if (n%j == 0) { flag =0; break; } }
return flag; }
Program to Check Whether a Number can be Expressed
as Sum of Two Prime Numbers
#include <stdio.h>
int checkPrime(int n);
int main()
{ int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for(i = 2; i <= n/2; ++i) Enter a positive
{ // condition for i to be a prime number integer: 34
if (checkPrime(i) == 1) 34 = 3 + 31
{ // condition for n-i to be a prime number 34 = 5 + 29
if (checkPrime(n-i) == 1) 34 = 11 + 23 34 =
{ // n = primeNumber1 + primeNumber2 17 + 17
printf("%d = %d + %d\n", n, i, n - i); flag = 1; } } }
if (flag == 0)
printf("%d cannot be expressed as the sum of two prime numbers.", n);
return 0; }
// Function to check prime number
int checkPrime(int n) { int i, isPrime = 1; for(i = 2; i <= n/2; ++i) { if(n % i == 0)
{ isPrime = 0; break; } } return isPrime; }
• Program to check prime and
armstrong number using
function
• Program to print maximum of
Implement C three numbers using function.
programs • Program to find square of a
given number using function
• Write a program in C to check
a given number is even or odd
using the function
Quiz
1.What will be the output of the C program?
In C, parameters are always
A.Passed by value B. Passed by reference
C. Non-pointer variables are passed by value and pointers are passed by
reference
D. Passed by value result

2. #include<stdio.h>
int main()
{ function(); return 0; }
void function()
{ printf("Function in C is awesome"); }
A. Function in C is awesome B. no output C. Runtime error D. Compilation
error

3. #include<stdio.h>
int main()
{ main(); return 0; }
A. Runtime error B. Compilation error C. 0 D. none of the above
4. #include<stdio.h>
int function();
main()
{ int i;
i = function();
printf("%d", i);
return 0;
}
function()
{ int a;
a = 250;
return 0;
}
A. Runtime error B. 0 C. 250 D. No output
5. #include<stdio.h>
int function();
main()
{ int i;
i = function();
printf("%d", i);
return 0; }
function()
{ int a; a = 250; }
A. 250 B. 0 C. 1 D. Some Garbage value

6. #include<stdio.h>
int function(int, int);
int main()
{ int a = 25, b = 24 + 1, c;
printf("%d", function(a, b));
return 0; }
int function(int x, int y) { return (x - (x == y)); }
A. Compilation error B. 25 C. 1 D. 24
7. What will be the output of the C program by considering 'c' as a User input?
#include<stdio.h>
int main()
{ char c = ' ', x;
getc(c);
if((c >= 'a') && (c <= 'z'))
x = convert(c);
printf("%c", x); return 0; }
A. Runtime Error B. Any symbols or special characters C. Compilation Error D. B

8. #include<stdio.h>
int main()
{ int num = returns(sizeof(float));
printf("Value is %d", ++num); return 0; }
int returns(int returns)
{ returns += 5.01;
return(returns); }
A. 9 B. Compilation error C. 10 D. None of the above
Through this lecture, students will learn the
Learning basics of computer networks with its different
Outcomes topologies.

You might also like