Adding two numbers in C++ programming is a very basic beginner-level question and one can easily write the code by following the below instructions.
Instruction:
- Declare two integer-type variables num1 and num2.
- Take two integer-type input variables from the user which we are going to store in num1 and num2.
- Declare another integer-type variable sum and initialize the variable with 0.
- Add two variables num1 and num2 and store the answer in the sum variable.
- Print the value present in the sum variable.
C++ Code to Add Two Integer Type Numbers.
#include<iostream> using namespace std; int main(){ int num1, num2; cout<<"Enter the first number: "; cin>>num1; cout<<"\nEnter the second number: "; cin>>num2; int sum = 0; sum = num1 + num2; //Print sum cout<<"Sum of two numbers: "<<sum; return 0; }
Enter the first number: 10
Enter the second number: 5
Sum of two numbers: 15
Note: For this example, we are using an integer-type variable but you can change your change the data type of your variables based on the requirement like you can use float-type variables to add decimal values.(alert-success)
C++ Code to Add Two Float Type Numbers.
#include<iostream> using namespace std; int main(){ float num1, num2; cout<<"Enter the first number: "; cin>>num1; cout<<"\nEnter the second number: "; cin>>num2; float sum = 0; sum = num1 + num2; //Print sum cout<<"Sum of two numbers: "<<sum; return 0; }
Output:
Enter the first number: 3.4
Enter the second number: 5.3
Sum of two numbers: 8.7
I hope you found this post useful, please write your comments below if you have any questions or feedback related to this topic.
No comments:
Post a Comment