954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Loop

How do i get the loop to go back and prompt using for a valid number?

<pre><code>#include&lt;iostream&gt;
#include&lt;conio.h&gt;
#include&lt;iomanip&gt;
#include&lt;string&gt;

using namespace std;

int main ()
{    
    string firstName;
    string lastName; 
    int score1, score2, score3, score4, score5;
    float totalpoints;
    
    cout&lt;&lt;fixed&lt;&lt;showpoint&lt;&lt;setprecision(2);
    
    cout&lt;&lt;&quot;Please enter the student first and last name: &quot;;
    cin&gt;&gt;firstName&gt;&gt;lastName;
    cout&lt;&lt; endl; 

cout&lt;&lt;&quot;Please enter the student's FIVE program scores&quot;&lt;&lt;endl;
    cout&lt;&lt;&quot;Each score must be an integer between 0 &amp; 100:&quot;&lt;&lt;endl;
    cout&lt;&lt;endl;
    
    
    
    cout&lt;&lt;&quot;Please enter the first program score: &quot;;
    cin&gt;&gt;score1;
    
    if (score1&gt;100) 
    {
       cout&lt;&lt;&quot;Invalid Number&quot;;
       }
    else if (score1&lt;0)
    {
         cout&lt;&lt;&quot;Invalid Number&quot;;
         } 
    cout&lt;&lt;endl&lt;&lt;&quot;Press any key to continue.&quot;&lt;&lt;endl;
    getch();
    
 return 0;   
}</code></pre>
ronthedon
Newbie Poster
4 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

Well, for starters, you need to actually create a loop. You don't have any loop structure in this code. Just remember, everything that you want to execute multiple times needs to be within the statement block controlled by the loop.

void someFunction() {

  //any code here will only run once

  while (someCondition == true) {
    //any code here will repeat as long as someCondition == true
  }                                           //end while

  //any code here will only run once

}                                             //end main()

NOTE: There are also do-while and for loops. This example only shows the standard while loop. More information.

Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
 

you can do

while(score1>100 || score1<0) // will loop until proper number entered
{
cout<<"invalid number,enter again\n";
cin>>score1;
}
ntrncx
Junior Poster
116 posts since Jan 2011
Reputation Points: 29
Solved Threads: 7
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: