Saturday, July 30, 2022

Decision Making Statements in Programming Languages 1

if Statement

Flowchart





if else Statements

Flowchart



Nested if Statements

Flowchart



if else if Ladder

Flowchart



switch Statements

Java Syntax

switch(expression) {  
    case value_1:    statement_1; break;   
    case value_2:    statement_2; break;
    case value_n:    statement_n; break;
    default:         statement_d;
}

Important Keywords

  • case : Specifies the statements that should be executed if case is matched.
  • default : Specifies the statements that should be executed if case is not matched.
  • break : Terminates the execution of the switch block.Languages

Jump Statements

break

The break keyword exits from the current iteration and jumps to the instructions following the loop block.

Java Syntax

class Main {
    public static void main(String[] args) { 
        boolean stopThread = true;
        while(true) {
            System.out.println("Running thread");
            if(stopThread) {
                break;
            }
        }

    }
}

Flowchart



continue

Just like the break keyword the continue exits from the current iteration, but unlike the break it goes on to the following iterations.



In Java, you can use the break keyword to exit from a label block, an if-else block, switch case, or a loop block. Needles to say, you can’t use the continue keyword except in a loop.

goto

Using the goto aka unconditional jump, you force the program counter (PC) to jump to a specific instruction.

#include<stdio.h>

void foo(int num) {
    int n = 0;
    label:
    n++;
    printf("%d", n);
    if (n <= num)
        goto label;
}

Below is the output of the x86-64 gcc 12.1 compiler. I used this wonderful tool to generate compiler’s assembly output.

.LC0:
        .string "%d"
foo(int):
        push    rbp
        mov     rbp, rsp
        sub     rsp, 32
        mov     DWORD PTR [rbp-20], edi
        mov     DWORD PTR [rbp-4], 0
.L2:
        add     DWORD PTR [rbp-4], 1
        mov     eax, DWORD PTR [rbp-4]
        mov     esi, eax
        mov     edi, OFFSET FLAT:.LC0
        mov     eax, 0
        call    printf
        mov     eax, DWORD PTR [rbp-4]
        cmp     eax, DWORD PTR [rbp-20]
        jg      .L4
        jmp     .L2
.L4:
        nop
        leave
        ret

Although C/C++ supports the goto keyword, Java doesn’t. However, Java supports using labels.


public class Label {
    public static void main(String[] args) {
        label  : {
            if (condition) 
                    break label;
            // some other code that won't be executed if the condition is true
        }
    }
}

return

Syntax

return[expression];

The return keyword, terminates a function jumping back to the instruction following the function call. The return keyword is different from other jump statements as it is not conditional.

Resources

No comments:

Post a Comment