Java Loops: Nested For & While Loops

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What output will the following code produce? int height = 4; int width = 10; for (int rowCount = 0; rowCount < height; rowCount++ ) { for (int colCount = 0; colCount < width; colCount++ ) { System.out.print("@"); } System.out.println(); }

  • A 4x10 grid of numbers.
  • A single line of 40 '@' symbols.
  • Ten lines, each containing four '@' symbols.
  • Four lines, each containing ten '@' symbols. (correct)

In a while loop, under what condition will the code block inside the loop execute?

  • When a specific exception is thrown.
  • When the boolean expression is true. (correct)
  • When the boolean expression is false.
  • Only once, at the beginning of the program.

Consider the Java code: int num = 1; int sum = 0; while (num <= 100) { sum += num; num++; } What is the final value of the variable sum?

  • 10000
  • 5050 (correct)
  • 50
  • 100

What is the key difference between a while loop and a do-while loop in Java?

<p>A <code>do-while</code> loop always executes at least once, while a <code>while</code> loop may not execute at all. (A)</p> Signup and view all the answers

What is the primary purpose of the break statement in a loop?

<p>To terminate the entire loop and proceed to the next statement after the loop. (D)</p> Signup and view all the answers

Given a for loop that iterates through numbers 1 to 10, what would be the effect of a continue statement when the loop variable is 5?

<p>The number 5 will be skipped, and the loop will continue with 6. (C)</p> Signup and view all the answers

What is the key difference between the break and continue statements in loop control?

<p><code>break</code> terminates the loop, while <code>continue</code> skips the current iteration. (B)</p> Signup and view all the answers

Which of the following statements about Java arrays is correct?

<p>The length of an array is fixed after creation. (A)</p> Signup and view all the answers

What is the purpose of an array in Java?

<p>To store a group of values of the same type. (C)</p> Signup and view all the answers

Given the following array declaration, int[] numbers = {10, 20, 30, 40, 50};, how would you access the third element (value 30) of the array?

<p><code>numbers[2]</code> (C)</p> Signup and view all the answers

Which of the following code snippets correctly instantiates an array of integers with a size of 10?

<p><code>int[] arr = new int[10];</code> (C)</p> Signup and view all the answers

If you declare an array as int[] numbers = new int[5];, what is the initial value of numbers[0]?

<p>0 (C)</p> Signup and view all the answers

What is the output of the following code? int[] arr = {50, 60, 70, 80}; for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); }

<p>50\n60\n70\n80\nArrayIndexOutOfBoundsException (A)</p> Signup and view all the answers

Given the following code, what will be printed to the console? String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i); }

<p>The strings &quot;Volvo&quot;, &quot;BMW&quot;, &quot;Ford&quot;, and &quot;Mazda&quot;, each on a new line. (B)</p> Signup and view all the answers

Consider the code: int[] ages = {27, 12, 82, 70, 54, 1, 30, 34}; for (int i = 0; i < ages.length; i++ ) { System.out.println("Age is " + ages[1]); } What will be the output?

<p>Age is 12\nAge is 12\nAge is 12\nAge is 12\nAge is 12\nAge is 12\nAge is 12\nAge is 12 (A)</p> Signup and view all the answers

Given the array int[] ages = new int[5];, what is the result of the following code? for (int i = 0; i < ages.length; i++ ) { ages[i] = 10; }

<p>All elements of the <code>ages</code> array will be set to 10. (D)</p> Signup and view all the answers

Given the code: int[] ages = {27, 12, 82, 70, 54, 1, 30, 34}; What is the output of the following enhanced for loop? for (int age : ages ) { System.out.println("Age is " + age); }

<p>Age is 27\nAge is 12\nAge is 82\nAge is 70\nAge is 54\nAge is 1\nAge is 30\nAge is 34 (D)</p> Signup and view all the answers

In the break example code, what will happen when a unitScore is greater than passmark?

