Page 1 of 1

[HD Pg 152, Sec. 6.4.0 - exercises]

Posted: Mon Jul 15, 2024 12:24 pm
by alexandra.i.vornicu
About exercise 2 "Accept a number between 0 to 5 as input and print the sum of numbers from 1 to the input number using code that exploits the "fall through" behavior of a switch statement. "
I wrote:

Code: Select all

public static void printSum (int number) {
        int sum = 0;
        switch(number) {
            case 1:
                sum += 1;
                break;
            case 2:
                sum += 3;
                break;
            case 3:
                sum += 6;
                break;
            case 4:
                sum += 10;
                break;
            case 5:
                sum += 15;
                break;
        }
        System.out.println(sum);
    }"
How can you make it with the "fall through" behaviour of switch statement?

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Posted: Tue Jul 16, 2024 10:53 am
by admin

Code: Select all

    public static void printSum (int number) {
        int sum = 0;
        switch(number) {
            case 5:
                sum += 5;
            case 4:
                sum += 4;
            case 3:
                sum += 3;
            case 2:
                sum += 2;
            case 1:
                sum += 1;
        }
        System.out.println(sum);
    }

Re: [HD Pg 152, Sec. 6.4.0 - exercises]

Posted: Thu Jul 18, 2024 11:06 am
by alexandra.i.vornicu
Thank you very much!