Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views7 pages

PSPC Unit II B Functions

The document provides an overview of functions in C programming, including their definitions, prototypes, and the use of library functions. It covers concepts such as modular programming, call by value and reference, and recursion, with examples demonstrating their implementation. Additionally, it discusses the benefits of using functions for code reusability and management.

Uploaded by

gdrivee515
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views7 pages

PSPC Unit II B Functions

The document provides an overview of functions in C programming, including their definitions, prototypes, and the use of library functions. It covers concepts such as modular programming, call by value and reference, and recursion, with examples demonstrating their implementation. Additionally, it discusses the benefits of using functions for code reusability and management.

Uploaded by

gdrivee515
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

10/12/2023

Dr. Dileep Kumar Singh


Head, JLU-SOET
[email protected]

Problem Solving and Program


Design using C

Problem Solving and Program Design using C

UNIT –II

B Tech/B Tech (Hons.) CSE – 1st Sem.

Functions

Program Modules in C
• Functions: Modules in C
– Programs combine user-defined functions with library functions
• C standard library has a wide variety of functions
• Math function, I/O function, such as printf(), scanf()
• Function calls: Invoking functions
• Provide function name and arguments (data)
• Function performs operations or manipulations and return the results
• Write function once and call it many times
– Function call analogy:
• Boss asks worker to complete task
– Worker gets information, does task, returns result
– Information hiding: boss does not know details
– Also called Encapsulation

Dr. Dileep Kumar Singh 1


10/12/2023

Math Library Functions


• Math library functions
– perform common mathematical calculations
– #include <math.h>
• Format for calling functions
– FunctionName( argument );
• If multiple arguments, use comma-separated list
– printf( "%f", sqrt( 900.0 ) );
• Calls function sqrt, which returns the square root of its
argument
• All math functions return data type double
– Arguments may be constants, variables, or expressions

Functions
• Functions: Modularize a program
– All variables declared inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
• Local variables
• Benefits of functions
– Divide and conquer
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition

Function Definitions
• Function definition format
return-value-type function-name( parameter-list )
{ declarations and statements }
– Function-name: any valid identifier
– Return-value-type: data type of the result (default int)
• void – indicates that the function returns nothing
• An unspecified return-value-type is always assumed by the compiler to be int
– Parameter-list: comma separated list, declares parameters
• A type must be listed explicitly for each parameter, unless the parameter is of type int
– Declarations and statements: function body (block)
• Variables can be declared inside blocks (can be nested)
• Functions can not be defined inside other functions
– Returning control
• If nothing returned: return; or, until reaches right brace
• If something returned : return expression;

Dr. Dileep Kumar Singh 2


10/12/2023

Function Prototypes
• Function prototype
– Function name
– Parameters – what the function takes in
– Return type – data type function returns (default int)
– Used to validate functions
– Prototype only needed if function definition comes after use in
program
– The function with the prototype
int maximum( int, int, int );
• Takes in 3 ints
• Returns an int

Examples:
Example 1: …
float mySquare(float);
main()
{
float y;
printf(“%f\n”, mySquare(5.0));
}
float mySquare(float x)
{
return x*x;
}

Example 2: /* calculate the sum from 1+2+…+n */


int sum(int n)
{
int i, sum = 0;
for (i=1; i<=n; i++)
sum += i;
return(sum);
}
main()
{
int j,n;
printf(“input value n: “);
scanf(“%d”,&n);
for (j=1; j<=n; j++)
printf(“sum from 1 to %d is %d\n”,j,sum(j));
}

Header Files

• Header files
– Contain function prototypes for library functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
• Custom header files
– Create file with functions
– Save as filename.h
– Load in other files with #include "filename.h"
– Reuse functions

Dr. Dileep Kumar Singh 3


10/12/2023

Calling Functions: Call by Value and Call by Reference


• Used when invoking functions
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
• Avoids accidental changes
Example:
addone(int);
main ()
{
int i = 5, j;
j=addone(i); 5 6
printf(“%d %d\n”,i, j);
}

addone(int x)
{
return ++x;
}

10

Calling Functions: Call by Value and Call by Reference

• Call by reference (Passing Address)


– Using & operator to pass address
– Only used with trusted functions
Example:
addone(int *);
main ()
{
int i = 5, j;
j=addone(&i);
printf(“%d %d\n”,i, j); 6 6
}
addone(int *x)
{
return ++(*x);
}
• For now, we focus on call by value

11

Recursion

• In some problems, it may be natural to define the problem in


terms of the problem itself.
• Recursion is useful for problems that can be represented by a
simpler version of the same problem.
• Example: the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1

We could write:
6! = 6 * 5!

12

Dr. Dileep Kumar Singh 4


10/12/2023

Example: factorial function

• In general, we can express the factorial function as


follows:
n! = n * (n-1)!
Is this correct? Well… almost.
• The factorial function is only defined for positive
integers. So we should be a bit more precise:
n! = 1 (if n is equal to 1)
n! = n * (n-1)! (if n is larger than 1)

13

factorial function

• The C++ equivalent of this definition:


int fac(int numb){
if(numb<=1)
return 1;
else
return numb * fac(numb-1);
}
• recursion means that a function calls itself

14

factorial function
• Assume the number typed is 3, that is, numb=3.
fac(3) :
3 <= 1 ? No.
fac(3) = 3 * fac(2)
fac(2) :
2 <= 1 ? No.
fac(2) = 2 * fac(1)

fac(1) :
1 <= 1 ? Yes.
return 1
int fac(int numb){
fac(2) = 2 * 1 = 2 if(numb<=1)
return fac(2) return 1;
else
fac(3) = 3 * 2 = 6 return numb * fac(numb-1);
return fac(3) }
fac(3) has the value 6

15

Dr. Dileep Kumar Singh 5


10/12/2023

factorial function
• For certain problems (such as the factorial function), a recursive solution often
leads to short and elegant code. Compare the recursive solution with the
iterative solution:

Iterative solution
Recursive solution
int fac(int numb){
int fac(int numb){ int product=1;
if(numb<=1)
while(numb>1){
return 1;
else
product *= numb;
return numb*fac(numb-1); numb--;
} }
return product;
}

16

Recursion

• We have to pay a price for recursion:


– calling a function consumes more time and memory than
adjusting a loop counter.
– high performance applications (graphic action games, simulations
of nuclear explosions) hardly ever use recursion.
• In less demanding applications recursion is an attractive
alternative for iteration (for the right problems!)

17

Recursion

• If we use iteration, we must be careful not to create


an infinite loop by accident:

for(int incr=1; incr!=10;incr+=2)


...

Oops!
int result = 1;
while(result >0){
...
result++;
}
Oops!

18

Dr. Dileep Kumar Singh 6


10/12/2023

Recursion
Similarly, if we use recursion we must be careful not
to create an infinite chain of function calls:
int fac(int numb){ Oops!
return numb * fac(numb-1); No termination
} condition
Or:
int fac(int numb){
if (numb<=1)
return 1;
else
return numb * fac(numb+1);
} Oops!

19

THANKS

20

Dr. Dileep Kumar Singh 7

You might also like