4

I'm trying to learn Java, I studied Pascal in high school and it has the repeat until..; instruction.

I want to solve an exercise where I'm supposed to keep entering numbers until the penultimate + antepenultimate numbers equal the last number I entered.(a[i-2]+a[i-1] = a[i]); I'm doing it without arrays but that doesn't really matter.

In Pascal it would be easy because repeat until is more easier to use For ex it would be

repeat  
...   
until ((a[i-2]+a[i-1] = a[i]) and (n=3)); 

n is the number of values I entered

I can't figure out how to introduce it in Java, so far I did this but it doesn't work if I enter 2 2 4. It should stop but it keeps asking for numbers

    int pen = 0, ant = 0, s = 0, n = 1;
    int ult = input.nextInt();
    s = s + ult;
    do {
        do {
            ant = pen;
            pen = ult;
            ult = input.nextInt();
            n++;
            s = s + ult;
        } while (ant + pen != ult);
        System.out.println(n);
    } while ((n == 3) || (n < 4));

ult is the last number I enter, s is the sum of the numbers entered.

Could anyone tell me how to set the conditions so it will stop if I enter the values 2 2 4?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 4
    You should do some debugging. – Oliver Charlesworth Aug 10 '16 at 19:03
  • 5
    Why are you testing if n equals three or n is less than four in the outer `do-while` loop? If `n==3` is true then `n<4` must also be true. – Susannah Potts Aug 10 '16 at 19:03
  • 2
    `do {} while ()` is not often used in Java. You'll probably have more luck with `while () {}`, perhaps using a `break` to exit the loop. – OrangeDog Aug 10 '16 at 19:04
  • 3
    In Java you pretty much do it exactly the same way as Pascal. Your explanation in the text is correct, with only one little niggle. – markspace Aug 10 '16 at 19:06
  • 1
    First of all, remove "(n==3) || " from the last condition. Second, keep in mind that do-while is executed at least once...this is the main difference with while. If you want to stop the execution place an "if" condition in one of the "do-whiles" along with a return command. If you want to continue execution just put a "break" instead of "return"... Every "break" breaks only the loop that is placed and program continues, – P. Str Aug 10 '16 at 19:13

5 Answers5

4

A Do-While loop runs the code in the loop first. It evaluates the logic last, and then if it's true it repeats the code inside the loop, and so on until the logic is false.

The way to solve tricky problems like this is to get out a sheet of paper and record what each variable does. Step through each line like a debugger and record what's being stored in each variable as the program progresses.

It's the best way to do it. You'll find that you'll gain a deeper understanding of how your programs are working.

Slothario
  • 2,830
  • 3
  • 31
  • 47
  • 1
    *"The way to solve tricky problems like this is to get out a sheet of paper ..." - or use a debugger. : ) – Jonny Henly Aug 10 '16 at 19:06
  • 4
    If you're learning, I find the sheet of paper is better. We did this in college, the professor called it "hand execution." It's an excellent learning tool. – markspace Aug 10 '16 at 19:07
1

Java isn't any more magic than Pascal, the issue might be you've had a long break from programming :). Anyway, its been a while since I wrote anything in Java, but the issue I could spot in your code is just that n equals three after you've entered three ints, and so the outer loop continues.

int pen = 0, ant = 0, ult = 0, n = 0;

do {
    ant = pen;
    pen = ult;
    ult = input.nextInt();
} while (++n < 3 || ant + pen != ult );

assert n >= 3;
assert ant + pen == ult;

Note that ever since Pascal everything has been zero indexed instead of one indexed.

1

Pascal uses the form:

repeat
  doStuff();
until (boleanValue);

Java is basically the same, except for one important point:

do 
  doStuff();
while (~boleanValue);

The important difference is that "~" before booleanValue. The Pascal repeat ... until keeps running until the boolean evaluates to true. In Java the do ... while keeps running until the boolean evaluates to false. When converting from Pascal to Java you need to switch the boolean to work the other way.

rossum
  • 15,344
  • 1
  • 24
  • 38
1

The primary difference between while loop and a do-while loop is that while loop does eager condition check where as do-while loop does lazy condition check

while: Expression is evaluated at the top of the loop

syntax:

while (expression) {
     statement(s)
}

enter image description here

(taken from http://www.w3resource.com/c-programming/c-while-loop.php)

Example:

public class WhileDemo{

    public static void main(String args[]) {
        boolean isSunday = false;
        while(isSunday) {
            System.out.println("Yayy.. Its Sunday!!");
        }
    }

}

Output: (nothing is printed on console)

Reason: Since isSunday is false, the body of loop is not executed

do-while: Expression is evaluated at the bottom of the loop. Therefore, the statements within the do block are always executed at least once.

syntax:

do {
     statement(s)
} while (expression);

enter image description here

(taken from http://www.w3resource.com/c-programming/c-do-while-loop.php)

Example:

public class DoWhileDemo{

    public static void main(String args[]) {
        boolean isSunday = false;
        do {
            System.out.println("Yayy.. Its Sunday!!");
        } while(isSunday);
    }

}

Output: Yayy.. Its Sunday!!

Reason: The body of do is executed first, there by printing Yayy.. Its Sunday!! and then the condition while(isSunday); evaluates to false since isSunday is false and the loop terminates

Matt
  • 74,352
  • 26
  • 153
  • 180
JavaHopper
  • 5,567
  • 1
  • 19
  • 27
0

You're only missing one thing from your problem. Your explanation of the Pascal code is almost correct, but wouldn't work without some modification.

In Java, use short-circuit logical operators to do the check.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

Not tested:

int n = 0;
int a[] = new a[3];
do {
   n++;
   a[0] = a[1];
   a[1] = a[2];
   a[2] = input.nextInt();
} while ((n < 3) || (a[0]+a[1] != a[2])); 
System.out.println(a[2]);
markspace
  • 10,621
  • 3
  • 25
  • 39