Header Ads

FUNCTIONS

Functions



Functions in c?
A function is a block of code that has a name and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.
A function have three parts: -
1.       Function declaration: declaring of the function takes place at first then the later two stage are followed by this   Syntax for declaration:   voidfunction_name();                                                                                                                 
2.       Function call: after the declaration second is to call the function for its use in program
   Syntax for call:function_name( );

3.      Function Definition: the main thing is to define the functions that has been passed and returning the result to the line where function is call                                                          
Syntax for definition:          voidfunction_name ( )                                     
          


Function declaration and call is end with the semicolon 
Have a program to better understand the function in C:


#include<stdio.h>
#include<conio.h>
void messages();
main()
{
            messages();
            getch();
}
void messages()
{
            printf("FUNCTION\n");
}

                                                               
Output

FUNCTION_ 

How to calculate factorial of a number using function: -


#include<stdio.h>
#include<conio.h>
int factorial(int);
main()
{
            int num,res;
            printf("Enter the number: ");
            scanf("%d",&num);
            res=factorial(num);
            printf("Factorial of %d = %d",num,res);
            getch();
}
int factorial(int n)
{
            int i,fact=1;
            for(i=1;i<=n;i++)
            fact*=i;
            return fact;
}

 Output
Enter the number:  5

Factorial of 5 = 120_                 

No comments