Write a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The user should be asked if he or she wishes to per- form the operation again. If so, the loop should repeat; otherwise it should terminate.

Respuesta :

The do-while loop for the given problem is shown below.  

do  

{  

  // user asked to enter two numbers  

  cout<<"Enter two numbers to be added."<<endl;  

  cin>>num1;  

  cin>>num2;  

  sum = num1 + num2;  

 

  // sum of the numbers is displayed  

  cout<<"Sum of the two numbers is "<<sum<<endl;  

  // user asked whether to perform the operation again  

  cout<<"Do you wish to continue (y/n) ?"<<endl;  

   cin>>choice;  

}while(choice != 'n');  

The variables to hold the two numbers and their sum are declared as float so that the program should work well for both integers and floating numbers.

float num1, num2, sum;

The char variable is taken since it holds only a single-character input from the user, 'y' or 'n'.

char choice;

The whole program is given below.

#include <iostream>

using namespace std;

int main() {

float num1, num2, sum;

char choice;  

do  

{  

  // user asked to enter two numbers  

  cout<<"Enter two numbers to be added."<<endl;  

  cin>>num1;  

  cin>>num2;  

  sum = num1 + num2;  

  // sum of the numbers is displayed  

  cout<<"Sum of the two numbers is "<<sum<<endl;  

  // user asked whether to perform the operation again  

  cout<<"Do you wish to continue (y/n) ?"<<endl;  

  cin>>choice;  

}while(choice != 'n');

cout<<"Quitting..."<<endl;

}

ACCESS MORE