<p>the variable <code>passed</code> will be set to true and the loop will exit. (C)</p> Signup and view all the answers

Referring to the continue example code, what occurs when score[i] is less than passMark?

<p>The current iteration is skipped using <code>continue</code>, and moves to the next unit. (B)</p> Signup and view all the answers

How would you declare a two-dimensional array named sales of type double?

<p><code>double[][] sales;</code> (B)</p> Signup and view all the answers

How do you instantiate a two-dimensional array named yearlySales with 5 rows and 4 columns?

<p><code>yearlySales = new int[5][4];</code> (B)</p> Signup and view all the answers

Given int[][] sales = new int[3][4];, how would you initialize the element in the first row and second column to 1000?

<p><code>sales[0][1] = 1000;</code> (D)</p> Signup and view all the answers

Which of the following loops will print each element of the 2D array int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};?

<p>All of the above (D)</p> Signup and view all the answers

What is the result of running this code?

int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
    if (i % 2 == 0) {
        continue;
    }
    sum += numbers[i];
}
System.out.println(sum);

<p>6 (A)</p> Signup and view all the answers

Which of the following best describes the ArrayIndexOutOfBoundsException in Java?

<p>It occurs when you try to access an array element with an index that is outside the bounds of the array. (A)</p> Signup and view all the answers

What is the output after executing the given code snippet?

int[] arr = {10, 5, 8, 20};
int maxVal = arr[0];
for (int num : arr) {
    if (num > maxVal) {
        maxVal = num;
    }
}
System.out.println(maxVal);

<p>20 (C)</p> Signup and view all the answers

What would be the output of the following program?

public class Main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == 3) {
                break;
            }
            System.out.println(numbers[i]);
        }
    }
}

<p>1\n2 (D)</p> Signup and view all the answers

Consider the code:

int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
    if (number % 2 == 0) {
        continue;
    }
    sum += number;
}
System.out.println(sum);

What will be printed?

<p>9 (B)</p> Signup and view all the answers

Analyze given code and tell what will be the output:

public class Example {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0; i <= arr.length; i++) {
            try {
                System.out.print(arr[i] + " ");
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.print("Exception ");
            }
        }
    }
}

<p>1 2 3 4 5 Exception (D)</p> Signup and view all the answers

Suppose you have the following code:

int[][] array2D = {{1, 2}, {3, 4, 5}};
System.out.println(array2D[1].length);

What will be printed to the console?

<p>3 (C)</p> Signup and view all the answers

What is the correct syntax to declare a String array named names with a size of 5?

<p><code>String[] names = new String[5];</code> (B)</p> Signup and view all the answers

What is the output of the following code snippet?

int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = i * 2;
}
System.out.println(numbers[3]);

<p>6 (B)</p> Signup and view all the answers

Given String[][] names = {{"Mr", "Mrs", "Ms"}, {"Smith", "Jones"}};, what is the value of names[0][1]?

<p>&quot;Mrs&quot; (C)</p> Signup and view all the answers

What will the code System.out.println(numbers.length); print, given this array: int[] numbers = {1, 2, 3, 4, 5};?

<p>5 (B)</p> Signup and view all the answers

Given the code:

int[] arr = {1, 2, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
    if (arr[i] % 2 != 0) {
        arr[i] = 0;
    }
}

What are the contents of arr after the loop?

<p><code>{0, 2, 0, 4, 0}</code> (D)</p> Signup and view all the answers

What will the value of sum be after executing the following code?

int[] nums = {10, 20, 30, 40};
int sum = 0;
for (int i = 1; i < nums.length; i++) {
    sum += nums[i];
}

<p>90 (A)</p> Signup and view all the answers

What is the output of this code?

String[] colors = {"red", "green", "blue"};
for (String color : colors) {
    System.out.println(color.toUpperCase());
}

<p>RED\GREEN\BLUE (C)</p> Signup and view all the answers

