Thursday, July 14, 2011

Functions: TYPES OF FUNCTIONS

TYPES OF FUNCTIONS

1.  Function Without return_type and without parameters:

#include<stdio.h>
#include<conio.h>
 
void add()
{
    int x, y;
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
 
    printf("Sum of x and y is %d", x+y);
}
main()
{
    add();
    getch();
}
void keyword is used since no return type is needed.

2.  Function Without return_type and with parameters:

#include<stdio.h>
#include<conio.h>
 
void add(int x, int y)
{
    printf("Sum of x and y is %d", x+y);
}
main()
{
    int x, y;
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
   
    add(x,y);
 
    getch();
}
Above example is of without return type so void keyword is used. Variable x and y is used as parameter in function add() whose value is supplied from  main() function.

3.  Function With return_type and without parameters

#include<stdio.h>
#include<conio.h>
 
int add()
{
    int x, y;
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
 
    return(x+y);
}
main()
{
    int sum;   
    sum=add();
 
    printf("Sum of x and y is %d", sum);
    getch();
}
In add() function int return type is used and at last line of add() function return keyword is used to return added value of x and y to main function to display.

4.  Function With return_type and with parameters

#include<stdio.h>
#include<conio.h>
 
int add(int x, int y)
{
    return(x+y);
}
main()
{
    int x, y, z;     
   
    printf("Enter value for x and y");
    scanf("%d %d", &x, &y);
 
    z=add(x, y);
   
    printf("Sum of x and y is %d", z);
    printf("Sum of x and z is %d", add(x,z));
 
    getch();
}
main() function calls add() function by passing two value. add() function those two value as parameter and performs addition and returns the added value to main() function so that main() function can display the added value.


Example 1: Write a program to find the factorial of N number using function.
#include <stdio.h>
#include<conio.h>
 
long int fact(int n);       //prototype
 
main()
{
    long int f;
    int x;
 
    printf("enter the value for x:")
    scanf("%d", &x);
 
    f = fact(x);
 
    printf(" Factorial of x is %ld", f);
    getch();
}
 
long int fact(int n)
{
    long int f=1;
    int i;
 
    for(i=1; i<=n; i++)
          f= f*i;
   
    return(f);
}
Example 2: Write a program to find the length of string using function.
#include<stdio.h>
#include<conio.h>
 
int slen(char str[]);
 
main()
{
    int len;
    char str[25];
 
    printf("Enter any string as input");
    scanf("%s", str);
 
    len = slen(str);
 
    printf("Length of string is %d", len);
    getch();   
}
 
int slen(int str[])
{
    int l;
   
    for(l=0; str[l] != '\0', l++);
 
    return(l);
}
 

0 comments:

Post a Comment