Adding two numbers is one of the fundamental operations in programming and serves as a great introduction to the syntax and arithmetic operations of a language like C++. Simple yet essential, this operation involves using basic mathematical operators to manipulate data, which can be represented in various data types.
In this article, you will learn how to create a C++ program to add two integers and then extend this to handle floating-point numbers. Discover how to prompt user input, perform the addition, and display the results.
Start by including the necessary headers. In this case, include <iostream> for input and output operations.
Declare two integer variables to store the numbers to be added.
Prompt the user to enter two integer values.
Perform the addition and store the result.
Output the result to the console.
#include <iostream>
using namespace std;
int main() {
int num1, num2, sum;
cout << "Enter two integers: ";
cin >> num1 >> num2;
sum = num1 + num2;
cout << "Sum = " << sum << endl;
return 0;
}
In this code, cin
is used to capture user input, and cout
is used to print the output. The integers num1
and num2
are added, and their sum is stored in the variable sum
which is then printed.
Begin by including the <iostream> header for handling input and output.
Declare two float variables to hold the numbers for addition.
Prompt the user for two floating-point numbers.
Execute the addition and store the result in a float variable.
Display the result.
#include <iostream>
using namespace std;
int main() {
float num1, num2, sum;
cout << "Enter two floating-point numbers: ";
cin >> num1 >> num2;
sum = num1 + num2;
cout << "Sum = " << sum << endl;
return 0;
}
This snippet functions similarly to the integer example but uses float
for decimal numbers. The cin
object reads the floating-point numbers entered by the user, and cout
prints the sum.
Adding numbers in C++ is a straightforward process that requires only basic programming skills. Whether dealing with integers or floating-point numbers, the approach remains similar: prompt for user input, perform arithmetic operations, and print the output. By mastering simple operations like this, you build a strong foundation for tackling more complex programming tasks in C++. Use these examples to effectively manage user input and arithmetic in your future C++ projects.