How to rewrite this code using For Loop format include incl
How to rewrite this code using \"For Loop\" format?
===========================================================
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
int main()
{
//declaring vars
double sum,
Value,
Max,
Min,
BestValue,
Uncertainty;
int count = 0;
char loop_test;
do // input
{ cout<<\"Type in a lab data:\";
cin>>Value; //cout<<\"\ The lab result of\"<<Value<<\"is\"<<endl;
if ( count == 0)
{
Max = Value;
Min = Value;
}
if (Value < Min)
Min = Value;
if (Value > Max)
Max = Value;
sum += Value;
count ++;
cout<<\"\ Another? Type Y for yes\";
cin>>loop_test;
}while(loop_test==\'y\'||loop_test==\'Y\');
cout<<endl;
// output
Uncertainty = (Max - Min)/count;
BestValue = sum / count;
cout << fixed;
cout.precision(2);
cout << \"\ max\" << Max;
cout <<\"\ min \" << Min;
cout << \"\ count \" << count << endl;
cout<<\"Physics 4AL Laboratory Results:\";
cout<<\"Distance = \"<<BestValue<<\" +&- \"<<Uncertainty<< endl;
return 0;
}
Solution
Answer:
int count; char loop_test = \'y\';
for (count=0; loop_test==\'y\' || loop_test==\'Y\'; count++)
{
bla bla bla....
}
In place of bla bla bla..., you just type exactly same thing as inside the do while loop
Except, do not write the count++; statement. Everything before and after should be same.
The for loop structure is :
for (initialize; condition; update)
{
bla bla bla....
}
The do while structure is :
initialize;
do
{
bla bla bla..... update;
}
while (condition);
In your example, condition is loop_test==\'y\' || loop_test ==\'Y\'
Initialize is count = 0 and update is count++
So the code is :
#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
int main()
{
//declaring vars double sum, Value, Max, Min, BestValue, Uncertainty; int count;
char loop_test = \'y\';
for (count=0; loop_test==\'y\' || loop_test==\'Y\';coint++)
// input { cout<<\"Type in a lab data:\"; cin>>Value;
//cout<<\"\ The lab result of\"<<Value<<\"is\"<<endl;
if ( count == 0) { Max = Value; Min = Value;
}
if (Value < Min) Min = Value;
if (Value > Max)
Max = Value;
sum += Value;
cout<<\"\ Another? Type Y for yes\";
cin>>loop_test;
}
cout<<endl; // output Uncertainty = (Max - Min)/count;
BestValue = sum / count;
cout << fixed; cout.precision(2);
cout << \"\ max\" << Max;
cout <<\"\ min \" << Min;
cout << \"\ count \" << count << endl;
cout<<\"Physics 4AL Laboratory Results:\";
cout<<\"Distance = \"<<BestValue<<\" +&- \"<<Uncertainty<< endl;
return 0;
}



