(C++) How do I convert for statements to while statements? Everything runs smoot
ID: 3588804 • Letter: #
Question
(C++) How do I convert for statements to while statements?
Everything runs smoothly and like I need it to; however, the for statements need to be while statements.
This is my code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string experiment_name;
float total = 0.0, average,no[10];
int number_of_results = 0, i = 0;
//Request user input
cout << "Please enter the name of the experiment:?";
getline(cin, experiment_name);
cout << "How many results would you like to enter:?";
cin >> number_of_results;
//If statement: number of results must be greater than 0
if (number_of_results < 1) {
cout << "ERROR: the number of experiments must be greater than 1!";
}
for (int i = 0; i < number_of_results; i++) {
cout << "Please enter the result:" << endl;
cin >> no[i];
}
//Calculate the total
for (int i = 0; i < number_of_results; i++) {
total += no[i];
}
//Calculatethe average
average = total / number_of_results;
//Set precision
cout << setprecision(3) << fixed << showpoint;
//Display output
cout << endl;
cout << experiment_name << " Experiment Calculations: " << endl;
cout << " The total of the results is " << total << endl;
cout << " The average of the results is " << average << endl;
system("pause");
return 0;
}
Explanation / Answer
Given below is the fixed code. I have replaced mulitple spaces in the last couts to use which means a tab character. Hope the answer helped. If it did, please do rate the answer . Thank you.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string experiment_name;
float total = 0.0, average,no[10];
int number_of_results = 0, i = 0;
//Request user input
cout << "Please enter the name of the experiment:?";
getline(cin, experiment_name);
cout << "How many results would you like to enter:?";
cin >> number_of_results;
//If statement: number of results must be greater than 0
if (number_of_results < 1) {
cout << "ERROR: the number of experiments must be greater than 1!";
}
i = 0;
while(i < number_of_results) {
cout << "Please enter the result:" << endl;
cin >> no[i];
i++;
}
//Calculate the total
i = 0;
while(i < number_of_results){
total += no[i];
i++;
}
//Calculatethe average
average = total / number_of_results;
//Set precision
cout << setprecision(3) << fixed << showpoint;
//Display output
cout << endl;
cout << experiment_name << " Experiment Calculations: " << endl;
cout << " The total of the results is " << total << endl;
cout << " The average of the results is " << average << endl;
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.