0% found this document useful (0 votes)
38 views2 pages

Common Loop Errors

arrays

Uploaded by

mercychep246
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views2 pages

Common Loop Errors

arrays

Uploaded by

mercychep246
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

COMMON LOOP ERRORS

Infinite Loops
Infinite loops occur when a loop keeps running indefinitely

Off-by-One Errors
Off-by-one errors are a common type of loop error where the loop iterates one time more or less than desired,
causing incorrect results

Nested Loop Confusion


Nested loops occur when one loop is placed inside another to perform complex tasks or multi-
dimensional iterations

2.ARRAYS IN JAVA
Definition
An array is a collection of similar data types stored in contiguous memory locations. Arrays have a fixed
size.
DECLARING , INITIALIZING AND ACCESSING AN ARRAY

Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

1.To declare an array, define the variable type with square brackets:

String[] cars;

2. To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

3 Access the Elements of an Array


You can access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

// Outputs Volvo
public class Main {
public static void main(String[] args) {
// Declaring and initializing an array
int[] numbers = {10, 20, 30, 40, 50};

// Accessing array elements


System.out.println("First element: " + numbers[0]);
System.out.println("Second element: " + numbers[1]);
}
}

ITERATING THROUGH AN ARRAY


public class Main {
public static void main(String[] args) {
// Array of integers
int[] numbers = {10, 20, 30, 40, 50};

// Looping through the array


for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}

You might also like