You are on page 1of 60

Functions

➢I N T R O D U C T I O NTO FUNCTIONS
➢T Y P E S O F F U N C T I O N S
➢E L E M E N T S O F U S E R D E F I N E D F U N C T I O N S
➢T Y P E S O N T H E B A S I S O F A R G U M E N T S A N D
RETURN VALUES
➢M E T H O D S O F C A L L I N G A F U N C T I O N
Introduction to Function

Block of statements that perform the particular task.


Enables modular programming.
Main() is the driver function.
Has pre defined prototype.
Same function can be accessed from different places
within a program.
Once a function execution is completed , control
return to the place from where the function was
called.
Advantages

Modular Programming
Length of source program can be reduced
Easy to locate and isolate faulty function
Functions can be used by other program’s
Types of Functions

Library (Built In) Functions:


 They are written in the header files.
 To use them appropriate header files should be included.
Header Files Functions Defined
stdio.h Printf(), scanf(), getchar(), putchar(),
gets(), puts(), fopen(), fclose()
conio.h Clrscr(), getch()
Ctype.h Toupper(), tolower(), isalpha()
Math.h Pow(), sqrt(), cos(), log()
Stdlib.h Rand(), exit()
String.h Strlen(), strcpy(), strupr()
User Defined Functions
 Written by the user at the time of programming.
Elements of User defined functions

Function Prototype
Function Call
Function arguments and parameters
Function Definitions
Function prototype

It specify the type of value that is to be return from


the function and that is to be passed to the function.
It is defined in the beginning before the function call
is made.
Syntax:
 return-type name-of-function(list of arguments);
 Example
Void sum(int, int);
Function Call

A function can be called by specifying name and list


of arguments enclosed in parenthesis and separated
by comma.
If there is no arguments empty parenthesis are place
after function name.
If function return a value, function call is written as
assignment statement as:
 A=sum(x,y);
Function arguments and parameters

Arguments are also called actual parameters.


Arguments are written within parenthesis at the time
of function call.

Parameters are also called formal parameters.


These are written within parenthesis at the time of
function definition.
Function Definition

It is the independent program module.


It is written to specify the particular task that is to be
performed by the function.
The first line of the function is called function
declarator and rest line inside { } is called function
body
#include<stdio.h>
#include<conio.h>
void sum(int , int );