Given the code:

int[][] matrix = new int[3][3];
int count = 1;
for(int i = 0; i < matrix.length; i++) {
    for(int j = 0; j < matrix[i].length; j++) {
        matrix[i][j] = count++;
    }
}

What is the value of matrix[1][2]?

<p>6 (C)</p> Signup and view all the answers

Flashcards

Nested for Loop

A loop inside another loop, allowing for more complex iteration patterns.

While Loop

A loop that executes a block of code as long as a specified condition is true.

Do-While Loop

A loop that executes a block of code once, and then repeats as long as a specified condition is true.

Break Statement

A statement that terminates the current loop and transfers control to the statement following the loop.

Signup and view all the flashcards

Continue Statement

A statement that skips the rest of the current iteration of a loop and proceeds to the next iteration.

Signup and view all the flashcards

Function of 'break'

Terminates the entire loop and jumps to the statement after the loop.

Signup and view all the flashcards

Function of 'continue'

Skips the current iteration and proceeds to the next iteration of the loop.

Signup and view all the flashcards

Array

A container object that holds a fixed number of values of a single type. Elements are accessed using indices.

Signup and view all the flashcards

One-Dimensional Array

A simple array that uses one index to access its elements.

Signup and view all the flashcards

Array Index

The numerical position of an element within an array, starting from 0.

Signup and view all the flashcards

Array Length

The total number of elements an array can hold.

Signup and view all the flashcards

Traversing an Array

Accessing each element of an array in sequential order.

Signup and view all the flashcards

ArrayIndexOutOfBoundsException

Occurs when trying to access an index that is outside the bounds of the array.

Signup and view all the flashcards

"For-each" Loop

Enhanced loop to iterate through each element of an array or collection.

Signup and view all the flashcards

For Loop with Arrays

A loop construct used to access elements of an array by incrementing an index.

Signup and view all the flashcards

Setting Array Values

Storing a value at a specific index within an array.

Signup and view all the flashcards

Two-Dimensional Array

An array that consists of rows and columns, requiring two indices to access an element.

Signup and view all the flashcards

Declaring a 2D Array

Defining the array's type and name, specifying it will hold multiple arrays.

Signup and view all the flashcards

Instantiating a 2D Array

Allocating memory space for the array, defining the number of rows and columns.

Signup and view all the flashcards

Initializing a 2D Array

Assigning initial values to the elements within the array.

Signup and view all the flashcards

Study Notes

  • Lecture 5 by Dr. Dina Saif

Nested for Loop

  • The provided code demonstrates a nested for loop in Java.
  • The outer loop iterates based on the height, which is set to 4.
  • The inner loop iterates based on the width, which is set to 10.
  • The inner loop prints "@" without a newline for each column in the current row.
  • System.out.println() is called after each inner loop, moving to the next line.

Creating while Loops

  • A while loop executes a block of code as long as a boolean expression is true.
  • Syntax of a while loop includes while (boolean expression) { code block; }.
  • The code block is executed repeatedly as long as the boolean expression evaluates to true.
  • If the boolean expression is false, the program skips the code block and continues execution after the loop.

While Loop Example

  • The while loop example uses variable i, initialized to 0.
  • The loop continues as long as i is less than 5.
  • Inside the loop, the current value of i is printed, then i increments by 1.

Example: NumberAdder Class

  • The NumberAdder class provides an example of using a while loop.
  • It calculates the sum of numbers from 1 to 100.
  • The loop continues as long as the variable "num" is less than or equal to 100.
  • Inside the loop, num is added to the value in "sum", and then increments num by 1.
  • Finally, it prints the sum of numbers from 1 to 100.

Do-While Loop

  • A do-while loop executes a block of code at least once, and then continues to execute the block repeatedly if the condition is true.
  • The code block is executed before the condition is checked.

