I would like to know how can I improve my code and make it simple. #include <ios
ID: 3691509 • Letter: I
Question
I would like to know how can I improve my code and make it simple.
#include <iostream>
using namespace std;
bool valid(int start, int end, int step);
void input(int& start, int& end, int& step); //by reference
int sum(int start, int end, int step);
int main() {
int start, end, step;
char choice;
cout << "Functions make programs easier to write and understand." << endl <<
"This program computes the sum of a range by using functions to do the work." << endl;
do {
input(start, end, step); //input values
if (valid(start, end, step)) {
cout << "The sum from " << start << " to " << end << " with step " << step << " is " << sum(start, end, step) << endl; //output sum
}
cout << "Compute another sum? [Y/N] ";
cin >> choice;
if (choice == 'N' || choice == 'n') {
cout << "Bye, bye" << endl;
break;
}
} while (choice == 'Y' || choice == 'y');
}
bool valid(int start, int end, int step) //validity
{
if (step <= 0) {
cout << "Step value should be greater than 0." << endl;
return false;
}
if(start > end) {
cout << "Start value should be smaller or equal to end value." << endl;
return false;
}
return true;
}
void input(int& start, int& end, int& step) //input data
{
cout << "Enter start of range: ";
cin >> start;
cout << "Enter end of range: ";
cin >> end;
cout << "Enter increment step: ";
cin >> step;
}
int sum(int start, int end, int step) //calculate sum
{
int s = 0;
while (start <= end) {
s += start;
start += step;
}
return s;
}
I would like to know how can I improve my code:
Explanation / Answer
I have though about a lot. There is nothing else you can improve. It is perfect.