int main()
{
int a,b;
printf("enter num \n");
scanf("%d%d",&a,&b);
sum(a,b);

getch();
return 0;
Return statement

It is the last statement of the function that return


certain values.
It return certain types of values to the place from
where the function was invoked.
Syntax:
 return(variable-name or constant);
Categories of function

Function with no arguments and no return


Function with arguments but no return
Function with no arguments and return
Function with arguments and return
N o argument no
return
#include<stdio.h>
#include<conio.h>
void sum()
{
int a,b;
printf("enter num \n");
scanf("%d%d",&a,&b);
printf(" num after sum %d \n",a+b);

int main()
{
Function with argument and no return

#include<stdio.h>
#include<conio.h>
void sum(int x,int y)
{

printf(" num after sum %d \n",x+y);

int main()
{
int a,b;
printf("enter num \n");
scanf("%d%d",&a,&b);
sum(a,b);
getch();
return 0;
}
Function with no argument and return

#include<stdio.h>
#include<conio.h>
int sum()
{
int a,b;
printf("enter num \n");
scanf("%d%d",&a,&b);
return a+b;

int main()
{
int x;
x=sum();
printf("value %d",x);
getch();
return 0;
}
Function with argument and return

#include<stdio.h>
#include<conio.h>
int sum(int a, int b)
{

return a+b;

int main()
{
int x,y,z;
printf("enter num \n");
scanf("%d%d",&x,&y);
z=sum(x,y);
printf("value %d",z);
getch();
return 0;
Methods of calling function

Call by value
Call by reference
Call by value

Copies the value of actual parameters into formal


parameters.
During execution whatever changes are made in the
formal parameters are not reflected back in the
actual parameters.
swap

#include<stdio.h>
#include<conio.h>
void swap(int x, int y)
{
int t;
t=x;
x=y;
y=t;
}
void main()
{
int a,b;
printf("enter num \n");
scanf("%d%d",&a,&b);
printf(" num befor call a=%d and b=%d\n",a,b);
swap(a,b);
printf(" num after call a=%d and b=%d \n",a,b);
getch();
}
Call by Reference

Reference(address) of the original variable is passed.


Function does not create its own copy, it refers to the
original values by reference.
Functions works with the original data and changes
are made in the original data.
Swap

#include<stdio.h>
#include<conio.h>
void swap(int *x, int *y)
{
int t;
t=*x;
*x=*y;
*y=t;
}
void main()
{
int a,b;
printf("enter num \n");
scanf("%d%d",&a,&b);
printf(" num befor call a=%d and b=%d\n",a,b);
swap(&a,&b);
printf(" num after call a=%d and b=%d \n",a,b);
getch();
}
Recursion, Debugging

SauleAnay
Fall 2016, NU, CSCI151
You should know already
• Functions
• Function parameters and arguments
• How to call function
• Global vs local variables
Recursion
• is a method where the solution to a problem
depends on solutions to smaller instances of
the same problem.
example: 2^11 = 2^10 * 2 = 1024 * 2
• one of the central ideas of computer science.
How do you empty a vasecontaining five
flowers?

Answer: if the vase is not empty, you take out one


flower and then you empty a vase containing four
flowers.
How do you empty a vase containing four flowers?
Answer: if the vase is not empty, you take out one
flower and then you empty a vase containing three
flowers.

How do you empty a vase containing one flower?
Answer: if the vase is notempty, you take out one
flower and then you empty a vase containing no
flowers.
How do you empty a vase containing no flowers?
Answer: if the vase is notempty, you take out one
flower but the vase is empty so you're done.
Base cases vs recursive cases
• one or more base cases:
– input(s) for which the function produces aresult
trivially (without recurring),
– Base case for emptyVase: vase with zero flowers
• one or more recursive cases: input(s)for
which the program recurs (calls itself).
Example: vase with flowers bigger than zero.
How do you
em
• Base: if Flowers=0  done. ptyVase is empty
a
• Recursive case: for all flowers>0, take out one
vase
flower, empty Vase of (N-1) flowers
con
tain
ing
five
flo
wer
s?
emptyVase program code
1. #include <stdio.h>
2. #include<conio.h>
3. void emptyVase(int numFlowers)
4. {
5. if (numFlowers ==0)
6. {
7. printf("Vase is empty now\n");
8. //return;
9. }
10. if (numFlowers>0)
11. {
12. numFlowers--;
13. printf("one flower have been taken
out\n");
14. emptyVase(numFlowers);
15. } //end of IF statement
16. } //end of Function
17. int main () {
18.
19. int flowers =8;
20. emptyVase(flowers);
21. getch();
22. return 0;
23. }
Check list recursive
function
• Have a base case
• Function call itself (recursive call)
• Recursive call MUST be with different input,
so that the base case must be reached
eventually
Recursion vs

iteration
Similarity
– Both repeat block of codes
• Difference
–iteration: loops to repeat the block of code
–recursion: call itself to repeat the block of code
Temination:
iteration: loop condition
recursion: base case
Infinite execution:
iteration: never reach loop condition
recursion: never reach basecase
Which is better?
• It depends from situation:
– Some problem difficult to solveiteratively
– Some problem difficult to solverecursively
• Math people like recursion
– Shorter solution, abstraction
– To find good recursive solution is not alwayssimple.
• CSpeople like iteration
– Easier to construct
– Easier to iterate and simulate (lessmagical)
Phillips head vs flat
headscrewdriver:
which isbetter?
It depends from
situation

recursion iteration
Examples of recursive solution
1.Factorial:
Base case:0! = 1
Recursive case: for all n > 0, n! = n(n −1)!
2.fibbonachi:
Base case:Fn(1) = 1, Fn(2) = 1
Recursive case: for all n > 2, Fn(n) =Fn(n-
1)+Fn(n-2)
3.X^n (x to the powern)
Base case: if n=0,x^n=1
Recursive case: for all n>0,x^n=x*x^(n-1)
Example with
Factorial
Factorial recursive
1.
2. function
#include <stdio.h>
#include<conio.h>
3. int factorial(int n)
4. {
5. //base case
6. if(n==0)
7. return 1;
8. //recursive case
9. if (n>0)
10. return n*factorial(n-1);
11. //default case if n<0

12. } //end Factorial

13. int main ()


14. {

15. int number=8;


16. printf("fatorial of %i is %i \n", number, factorial(number));
17. getch();
18. return 0;
19. }
conclusion
• How to know if functionrecursive?
– It must call itself
• Recursive function must have 2 cases:
– Base case
– Recursive case
• Any recursion can be rewritten with iteration
• Which to choose depends on situation
What is inside myprogram?
Computer memory
What happenswhen?
1. you declare new variable?
2. You declare newarray
3. You call afunction

Computer allocates memory for variable,fro


array
continu
function name var name value e line console
main flowers 8 29
one flower have beentaken
emptyVase(8) numFlowers 7 12 out
one flower have beentaken
emptyVase(7) numFlowers 6 12 out
one flower have beentaken
emptyVase(6) numFlowers 5 12 out
one flower have beentaken
emptyVase(5) numFlowers 4 12 out
one flower have beentaken
emptyVase(4) numFlowers 3 12 out
one flower have beentaken
emptyVase(3) numFlowers 2 12 out
one flower have beentaken
emptyVase(2) numFlowers 1 12 out
one flower have beentaken
emptyVase(1) numFlowers 0 12 out
emptyVase(0) numFlowers 0 vase is empty
Tasks

1- write c function program that converte currancy


form dollar to pound ,yan,franc. Assume dollar=
17,yan=8,franc=9
2- write c function program that compute factrial.
3- write c function to compute Power of a Number
with recursive.
What is Memory?

Computer memory is any physical device capable of storing


information temporarily or permanently.

Memory is the processes by which information isencoded,


stored and retrieved.
What is stack Heap?

Stack is. used for static memory allocation and Heap for dynamic memory allocation, both
stored in the computer's RAM .
Variables allocated on the stack are stored directly to the memory and access to this
memory is very fast, and it's allocation is dealt with when the program is compiled. When
a function or a method calls another function which in turns calls another function etc.,
the execution of all those functions remains suspended until the very last function
returns its value. The stack is always reserved in a LIFO order, the most recently reserved
block is always the next block to be freed. This makes it really simple to keep track of the
stack, freeing a block from the stack is nothing more than adjusting one pointer.
Variables allocated on the heap have their memory allocated at run time and accessing
this memory is a bit slower, but the heap size is only limited by the size of virtual memory
. Element of the heap have no dependencies with each other and can always be accessed
randomly at any time. You can allocate a block at any time and free it at any time. This
makes it much more complex to keep track of which parts of the heap are allocated or
free at any given time.
Representation of
stack and heap
Type of Memory Allocation
There are two type of memoryallocation.
1) Static memory allocation.
2) Dynamic memory allocation.
Different Between Static and dynamic memoryallocation.
• Static memory allocation is allocated the memoryat
the compile time. Dynamic at the runtime of
execution of program.
• In static memory can’t be increase whileexecution of
the program. But in the dynamic memory can
increase while executing the program.
• Static used in array and dynamic used in linkedlist.
Memory space required caman be specified at the
timeof execution.

The concept of dynamic memory allocation in c


language enables the C programmer to allocatememory
at runtime. Dynamic memory allocation in c language is
possible by 4 functions of stdlib.h headerfile.
➢ malloc()
➢ calloc()
➢ realloc()
➢ free()
function
What is Allocation?

An allocation is something that you set aside for use. For


instance if you want to set aside a certain amount of hard
drive space for an application.

Memory allocation is the process of setting aside section


of memory in a program to be used to store variables, and
instances of structure andclasses.

.
malloc()
The declaration of malloc ( ) functionis
Syntax:-
Void*malloc(size_t size)
Example:- int *nums =(int*)malloc(5*sizeof(int));
This is similar to int *nums=newint[5];
➢Deallocation of using free[] function-
free(nums);
➢This is special function that are used to assign valueto
variable.
➢ New return exact datatype, while malloc() return void
pointer.
➢To use malloc() you must#include<stdlib.h>
malloc() …continue….

➢ On error malloc()return NULL.


➢ If size =0 malloc() also return NULL.
➢ The malloc function allocates a block of size bytes from
the memory heap.
➢ It allows a program to allocates memory as it’sneeded
and in the exact , amountneeded.
➢ On success malloc() return a pointer to the newely
allocated block of memory.
malloc()….. Continue..

char *charpt; / * declare a pointer to char * /

charpt

charpt = malloc(10);
10 bytes or chars
charpt

charpt contains the address of the beginning of that


block.
calloc()

The calloc() function allocates multiple blockof


requested memory.
It returns NULLif memory is notsufficient.
The declaration of calloc ( ) functionis –
void *calloc(size_t n items , size_tsize)

Example:- ptr = (float*) calloc(25, sizeof(float));


calloc() provided access in c memory heap. which is
available for dynaminc allocation of variable sizeblock
of memory.
calloc()… continue..

➢ The name calloc stands for "contiguous allocation".


➢ The only difference between malloc() and calloc() is
that, malloc() allocates single block ofmemory whereas
calloc() allocates multiple blocks of memory each of
same size and sets all bytes to zero.
➢ Allocates space for an array of elements, initializesthem
to zero and then returns apointer.
realloc()

➢ Reallocates the memory occupied by malloc() orcalloc()


functions.
Syntax:-
void *realloc(void *ptr, size_tnewsize);
Let’s take an example:-
int *ptr;
/ / allocate memory for 5 integers

ptr =(int*)malloc(5*sizeof(int));
/ / allocate memory for 6 more integers i.e a total of 11.

ptr = (int*)realloc(ptr, 11*sizeof(int));


realloc() ….continue..
#include <stdio.h>
#include<string.h>
int main () {
char *str;
/* Initial memory allocation */ str =
(char *) malloc(5);
strcpy(str, "kiran");
printf("String = %s, Address = %u\n",
str, str);
/* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, "patel");
printf("String = %s, Address = %u\n",
str, str);
free(str);
getch();}
Output:-
free()

The Clibrary function void free(void *ptr)


deallocates the memory previously allocated by
a call to calloc, malloc, or realloc.
Syntax:-
void free(void
*ptr) Example:-
Int main(){
char *str;
-----
-----
free(str);
}
Find Largest Element Using Dynamic Memory
Allocation - calloc()

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
int main()
{
int i, num;
float *data;
printf("Enter total number of elements(1 to 100): ");
scanf("%d", &num);
// Allocates the memory for 'num' elements.
data = (float*) calloc(num, sizeof(float));
if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
printf("\n");
// Stores the number entered by the user.
for(i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}
// Loop to store largest number at address data
for(i = 1; i < num; ++i)
{
// Change < to > if you want to find the smallest number
if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f", *data);
getch();
return 0;
}
task

Write a C program to find sum of n elements


entered by user allocate memory
dynamically

You might also like