Week 2

Table of Contents

Primitive Data Types in Java
Operators in Java
Classes and the Math Class
Packages in Java
Variable Scope in Java
Looping Structures in Java
Conditional Structures in Java

Looping Structures in Java

In most programming, there are 3 main kinds of loops. The For Loop, the While Loop, and the Do Until(While) loop. We will look at each individually below. There are also several statements, such as break and continue, that we will demonstrate their use for.

For Loop

basic syntax:

for (initialization expr; test expr; update exp) {
    // body of the loop
    // statements we want to execute
}

example:

for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}
// simply loops from 1 to 10 outputting the number of the current iteration.
// where.....
// int i = 1    is the initialization parameter
// i <= 10      is the conditional parameter
// i++          is the incremental parameter

For Each Loop

basic syntax:

for (type var : array) { 
    statements using var;
}

example:

// array declaration 
int ar[] = { 10, 50, 60, 80, 90 }; 

for (int element : ar) {
    System.out.print(element + " ");
}

While Loop

basic syntax

while (test_expression)
    {
       // statements
       
       update_expression;
    }

example

int i=0;
while (i<=10)
    {
        System.out.println(i);
        i++;
    }
}

Do Loop (Do Until/Do While)

basic syntax

do {
    // Loop Body
    Update_expression
} while (test_expression);   // Condition check

example:

// initial counter variable
int i = 0;
do {
    // Body of loop that will execute minimum
    // 1 time for sure no matter what
    System.out.println("Print statement");
    i++;
} while (i < 0);
// Checking condition
// Note: It is being checked after
// minimum 1 iteration