Loop the whole program
Oct 26, 2020 at 6:20am UTC
I want to loop the entire program with a "Do you wish to loop through the code again? [Y/N]" type of code. I don't know how to do the sequence I keep getting two loops before it pops out. So I've put a fresh code with no looping the whole program code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include<iostream>
using namespace std;
int main(){
double number = 0, sum = 0, loop = 0, total = 0;
float average = 0;
double counter = 1;
int minimum = INT_MAX, maximum = INT_MIN;
int minimumIndex = 0, maximumIndex = 0;
cout<<"Enter # of times to loop: " ;
cin>>loop;
total = loop;
while (loop > 0){
cout<<"Enter #" << counter<<": " ;
cin>>number;
if (number<minimum){
minimum=number;
minimumIndex = counter;
}
if (number > maximum){
maximum = number;
maximumIndex= counter;
}
sum = sum + number;
counter++;
loop--;
}
average=sum/total;
cout<<"Highest #: " <<maximum<<endl;
cout<<"Lowest #: " <<minimum<<endl;
cout<<"Average #: " << average<<endl;
return 0;
}
Oct 26, 2020 at 6:47am UTC
Testing will show this works but replying other than y or n needs more thinking.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include<iostream>
using namespace std;
int main()
{
double number = 0, sum = 0;
float average = 0;
double counter = 0;
int minimum = INT_MAX, maximum = INT_MIN;
int minimumIndex = 0, maximumIndex = 0;
char reply{'?' };
while (cout << "Continue <y/n>? " && cin >> reply && tolower(reply) == 'y' )
{
cin.ignore(1000, '\n' ); // GETS RID OF EXCESS INPUT
cout<<"Enter #" << counter + 1 <<": " ;
cin >> number;
if (number<minimum)
{
minimum=number;
minimumIndex = counter;
}
if (number > maximum)
{
maximum = number;
maximumIndex= counter;
}
sum += number;
counter++;
average = sum/counter;
}
cout << "Highest #: " << maximum << endl;
cout << "Lowest #: " << minimum << endl;
cout << "Average #: " << average << endl << endl;
return 0;
}
Oct 26, 2020 at 6:48am UTC
BTW you need to properly indent your coding and make good use of whitespace.
Topic archived. No new replies allowed.