Employablity presentation and Future Career Plan.pptx
Function lecture
1. A
Lecture
on
Function in C
Prepared by:
AJAY KUMAR
Assistant Professor
Department of CSE
DIT University, Dehradun
2. Introduction to Function in C
• Rely on person for so many other things
Eg. call a mechanic to fix up your bike
hire a gardener to mow your lawn
rely on a store to supply you groceries every month
• Similarly a computer program cannot handle all the
tasks by itself.
• So it requests other program —called ‘functions’ in
C—to get its tasks done.
visit us: http://sites.google.com/site/kumarajay7th/ 2
3. Modular Programming
(Top-Down Programming)
• Large program is broken into segments
i.e.number of smaller and simpler tasks.
• All individual segment is known as “module”.
Eg. In a mobile phone,
contact list
SMS
calculator Module
games
so on…
visit us:http://sites.google.com/site/kumarajay7th/ 3
4. Advantage of Modular Programming
• Codes and variables are isolated from other program
• Easy to debug or trace the errors
• Reuse the same code in other program also
• Less effort to write a new code for similar task
eg. printf(), scanf(), clrscr(),sqrt()
visit us: http://sites.google.com/site/kumarajay7th/ 4
5. Function
• A function is a self-contained block of
statements that perform a coherent task of
some kind.
• A function that calls or activates the function
and the function itself.
F SYSTEM-DEFINED FUNCTION
U Or PRE-DEFINED function
N Or Library function
C Or Built-in Function
T
I
O
User-Defined Function
N
5
visit us: http://sites.google.com/site/kumarajay7th/
6. Basic structure of function
Return_type function_name (arguments_list)
{
set of statements (or function body)
}
visit us: http://sites.google.com/site/kumarajay7th/ 6
7. Function (contd…)
• Built-in Function
Eg. Sqrt(),pow(),printf(),scanf()
• User-defined Function’s components
– Return type
– Function name
– Function argument list
– Function’s body= set of statements
visit us:http://sites.google.com/site/kumarajay7th/ 7
8. Function categories
on the basis of argument_list and return_type
• Function with no arguments and no return values
• Function with arguments and no return values
• Function with arguments and return values
• Function with no arguments and return values
visit us:http://sites.google.com/site/kumarajay7th/ 8
9. First Program of Function
#include<stdio.h>
#include<conio.h>
void main() Output:
{
clrscr();
1 printf(“n hello ”); Hello
message();
printf(“n everyone”);
Good morning
3
getch(); everyone
}
// function start
message()
{
2 printf(“n good morning”);
} visit us: http://sites.google.com/site/kumarajay7th/ 9
10. First program of Function
#include<stdio.h>
Header File
#include<conio.h>
void main() Main function
{ (Calling function)
clrscr();
printf(“n hello ”);
message(); body of statement in main function
printf(“n everyone”);
getch();
}
// function start Comments
message() User-defined function name
{ (Called function)
printf(“n good morning”); Body of statement in user-defined functi
} visit us: http://sites.google.com/site/kumarajay7th/ 10
11. Program example
void main( )
{
printf ( "ni am in main function" ) ;
Output:
italy( ) ;
printf(“n i am in middle of main”);
brazil( ) ;
?
printf(“n i am back to main”);
getch(); Output:
} I am in main function
italy() Hi how are you?
{ I am in middle of main
printf(“n Hi how are you?”); Hmmm, not bad
}
I am back to main
brazil()
{
printf(“n Hmmm, not bad!”);
} visit us: http://sites.google.com/site/kumarajay7th/ 11
12. Why use function?
• Writing functions avoids rewriting the same
code over and over.
• Separating the code into modular functions
makes the program easier to design and
understand.
visit us: http://sites.google.com/site/kumarajay7th/ 12
13. Function categories
on the basis of argument_list and return_type
• Function with no arguments and no return values
• Function with arguments and no return values
• Function with arguments and return values
• Function with no arguments and return values
visit us: http://sites.google.com/site/kumarajay7th/ 13
14. Function with
no arguments and no return values
#include<stdio.h>
#include<conio.h>
Function prototype declaration
void my_sms(void);
void main() output:
{
printf(“n send me a message”);
my_sms(); send me a message
my_sms(); plz rd my msg
} plz rd my msg
void my_sms()
{
print(“n plz rd my msg.”);
} visit us: http://sites.google.com/site/kumarajay7th/ 14
15. Function with
arguments and no return values
#include<stdio.h>
void factorial(int);
void main()
{
int n;
printf(“n enter a no.”);
scanf(“%d”, &n); Output:
factorial(n);
getch();
} Enter a no. 5
void factorial(int m)
Factorial of 5 is 120
{
int i,f=1;
for(i=1;i<=m;i++)
f=f*i;
printf(“n factorial of %d is %d”, m,f);
} visit us: http://sites.google.com/site/kumarajay7th/ 15
16. Function with
arguments and return values
#include<stdio.h>
#include<stdio.h> float add (int,int);
?
int compute(int,int); void main()
void main() {
{
int n1=100,n2=500,ans;
ans=compute(n1,n2);
? float n1,n2,ans;
printf(“n enter 2 no.”);
scanf(“%f%f”,&n1,&n2);
printf(“n largest no=%d”,ans); ans=add(n1,n2);
getch(); printf(“n sum=%f”,ans);
} getch();
}
int compute(int x,int y) float add(int a,int b)
{ {
if(x>y) float result;
return x; result=a+b;
else return result;
return y; } 16
visit us: http://sites.google.com/site/kumarajay7th/
17. Function with
No arguments and return values
#include<stdio.h> int p()
#include<conio.h> {
int p(); int i,power=1,n;
void main() printf("n enter value for power:");
{ scanf("%d",&n);
int my_p;
clrscr(); for(i=1;i<=n;i++)
my_p=p(); power=power*n;
printf("n power = %d", my_p);
getch(); return power;
} }
Output: enter value for power: 5
55= 5 x 5 x 5 x 5 x 5=3125
Power= 3125
visit us: http://sites.google.com/site/kumarajay7th/ 17
18. Excercise
Exercise:
void main(){
void main()
int i = 10, j = 20 ; {
printf ( "%d %d %d ", i, j ) ; int a = 1 ;
printf ( "%d", i, j ) ; printf ( "%d %d %d", a,++a,a++ ) ;
} }
Output;
10 20 860 Output:
10 331
Garbage value
visit us: http://sites.google.com/site/kumarajay7th/ 18
19. assignment
• WAP to find the factorial of a number using
function with arguments and return value
• Wap to find the cube of a number using
function with argument but no return value
• Write a c function which returns the biggest of
3 numbers.
• Do the exercise from Let-Us-C
visit us: http://sites.google.com/site/kumarajay7th/ 19
20. Function Prototype
Declaring a function is function prototype which
provides the compiler with a description that will be
defined at a later point in the program.
Syntax:
Return_type function_name(arg-type-1,arg-type-2,……..arg-type-n);
Example:
int my_square(int);
double amount(int,float,int);
void useless_msg(char[],int);
visit us: http://sites.google.com/site/kumarajay7th/ 20
21. Function definition
• An actual function is a snippet code that gets
executed.
• First line of function definition (known as
function header) should be identical to function
prototype with no semicolon.
• Example:
int my_square(int x)
{
Snippet long int my_sq;
code my_sq=x*x;
return my_sq;
visit us: http://sites.google.com/site/kumarajay7th/
} 21
22. Actual and Formal Parameter
#include<stdio.h>
int compute_sum(int,int);
void main() Actual Arguments
{ Variable used in (or Actual Parameter)
int sum,n1=10,n2=30; Calling function
sum=compute_sum(n1,n2);
printf(“total =%d”,sum);
getch();
}
int compute_sum(int x, int y)
{
return (x+y); Variable used in
Formal Parameter
} Called function
visit us: http://sites.google.com/site/kumarajay7th/ 22
23. Actual & Formal Parameter example
#include<stdio.h> #include<stdio.h> Output
Output
void plz_do_it(int); square (float); Enter a number: 2
Enter a number: 2
void main( ) Output: void main() 4.00000
4.00000
Enter a number: 2.5
Enter a number: 2.5
{ 60 {
6.000000
6.000000
int a = 30 ; 30 int a;
printf(“n enter a number”); wrong
plz_do_it ( a ) ;
scanf(“%f”,&a);
printf ( "n%d", a ) ; printf(“%f”,square(a));
} }
void plz_do_it ( int b ) square(float x)
{ {
b = 60 ; return (x*x);
printf ( "n%d", b ) ; }
} visit us: http://sites.google.com/site/kumarajay7th/ 23
24. Actual & Formal Parameter example
#include<stdio.h> #include<stdio.h>
wrong
Output
void plz_do_it(int); float square (float); Enter a number: 2
void main( ) Output: void main() 4.00000
{ Enter a number: 2.5
{ 60 6.000000
int a = 30 ; 30 int a;
printf(“n enter a number”);
plz_do_it ( a ) ;
scanf(“%f”,&a);
printf ( "n%d", a ) ; printf(“%f”,square(a)); correct
} } Output
void plz_do_it ( int b ) float square(float x) Enter a number: 2
{ { 4.00000
Enter a number: 2.5
b = 60 ; return (x*x);
6.250000
printf ( "n%d", b ) ; } Enter a number:1.5
} 2.250000
24
visit us: http://sites.google.com/site/kumarajay7th/
25. Scope Rules
• The scope of a variable is in the program or function in
which it is declared.
• A global variable is visible to all contained functions
including the function in which the variable is declared.
• An entity* declared in the scope of another entity is
always a different entity even if their names are
identical.
entity*= variable, function, parameter
visit us: http://sites.google.com/site/kumarajay7th/ 25
26. Scope Rule (contd…)
1. The scope of a variable is in the program or
function in which it is declared.
#include<stdio.h> void add(int x1,int x2)
void add(int,int); {
printf(“n sum=%d”,x1+x2);
void mul(int,int);
}
void main()
void mul(int y1,int y2)
{
{
int a=20,b=10; printf(“n multiplication=%d”,y1*y2);
add(a,b); }
mul(a,b);
Scope of variable a,b is within the main() only.
} Scope of variable x1,x2 is within the add() only.
visit
us:http://sites.google.com/site/kumarajay7th
/ Scope of variable y1,y2 is within the mul() only.
26
27. Scope Rule (contd…)
2. A global variable is visible to all contained functions
including the function in which the variable is declared.
#include<stdio.h> Global variable
int add_me();
A variable declared outside of a function.
int n1,n2;
They are known or accessed by any function
void main() {
comprising the program.
int my_sum;
my_sum=add_me();
printf(“n sum=%d”,my_sum);
} /* end of main*/ Local Variable
int add_me(){
A variable declared inside of a function. They are
int result; unknown to other function. i.e. scope is only within
Result=n1+n2; the function in which They are declared. Variable are
return result; Not accessed outside of function.
visit us: http://sites.google.com/site/kumarajay7th/ 27
}
28. Scope Rules (contd…)
• An entity* declared in the scope of another
entity is always a different entity even if their
names are identical.
entity*= variable, function, parameter
Example; ??????
visit us: http://sites.google.com/site/kumarajay7th/ 28
29. Parameter passing method
on the basis of argument (or parameter)
Parameter passing method
Pass by Value Pass by Reference
Or Call by value Or Call by Reference
When the values of arguments are passed Actual values are not passed, instead
From the calling function to the called their addresses are passed. There is no
function, The values are copied into called copying of values since their memory
function. locations are referenced.
If any changes made to the value in calling If any changes is made to value in
function, There is no change in the original called function, The original value gets
values within the calling function. changed within the calling function.
29
visit us :http://sites.google.com/site/kumarajay7th/
30. Call by values
//swaping the value by callByValue
//no change in calling function
#include<stdio.h>
void call_by_value(int,int);
#include<stdio.h>
void main( )
void no_change_value(int);
{
void main( ) Output:
int a = 10, b = 20 ;
{ B=60
call_by_value ( a, b ) ;
int a = 30 ; A=30
printf ( "na = %d t b = %d", a, b ) ;
no_change_value ( a ) ;
}
printf ( "na=%d", a ) ;
void call_by_value ( int x, int y )
}
{
void no_change_value ( int b )
int t ; Output:
{
t=x; x = 20 y = 10
b = 60 ;
x=y; a = 10 b = 20
printf ( "nb= %d", b ) ;
y=t;
}
printf ( "nx = %d t y = %d", x, y ) ;
visit us: http://sites.google.com/site/kumarajay7th/ 30
}
31. Pointer
(know it before using call by reference)
Let us take an example, int i=3;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
Memory map
i Location name
For Value at location
i’s location
65524 Location number
31
visit us: http://sites.google.com/site/kumarajay7th/
32. Pointer (contd…)
Memory map
i Location name
For Value at location
i’s location
65524 Location number
void main( )
%u=unsigned integer output:
{
Address of i = 65524
int i = 3 ;
Value of i = 3
printf ( "nAddress of i = %u", &i ) ;
printf ( "nValue of i = %d", i ) ;
} First time used & in printf() indicating
visit us: http://sites.google.com/site/kumarajay7th/
address of variable 32
33. Pointer (contd…)
&(address operator) and *(indirection operator)
main( )
main( ) {
{ int i = 3 ;
int i = 3 ; printf ( "nAddress of i = %u", &i ) ;
printf ( "nAddress of i = %u", &i ) ; printf ( "nValue of i = %d", i ) ;
printf ( "nValue of i = %d", i ) ; printf ( "nValue of i = %d", *( &i ) ) ;
} }
output: output:
* is known as
Address of i = 65524 Address of i = 65524 ‘indirection
Value of i = 3 Value of i = 3
Value of i = 3
operator’ or
‘value at address’
visit us: http://sites.google.com/site/kumarajay7th/ 33
34. Pointer (contd…)
Output:
main( ) Address of i = 65524
{ Address of i = 65524
Pointer variable (‘j’ in Address of j = 65522
int i = 3 ;
this case) contains Value of j = 65524
int *j ; Value of i = 3
address of other
variable (‘i’ in this case) Value of i = 3
j = &i ; Value of i = 3
printf ( "nAddress of i = %u", &i ) ;
printf ( "nAddress of i = %u", j ) ;
printf ( "nAddress of j = %u", &j ) ; i j
printf ( "nValue of j = %u", j ) ;
printf ( "nValue of i = %d", i ) ;
3 65524
printf ( "nValue of i = %d", *( &i ) ) ; 65524 65522
printf ( "nValue of i = %d", *j ) ;
} visit us: http://sites.google.com/site/kumarajay7th/ 34
35. Call by reference
//swapping the value by reference void call_by_reference( int *x, int *y )
#include<stdio.h> {
void call_by_reference(int*, int*); int t ;
void main( ) { t = *x ;
int a = 10, b = 20 ; *x = *y ;
printf(“n before swappingn”); *y = t ;
printf(“n a=%d t b=%d”,a,b); }
call_by_reference( &a, &b ) ;
printf(“n after swappingn”); Output:
printf ( "na = %d b = %d", a, b ) ;
before swapping
}
a=10 b=20
after swapping
visit us: http://sites.google.com/site/kumarajay7th/
a=20 b=10 35
36. Call by value vs call by reference
Call by value Call by reference
It consumes more memory It consumes less memory
space because formal space because irrespective
parameter also occupies of data type of the actual
memory space. arguments, each pointer
occupies only 4 bytes
It takes more time to It takes less time because
execute because the values no values are copied.
are copied.
visit us: http://sites.google.com/site/kumarajay7th/ 36
37. Exercise
• Write a C program using function to find the
numbers between 1 to 1000 which follows the
property that 12 possesses. i.e.
(a) The number is 12
(b) Take it reverse (i.e.21) and square it (i.e. 441)
(c) Now take the square of 12 (i.e. 144)
(d) Compare the result of step (b) & step (c)
(e) If they are reverse of each other then print 12.
visit us: http://sites.google.com/site/kumarajay7th/ 37
38. Recursion(A recursive function)
• A function is called ‘recursive’ if a statement
within the body of a function calls the same
function.
• Sometimes called ‘circular definition’,
recursion is thus the process of defining
something in terms of itself.
• A situation in which a function calls itself
either directly or indirectly.
visit us:http://sites.google.com/site/kumarajay7th/ 38
39. Recursion (contd…)
e.g. Recursion can be used to calculate factorial of a number.
X!= x* (x-1)* (x-2)*(x-3)*…*2*1
e.g.
However x! may be calculated as find the factorial of 4
X!=x*(x-1)!
And then (x-1)!= (x-1)*(x-2)!
4!=4*3*2*1
Or
And then (x-2)!=(x-2)*(x-3)! 4!=4*3!
------------------------
----------------------
And so on……
visit us: http://sites.google.com/site/kumarajay7th/ 39
40. Recursion example
.
Q find the factorial of a number using recursion
main( ) rec ( int x )
{ {
int a, fact ; int f ;
printf ( "nEnter any number " ) ; if ( x == 1 )
return ( 1 ) ;
scanf ( "%d", &a ) ; else
fact = rec ( a ) ; return (x * rec ( x - 1 )) ;
printf ( "Factorial value = %d", fact ) ; }
}
visit us: http://sites.google.com/site/kumarajay7th/ 40
41. Recursion concept understanding
return ( x * rec ( x - 1 )) ; Important line
rec ( 5 ) returns ( 5 times rec ( 4 ),
which returns ( 4 times rec ( 3 ),
which returns ( 3 times rec ( 2 ),
which returns ( 2 times rec ( 1 ),
which returns ( 1 ) ) ) ) )
visit us: http://sites.google.com/site/kumarajay7th/ 41
42. Recursion flow example
Starts here
visit us: http://sites.google.com/site/kumarajay7th/ 42
43. Assignment on recursion
1. Find the factorial of a given number using recursion.
2. Generate fibonacci series upto nth terms using recursion
3. Define power function using recursion
4. Find the greatest common divisor (GCD) of 2 no.
5. Conversion from decimal to binary
visit us: http://sites.google.com/site/kumarajay7th/ 43
44. Special assignment on function
• Go through Let-Us-C of chapter function
• Try to generate your own function, say myf()
• Save a defined function myf() with new .cpp file name ,
say myf.cpp
• Save a new header file with declaring myf() prototype,
say myf.h
• Add this header file myf.h to TurboC library
• Include this header file in your new file and execute the
statement, #include ”myf.h”
1. do_it(). 2.print_me(). 3.add_me() 4.print_table()
visit us: http://sites.google.com/site/kumarajay7th/ 44
45. Data Storage in C
1.Variable’s value stores at two location:
• Memory and
• CPU Register
2.Variable’s storage class tells us:
Where the value would be stored.
Default initial value
Scope of a variable
Life of a variable
visit us: http://sites.google.com/site/kumarajay7th/ 45
46. Type of Storage Class
Data storage
Automatic
Register Static External
visit us: http://sites.google.com/site/kumarajay7th/ 46
47. Automatic Storage Class (keyword:auto)
• Storage- Memory
• Default Initial Value- garbage value
• Scope- local to the block in which variable is defined
• Life- within the block
void main( ) {
void main( ) auto int i = 1 ;
{ { Output:
auto int i, j ; { 1 1 1
{
printf ( "n%d %d", i, j ) ; printf ( "n%d ", i ) ;
} }
printf ( "%d ", i ) ;
Output: Garbage value
}
1211 221 printf ( "%d", i ) ;
}
visit us: http://sites.google.com/site/kumarajay7th/ 47
}
48. Automatic Storage class example
void main( )
{
auto int i = 1 ; Output:
{
auto int i = 2 ;
{ 3
auto int i = 3 ; 2
printf ( "n%d ", i ) ;
}
1
printf ( “n%d ", i ) ;
}
printf ( “n%d", i ) ;
}
48
visit us: http://sites.google.com/site/kumarajay7th/
49. Register storage class
• Storage - CPU registers.
• Default initial value - Garbage value.
• Scope - Local to the block in which the variable is defined.
• Life - remains within the block in which the variable is
defined.
void main( )
{ Register variable is
register int i ; used to use the
for ( i = 1 ; i <= 10 ; i++ ) variable frequently.
printf ( "n%d", i ) ;
}
visit us: http://sites.google.com/site/kumarajay7th/ 49
50. Static Storage class
• Storage − Memory.
• Default initial value − Zero.
• Scope − Local to the block in which the variable is defined.
• Life − Value of the variable persists between different function calls.
void main( ) increment( ) Output:
{ { 1
increment( ) ; static int i = 1 ;
2
increment( ) ; printf ( "%dn", i ) ;
increment( ) ; i=i+1;
3
Output:
} } auto int i=1; 1
1 50
visit us:http://sites.google.com/site/kumarajay7th/
1
51. External Storage Class
(keyword:extern)
• Storage − Memory.
• Default initial value − Zero.
• Scope − Global.
• Life − As long as the program’s execution doesn’t come to an end.
int i ; increment() { Output:
main( ) i=i+1;
{ printf ( "non incrementing i = %d", i ) ; i=0
printf ( "ni = %d", i ) ; } on incrementing i =
decrement( ) 1
increment( ) ; { on incrementing i =
increment( ) ; i=i-1; 2
decrement( ) ; printf ( "non decrementing i = %d", i ) ; on decrementing i =
decrement( ) ; } 1
} visit us: http://sites.google.com/site/kumarajay7th/
on decrementing i =
51
52. Extern Storage Class Example
int x = 21 ; global
void main( )
{ Declaring a variable
extern int y ; Requires no space Defining a
printf ( "n%d %d", x, y ) ; variable
space gets
} reserved
int y = 31 ;
global
visit us:http://sites.google.com/site/kumarajay7th/ 52
53. Extern storage class example (contd…)
int x = 10 ; Global x
main( )
{ Confused ?
int x = 20 ; Local x
printf ( "n%d", x ) ;
display( ) ;
} Output: Preference is given
20 to local variable
display( )
{
10
printf ( "n%d", x ) ;
} us: http://sites.google.com/site/kumarajay7th/
visit 53
54. Excercise
• From Let-Us-C
visit us:http://sites.google.com/site/kumarajay7th/ 54