Skip to main content

Add two integers

In the following program, we will ask the user to enter two integer inputs. The programs will calculate and print the sum of two numbers.

src/c/basics/01-add-two-integers.c
#include <stdio.h>

int main()
{
int input1, input2, sum;

printf("Enter input 1: ");
scanf("%d", &input1);

printf("Enter input 2: ");
scanf("%d", &input2);

sum = input1 + input2;

printf("%d + %d = %d\n", input1, input2, sum);

return 0;
}
danger
int a = 123456789;
long long b = a * a; // this is wrong, a * a will result in int type
long long c = (long long) a * a; // or change the type of a to long long
caution

It is risky to compare floating point numbers with == due to precision errors. Better approach is to check the difference is less than a small number:

if (abs(a - b) < 1e-9)
{
// a and b are equal
}