Friday, July 31, 2009

Easy Basic C++ Programming Help?

Doing a while loop that will allow the user to continue running the program until they enter 'x' to exit the program. It keeps giving me previous results added onto when you run it again. How do u make the program start over the results the 2nd time around?





int counter = 0;


int oddcount = 0;


int num1;


int scores;


char letter;


int highestscore = 0;








while (letter != 'x')





{


cout%26lt;%26lt;"How many scores are you entering?"%26lt;%26lt;endl;


cin%26gt;%26gt;num1;








for (int counter=0; counter%26lt;num1;counter++)


{





cout%26lt;%26lt;"Enter an integer: "; cin%26gt;%26gt;scores;





cout%26lt;%26lt;endl;








oddcount += (( scores % 2)!= 0);





if ( scores %26gt; highestscore )





highestscore = scores;


}


cout%26lt;%26lt;"You entered "%26lt;%26lt;oddcount%26lt;%26lt;" odd numbers."%26lt;%26lt;endl;


cout%26lt;%26lt;"The highest # is "%26lt;%26lt;highestscore%26lt;%26lt;endl;


cout%26lt;%26lt;"Finish...press 'x' to exit program. any other key to run again."%26lt;%26lt;endl;


cin%26gt;%26gt;letter;


}

Easy Basic C++ Programming Help?
Do this when you enter the while loop:


oddcount = highestscore = 0;





By the way, you're using the variable 'letter' before you set it. This is generally a bad idea. Always set data before you use it. You may want to change your loop to a do { } while, so letter will only be checked after the cin.
Reply:I've been tracking your problem as you continually post the same question. First off, the person on the previous question is wrong. Unless I'm mistaken, you're trying to count how many odd numbers have been entered? The += operator basically is doing this: oddcount = oddcount + scores%2. In the code, that's not even syntaxually correct. It should actually be this:





(keep in mind, this is still in the "for" loop)





if ((scores % 2) != 0)


{


oddcount++;


{





%26lt;rest of code here%26gt;





Also, you should initialize your INSIDE the while loop. Otherwise, if the person doesn't press x, the values stored in the variables are still the same (because only the stuff inside the while loop is run again). Put all your initializations of your variables as the first thing in the while loop. Because once the loop starts over, it'll reinitialize the variables again and clear all previous data (meaning you won't get the same answers). Also, initialize num1 and scores to 0 so that they reset themselves too.


No comments:

Post a Comment