Introduction
In this lab, you will learn how to write a basic program to add two numbers in C++ programming language. You will also learn about variable declaration, initialization, input/output operations, and basic mathematical operations in C++.
In this lab, you will learn how to write a basic program to add two numbers in C++ programming language. You will also learn about variable declaration, initialization, input/output operations, and basic mathematical operations in C++.
First, declare two variables a
and b
of integer type, to store the user input. Also, declare a variable sum
and initialize it with 0.
#include<iostream>
using namespace std;
int main()
{
//variable declaration
int a, b;
//variable declaration and initialization
int sum=0;
//...
}
Take input from the user using cin
and cout
statements. cout
is used to display the message to the user, cin
is used to accept the input from the user.
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to add 2 numbers ===== \n\n";
cout << "Enter the first Number : ";
cin >> a;
cout << "\nEnter the second Number : ";
cin >> b;
Add the two numbers a
and b
and store the result in the variable sum
.
//Adding the two numbers
sum = a + b;
Display the result to the user using cout
statement.
//displaying the final output (sum)
cout << "\nAddition of the two numbers is : " << sum;
Compile the program using the following command in terminal:
g++ ~/project/main.cpp -o main
Run the program using the following command in the terminal:
./main
After running the program, you should see the output in the terminal:
Welcome to Studytonight :-)
===== Program to add 2 numbers =====
Enter the first Number : 10
Enter the second Number : 20
Addition of the two numbers is : 30
In this lab, you learned how to write a basic C++ program to add two numbers. You also learned about variable declaration, initialization, user input/output, and basic mathematical operations in C++. You can now try out other mathematical operations or modify the program to suit your needs.
Here is the complete code for the main.cpp
file:
#include<iostream>
using namespace std;
int main()
{
//variable declaration
int a, b;
//variable declaration and initialization
int sum=0;
//take user input
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to add 2 numbers ===== \n\n";
cout << "Enter the first Number : ";
cin >> a;
cout << "\nEnter the second Number : ";
cin >> b;
//Adding the two numbers
sum = a + b;
//displaying the final output (sum)
cout << "\nAddition of the two numbers is : " << sum;
return 0;
}