C++ Program to Add Two Numbers

C++ProgrammingServer Side Programming

Addition is a basic arithmetic operation. The program to add two numbers performs addition of two numbers and prints their sum on screen.

A program that demonstrates addition of two numbers is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int num1=15 ,num2=10, sum;
   sum = num1 + num2;
   cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum;
   return 0;
}

Output

Sum of 15 and 10 is 25

In the above program the sum of two numbers i.e. 15 and 10 is stored in variable sum.

sum = num1 + num2;

After that it is displayed on screen using the cout object.

cout<<"Sum of "<<num1<<" and "<<num2<<" is "<<sum;

A program that uses an array to store two numbers and their sum as well is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a[3];
   a[0]=7;
   a[1]=5;
   a[2]=a[0] + a[1];
   cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
   return 0;
}

Output

Sum of 7 and 5 is 12

In the above program, the numbers to be added are stored in the 0 and 1 index of the array.

a[0]=7;
a[1]=5;

After that, the sum is stored in the 2 index of the array.

a[2]=a[0] + a[1];

The sum is displayed on screen using the cout object.

cout<<"Sum of "<<a[0]<<" and "<<a[1]<<" is "<<a[2];
raja
Published on 26-Sep-2018 12:45:07
Advertisements