SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
C++ Basics
Exercise:
Programming Projects
Question:16 | ISBN:9780321531346 | Edition: 7

Question

The following is a short program that computes the volume of a sphere given the radius. It will compile and run, but it does not adhere to the
program style recommended in Section 2.5. Rewrite the program using the style described in the chapter for indentation, adding comments, and appropriately naming constants.

#include <iostream>
using namespace std;
int main() {
double radius, vm;
cout << "Enter radius of a sphere." << endl; cin >> radius;
vm = (4.0 / 3.0) * 3.1415 * radius * radius * radius;
cout << " The volume is " << vm << endl;
return 0;
}

 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

The following  points are modified in given program.

  • The variable name "vm" changed to "volume" for suitable naming conversion for easy understanding.
  • Adding naming constants "PI, NUMERATOR, DENOMINATOR " with initialized given values in the code.
  • Code indentation is not followed in given code. So, i provided the code indentation in below program clearly.

The following modified program code contains code indentation, adding comments, and appropriately naming constants:

Modified Program Code:

//Import file names
#include <iostream>
using namespace std;
//Program start here
int main()
{
    //Double data type variables declaration
    double radius, volume;
    
    //Constant double data type variables declaration
    const double PI = 3.1415; 
    const double NUMERATOR = 4.0;
    const double DENOMINATOR = 3.0;
    
    //Read radius of a sphere from the user
    cout<<" \n Enter radius of a sphere: ";
    cin>>radius;
    
    //Computes the volume of a sphere 
    volume = (NUMERATOR/DENOMINATOR)* PI * radius * radius * radius;
    
    //Display output
    cout<<" The volume of a sphere is " << volume << endl;
}//End program

Output of the program code:

Enter radius of a sphere: 5.5
The volume of a sphere is 696.889

 

0 0

Discussions

Post the discussion to improve the above solution.