Pages

This blog is under construction

Friday, December 21, 2018

Types of User-defined Functions in c programming.


1) Function with no arguments and no return value
   
Example:

#include <stdio.h>

void main()
{
          sum();
 }

  void sum()     //no arguments and no return value
  {
      int a,b,c;
      printf("Enter two numbers");
      scanf("%d%d",&a,&b); 
      c=a+b;
      printf("Sum of both numbers is %d",c);  
    
  }

Enter two numbers 4                                                                                                                                   
5                                                                                                                                                    
Sum of both numbers is  9


2) Function with no arguments and a return value

#include <stdio.h>
void main()
{  
   int c= sum();
   printf("Sum of both numbers is %d",c); 
}

int sum()  //no arguments and a return value
{
      int a,b,c;
      printf("Enter two numbers");
      scanf("%d%d",&a,&b); 
      c=a+b;
      return c;    
}

Enter two numbers 5                                                                                                                                   
7                                                                                                                                                    
Sum of both numbers is 12 

3)Function with arguments and no return value

#include <stdio.h>

void main()
{
    int a,b;
     printf("Enter two numbers");
     scanf("%d%d",&a,&b);  
     sum(a,b);
 }

void sum(int a, int b)  //arguments and no return value
{
       int c;
        c=a+b;
       printf("Sum of both numbers is %d",c);    
    
}

Enter two numbers 6                                                                                                                                   
5                                                                                                                                                    
Sum of both numbers is 11

4) Function with arguments and a return value
      (This is most appropriate function type) 
#include <stdio.h>

void main()
{
     int a,b,c;
     printf("Enter two numbers");
     scanf("%d%d",&a,&b);  
     c=sum(a,b);
     printf("Sum of both numbers is %d",c);
}

int sum(int a, int b) //arguments and a return value
{    
    return a+b;
    
}

Enter two numbers 5                                                                                                                                   
5                                                                                                                                                    
Sum of both numbers is 10 

No comments:

Post a Comment