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.
- C
- C++
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;
}
src/cpp/basics/01-add-two-integers.cpp
#include <iostream>
using namespace std;
// above declaration exposes all the methods described in the std namespace
// so that we can use cout instead of std::cout. Beware that in large
// applications there could be naming conflict among various imported headers.
// We can either use the convention std::cout or declare only the methods we
// need:
// using std::cout;
int main()
{
int input1, input2, sum;
cout << "Enter input 1: ";
cin >> input1;
cout << "Enter input 2: ";
cin >> input2;
sum = input1 + input2;
cout << input1 << " + " << input2 << " = " << sum << endl;
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
}