facebook like button

23 May, 2011

program 46: addition with user defined function

The need: 
      This is program is just to add two given numbers and print their on the standard output using User defined function.

The code: 
--------------------------------------------
#include<stdio.h>
int getsum(int a,int b);       //declaration of function
int main()
{
    int i,j,k;
    printf("The program to add two numbers.\n");
    printf("Enter first number.\n");
    scanf("%d",&i);
    printf("Enter second number.\n");
    scanf("%d",&j);
    k=getsum(i,j);
    printf("Sum = %d\n",k);
}
int getsum(int a,int b)       //definition of function
{
  int temp;
  temp=a+b;
  return temp;
}
--------------------------------------------

The approach: 
First of all copy, paste, compile and run the program. After that try to understand the code and also try to compare with code of program3 of this blog. In this program I have used a user UDF getsum() which takes 2 integers as arguments, adds them and stores in a temporary variable temp and returns the value of temp (that is the sum). This much is clearly visible in the definition of the UDF getsum(). You know that everything should be declared before it is used. In the same way a UDF is declared before it is called. Thats why it has been declared above main().

Remarks:
There are 2 noticeable points. 
1. The output of both the programs is same.
2. The only difference is in the code (that is in this I have used UDF.)

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply