Addition of two numbers in C

Created with Sketch.

 

Addition of two numbers in C

The addition of two numbers in C language is performing the arithmetic operation of adding them and printing their sum on the screen. For example, if the input is 5, 6, the output will be 11.

Addition program in C

#include <stdio.h>

int main()
{
int x, y, z;

printf(“Enter two numbers to add\n);
scanf(“%d%d”, &x, &y);

z = x + y;

printf(“Sum of the numbers = %d\n, z);

return 0;
}

Output of the program:
Addition C program output.

 

In the expression (z = x + y), overflow may occur if the sum is greater than the maximum value that the variable z can store.

Similarly, we can write a program that performs subtraction, multiplication, and division of two numbers.

Addition without using third variable

#include<stdio.h>

int main()
{
int a = 1, b = 2;

/* Storing result of the addition in variable a */

a = a + b;

printf(“Sum of a and b = %d\n, a);

return 0;
}

Doing this isn’t recommended because the original value of the variable ‘a’ is lost; 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(“Input 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:

Input two integers
2 6
(2) + (6) = (8)
Do you wish to add more numbers (y/n)
y
Input two integers
2 6
(2) + (6) = (4)
Do you wish to add more numbers (y/n)
y
Input two integers
5 3
(5) + (3) = (2)
Do you wish to add more numbers (y/n)
y
Input 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);

int 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 are using long data type as it can handle large numbers.

To add numbers that don’t fit in in-built data types, use an array, a string, or other suitable data structure.

Leave a Reply

Your email address will not be published. Required fields are marked *