0

Ive encountered an infinite loop while writing code for the water assignment of pset1 enter image description here

Yeah, I realise Ive made a complete mess. Now Im lost as to how I should proceed further. Also I did the same problem using if else structure and it worked (confirmed by check50). However in the walkthrough video for water a do while structure is mentioned for this problem, so do i need to have a do while structure or can I submit the if else one if im not able to do it using the former?

So from the suggestions commented below i tried writing a new code but im getting errors: enter image description here enter image description here

I dont understand why its saying that i havent initialised the variable a. Have i placed it wrong?

2

What we want is that the user input, with the get_int function is inside the DO-WHILE loop, we do not want to print the number of bottles inside that loop because if i is positive the end condition of loop (i> 0) does not Is never fulfilled, and we have an infinite loop. The solution is to ask the user a positive number, that is to say we keep asking for a number while it is negative:(eliminate IF condition)

do
{
   int i = get_int()
}
while(i < 0)

And only then print the number of bottles EDIT:

Maybe my answer is not clear, Inside main we must declare int a = 0; We can initialize to zero so that the compiler is happy, This variable is visible inside the DO-WHILE loop, so we must not re-define it, ie inside the loop we must not do again int a, only a = get_int(); If we declare again int a, within the loop we actually have a new variable, different from the previous one, so the first one appears as shaded and unused

5
  • Thanks, I tried to modify the code but have encountered errors. Ive edited the question to attach the screenshot, could you have a look at it?
    – Vida
    Apr 23 '17 at 12:10
  • a as global variable do not can be redefine again simply you must to do a = get_int()
    – MARS
    Apr 23 '17 at 13:25
  • Sorry do you mean to say i should exclude "int a;"? because on doing that i get an error saying " use of undeclared identified variable 'a' ".
    – Vida
    Apr 23 '17 at 14:34
  • you can read my edit
    – MARS
    Apr 23 '17 at 15:05
  • YES It finally worked! Thanks for the detailed explanation @MARS, very helpful
    – Vida
    Apr 24 '17 at 0:40
0

Remember your not changing the value of 'i' ..try a different way to stop th loop 😅Vote if u understood 🤘🏻

0

There is no need for using a loop in this question. Just type the exact code, this time without using a loop. The get_int function will give retry message if the entered data is not an integer. I hope i made it clear.

1
  • You should keep in mind that per spec we assume that values are always positive, but it is not bad for students to want to go a little further
    – MARS
    Apr 23 '17 at 18:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .