hi. I have written this code for my homework in FOR loop. The programs runs but i just want to make sure i used it correctly. Any suggestions? i also need to write the same in do-while and i am a little confused about it. how can i do it?
#include <iostream>
using namespace std;
int main()//DEFINE THE MAIN FUNCTION
{
//DECLARE THE REQUIRED VARIABLES
int number ,max ,min ;
cout << " " " Enter -99 to end the series ." << endl;
cout << " " " \nEnter a number in a series : " << endl;//ASK THE USER TO ENTER THE VALUES
cin >>number;
min = max = number ;//SET THE INITIAL VALUES
for (int i = 0; number!=-99; i++)//BEGIN THE LOOP
{
if(number > max)//SET THE MAX
max = number;
if (number < min)//SET THE MIN
min = number ;
//ASK THE USER TO ENTER THE VALUES
cout << " " " Enter a number in the series : " <<endl;
cin >>number;
}
//DISPLAY THE LARGEST AND SMALLEST VALUE.
cout << "\nlargest number is : " << max << endl;
cout << "smallest number is : " <<min << endl;
You simply test at the end of the loop whether you want to run the next loop ... with the same condition as currently in the middle of your for(;;) statement.
do{
contents of loop
} while( condition );
Your do statement replaces the current for statement.
Your while condition is the same as that currently in the middle of your for statement.
With regards to your current code, you don't use variable i (at the moment), so those bits of the for loop could be left blank (unless you wanted to count inputs).
I think your commenting is a bit over the top. However, that's a personal opinion. Sometimes it's a left-over of students considering their program flow before starting coding, which could only be complimented.