Professional Documents
Culture Documents
Functions-building block of C
programming language.
• is a subroutine that contains one or more
statements and performs one or more tasks
• is a section of a program which perform a
specific task. The task assigned to a function is
performed whenever C encounters the
function name.
• Is actually a subprogram that is, a function
perform a task within a program and is written
in a form similar to C main program.
2 Types of Function
• Standard function
• Programmer-defined function
Reuse of Code
• Functions can be executed more than once
• Easier to alter code
Procedural Abstraction
• Procedures – functions in C
• A programming technique in which we use function subprograms to allow us to remove from
the main function, the code that provides detailed solution to a sub-problem.
Syntax:
type_specifier function_name(parameter_list)
{ body of function
}
• type_specifier / return_type
– ( specifies the type of value that the function returns
using the return statement.
• parameter_list / function_argument
– ( comma separated list of variables that receive the
values of the arguments when the function is called.
– ( a function maybe without parameters in which case the
parameter list contains only the keyword void.
Uses of return Statement:
• it causes an immediate exit from the function
it is in. That is, it causes program execution to
return to the calling code.
• it can be used to return a value.
#include <stdio.h>
void star(void)
{
printf("*****");
}
*****C*****
main()
{
star();
printf("C");
star();
getch();
}
#include<stdio.h>
int f(int x)
{
return(x+1); 3
}
main()
{
printf("%d",f(2));
getche();
}
#include <stdio.h>
int cube(int x)
{
int ans;
ans = x * x * x;
Enter Number: 3
return(ans);
The cube of 3 is 27.
}
main()
{
int y;
printf("Enter a number : ");
scanf("%d",&y);
printf("The cube of %d is %d",y, cube(y));
getche();
}
#include "stdio.h"
int inc(int x)
{
int ans;
x++;
ans=x;
The value if y is 6
return(ans);
}
main()
{ int y=5;
2. Call by reference
• the address of an argument is copied into the parameter.
Inside the subroutine, the address is used to access the
actual argument used in the call.
• changes made to the parameter affect the variable used
to call the routine.
#include "stdio.h"
int inc(int x)
{
int ans;
x++;
ans=x; What type of
return(ans); passing data
}
main() in function is
{ int y=5; this?
printf("The value of y now is %d", inc(y));
getche();
}
#include <stdio.h>
void star(void)
{
printf("*****");
}
What type of
main() passing data
{ in function is
star(); this?
printf("C");
star();
getch();
}
End of lesson