Even Numbers using For and While Loop

  • Demonstrates how to print even numbers from 1 to 100 using both for and while loops.
  • Using for loop, an if statement checks if the current number is even (divisible by 2).
  • Using while loop also uses an if statement to check for evenness and prints accordingly

Descending Numbers Program

  • Program prints numbers from 50 to 10 in descending order, using both for and while loops.
  • The for loop initializes i to 50, continues as long as i is greater than or equal to 10, and decrements i by 1 in each iteration.
  • The while loop initializes j to 50, continues as long as j is greater than or equal to 10, and decrements j by 1 in each iteration.

Break Statement

  • A break statement is used to exit a loop early.
  • The Java code demonstrates how to print numbers from 1 to 10, but stop when the number 5 is reached using a break statement.

Break Example Program

  • The loop prints numbers from 1 to 4, then exits when it reaches the number 5.

Continue Statement

  • The continue statement skips the current iteration and goes to the next iteration of the loop.
  • Used to print numbers from 1 to 10, skipping the number 5.

Continue Example Program

  • Demonstrates skipping the number 5 within the loop, printing all other numbers from 1 to 10.

Break and Continue Statements

  • Break statement terminates the entire loop and jumps to the statement after it.
  • Continue statement skips the current iteration and proceeds to the next iteration of the loop.
  • Using both can make code flexible and efficient by controlling loop flow based on conditions.

Introduction to Arrays

  • An array is a container object that holds a group of values of a single type.
  • The type of the values in the array can be a primitive or an object type.
  • The length of an array is established when the array is created and fixed after.
  • Each item in an array is called an element, accessed by a numerical index, which starts at 0 (zero).

One-Dimensional Arrays

  • Example declaration of multiple one dimensional arrays
  • Each array is of type int

Creating One-Dimensional Arrays

  • Depicts arrays of int types and arrays of String types

Multidimensional Arrays

  • Multidimensional arrays will have rows and columns.
  • This can be thought of as a grid.

Array length is 8

  • First index starts at 0
  • Last index is element 5 at the value 1
  • Ages length is 8 (ages.length)

Java Array Advantages

  • Code Optimization: optimizes code by retrieving and sorting efficiently.
  • Random access: accesses any data located at an index position.
  • Disadvantage: has a size limit

Single Dimensional Array in Java

  • dataType[] arr; or dataType []arr; or dataType arr[];
  • arrayRefVar=new datatype[size];

Storing Arrays in Memory

  • char size = 'L'
  • char[] sizes = {'S', 'M', 'L' };
  • Shows how primitive variables are stored in memory

Storing Arrays of References in Memory

  • Shirt myShirt = new Shirt();
  • Shirt[] shirts = { new Shirt(), new Shirt(), new Shirt() };
  • Shows how shirts are stored in memory

Traversing Array

  • Traverses an array and prints all numbers from 10, 20, 70, 40, and 50 through each loops

Declaration and Initialization

  • Declares variables to 33, 3, 4, 5 and prints each line

ArrayIndexOutOfBoundsException

  • An exception that will occur if the bounds of an array is broken

For Each Array

  • String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
  • Prints each car

For Loop with Arrays

  • Each array item is printed out
  • "Age is..." ages is the array being used

Set Values in Arrays

  • Each element in array is set to the value 10

Enhanced for Loop with Arrays

  • Array is transversed and printed in each line

Enhanced for Loop with Array Lists

  • Code loops through an ArrayList to access each element

Using Break with Loops

  • If you meet condition, end loop.
  • There is no need to go through loop so break.

Using Continue with Loops

  • If failed unit, test for all next unit
  • If unit failed, go on to check the next unit

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Nested Loops in C#
6 questions

Nested Loops in C#

ThrillingParadox avatar
ThrillingParadox
Nested Loops in Programming
5 questions

Nested Loops in Programming

MemorableWashington8619 avatar
MemorableWashington8619
Understanding and Using Nested Loops
10 questions
Use Quizgecko on...
Browser
Browser