C++ Program to Add Two Numbers

by | Jan 2, 2023 | C++ Programs

Introduction

This program can be in two ways. One way is declaring and assigning the values to the variables and then calculating their sum. The other method is to declare the variables first and then the user is asked to enter two integers. Then, the sum operation is applied to both values.

The final value of the sum so obtained is stored in another variable and the result will be displayed on the screen.

To understand this program, the learners should know about the following C programming topics:

1. Data Types in C

2. Variables, literals, and constants

3. C Programming operators

The numbers entered by the user can be of any type, either int or float, or both.

Program

#include<iostream>
using namespace std;
int main()
{
float x,y;
cout<<"Enter two values to calculate their sum:\n";
cin>>x>>y;


float sum=x+y; // sum of x and y assigned to sum variable.
cout<<"Sum= "<<sum<<endl;
return 0;
}

 

Output

Explanation

float x,y;

‘x’ and ‘y’ are two variables declared with ‘float’ type.

cout<<“Enter two values to calculate their sum:\n”;

A message is printed on the screen using cout statement for the user to enter two values and these two values get stored in ‘x’ and ‘y’ using cin stateemnt.

float sum=x+y;

‘sum’ is a variable of ‘float’ type declared to store the value obtained by adding ‘x’ and ‘y’.

Finally, the value of ‘sum’ is displayed on the screen.

 

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.