-2
#include<iostream>
#include<string>
using namespace std;

int main()
{
const int SIZE=7;
string tuition[SIZE];
 tuition[0]="Student ID";
 tuition[1]="total financial aid recieved";
 tuition[2]="amount paid for tuition";
 tuition[3]="amount paid for fees";
 tuition[4]="amount paid for books";
 tuition[5]="amount paid for housing";
 tuition[6]="amount paid for meal plan";
int costs[SIZE];


for(int index =0;index < SIZE;index++)
{
    cout<<"Please enter your "<<tuition[index]<<endl;
    cin>>costs[index];
    do{
        return 0;
    }while(costs[0] == 0);
    do{
        cout<<"Please re-enter the correct data.\n";
        cin>>costs[1];
    }while(costs[1] < 0);

}

return 0;

}

when the code is being run It executes the conditional code even when the conditional statement is false. I'm confused as to why that is happening.

Michael45
  • 19
  • 2

3 Answers3

2

A do-while will execute one or more times. The code is run before the conditional is checked.

Eljay
  • 4,648
  • 3
  • 16
  • 27
0

Because in the do-while loop, the code will execute the body of the condition at least once. Use just a while loop instead, that will fix your problem.

Yunus Kulyyev
  • 1,022
  • 15
  • 26
-1

Well it is petty simple, do while loop does this:

Do While(check if condition is true, after running code for the first time).

If you want the code to not run if condition is false you should just use the while loop (without the do part)

So here is how your code should look if you want to do exactly that:

for(int index =0;index < SIZE;index++)
{
cout<<"Please enter your            "<<tuition[index]<<endl;
cin>>costs[index];
While(costs[0]==0){
    return 0;
}
While(costs[1] < 0){
    cout<<"Please re-enter the correct        data.\n";
    cin>>costs[1];
  }

return 0;

}

Now why this happens?

Well if you understand the 2 different condition this becomes quite easy.

We have:

  1. While
  2. Do while

**While first check if the condition is true.

Do while first run the code and after that checks if true(it will always run your code at least once).**

That is why ur code always run, because that is what do while does.

As suggested by tas:

Is far better to use if in this case, why? Well in this case you are already looping using the for, so if you change the while with and if, else if statement you will have the same results.

Here you can learn how to use the if statement:

https://www.programiz.com/cpp-programming/if-else

Extra, here you can find how to use while:

https://www.tutorialspoint.com/cplusplus/cpp_while_loop.htm

Yorki Bonilla
  • 535
  • 2
  • 9
  • This isn't a good example. a) you spelt `while` wrong, and b) why would you write `while(costs[0] == 0) return 0;`. It'd make far more sense as a simple `if` – Tas Nov 20 '17 at 00:33
  • Well not saying you are wrong, but i wanted to answer using the same user example. Thanks for the advice since is true i will add it as a suggestion in the end – Yorki Bonilla Nov 20 '17 at 00:40