You are here

Addition of two numbers in C

Addition of two numbers in C: This C language program performs the basic arithmetic operation of addition of two numbers and then prints their sum on the screen. For example, if a user will input two numbers as; '5', '6' then '11' (5 + 6) will be printed on the screen.

Addition program in C

#include<stdio.h>
 
int main()
{
   int a, b, c;
 
   printf("Enter two numbers to add\n");
   scanf("%d%d",&a,&b);
 
   c = a + b;
 
   printf("Sum of entered numbers = %d\n",c);
 
   return 0;
}

Output of C addition program:
Addition C program output.

Download Add numbers program executable.

In the expression (c = a + b) overflow may occur if the sum of a and b is larger than the maximum value which can be stored in the variable c. Similarly, you can write a C program which performs subtraction, multiplication, and division of two numbers.

Addition without using third variable

#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);
 
   return 0;
}

This method is not recommended because the original value of the variable 'a' is lost and if we require it further in the program, then we will not have it.

C program to add two numbers repeatedly

#include <stdio.h>
 
int main()
{
   int a, b, c;
   char ch;
 
   while (1) {
      printf("Inut two integers\n");
      scanf("%d%d", &a, &b);
      getchar();
 
      c = a + b;
 
      printf("(%d) + (%d) = (%d)\n", a, b, 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;
}

Output of program:

Inut two integers
2 6
(2) + (6) = (8)
Do you wish to add more numbers (y/n)
y
Inut two integers
2 -6
(2) + (-6) = (-4)
Do you wish to add more numbers (y/n)
y
Inut two integers
-5 3
(-5) + (3) = (-2)
Do you wish to add more numbers (y/n)
y
Inut two integers
-5 -6
(-5) + (-6) = (-11)
Do you wish to add more numbers (y/n)
n

C program for addition of two numbers using a function

We can calculate sum of two integers using a 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;
}

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