Thursday, 3 April 2014

How to Add Two Numbers in c Language Using Different Methods?

This c language program is used to add two numbers. It uses the basis arithmetic operation for adding two numbers and then prints the sum on output screen. It is as simple as your First C Language Program.

C Language Program to Enter 2 numbers by entering values

#include<stdio.h>
main()
{
   int a, b, c;   //Declaration of variables
   printf("Enter two numbers to add\n");
   scanf("%d%d",&a,&b);

   c = a + b; 
//Addition of variable
printf("Sum of entered numbers = %d\n",c);
}

Below is the output of the above program.





Program to ADD 2 numbers by Declaring values

#include<stdio.h>
main()
{
   int a = 1, b = 2;

   /* Storing result of addition in variable a */

   a = a + b;
   printf("Sum of a and b = %d\n", a);
}






C program to add two numbers repeatedly


#include<stdio.h>

main()
{
   int a, b, c;
   char ch;

   while(1)
   {
      printf("Enter values of a and b\n");
      scanf("%d%d",&a,&b);

      c = a + b;

      printf("a + b = %d\n", c);

      printf("Do you wish to add more numbers(y/n)\n");
      scanf(" %c",&ch);

      if ( ch == 'y' || ch == 'Y' )
         continue;
      else
        break;
   }

   return 0;
}


Adding numbers in c using function


#include<stdio.h>
 long addition(long, long);
 main()
{
   long first, second, sum;
   scanf("%ld%ld", &first, &second);
   sum = addition(first, second);
   printf("%ld\n", sum);
   return 0;
}
long addition(long a, long b)
{
   long result;
   result = a + b;
   return result;
}



I have used long data type as it can handle large numbers, if you want to add still larger numbers which doesn't fit in long range then use array, string or other data structure.

No comments:

Post a Comment