0% found this document useful (0 votes)
2 views

Snippet_of_code_and_what_it_does

fcjhgvjhu

Uploaded by

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

Snippet_of_code_and_what_it_does

fcjhgvjhu

Uploaded by

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

1.

Sum of Array Elements Using For-Each Loop

Snippet of code What it does


int[] numbers = {4, 8, 15, 16, 23, 42}; Create a list of numbers

int sum = 0;
Start with sum = 0
for (int number : numbers) { Go through each number in the list

sum += number; Add the number to sum.

System.out.println("Sum: " + sum); Print the sum.

2. Finding the Maximum Element Using For-Each Loop

Snippet of code What it does


int[] numbers = {4, 8, 15, 16, 23, 42}; Create a list of numbers

int max = numbers[0]; Start with the first number as max

for (int number : numbers) { Go through each number in the list

if (number > max) { If a number is bigger than max,

max = number; Update max to this number

System.out.println("Maximum: " + max); Print the biggest number

3. Counting Even Numbers Using For-Each Loop

Snippet of code What it does


int[] numbers = {4, 8, 15, 16, 23, 42}; Create a list of numbers

int count = 0; Start with count = 0

for (int number : numbers) { Go through each number in the list

if (number % 2 == 0) { If the number is even,

count++; Increase the count by 1

System.out.println("Even Count: " + count); Print the count of even numbers


4. Printing Elements in Reverse Order Using Traditional For Loop

Snippet of code What it does


int[] numbers = {4, 8, 15, 16, 23, 42}; Create a list of numbers

for (int i = numbers.length - 1; i >= 0; i--) { Start with the last number and go backwards

System.out.println(numbers[i]); Print each number in reverse order

5. Searching for a Specific Value Using For-Each Loop

Snippet of code What it does


int[] numbers = {4, 8, 15, 16, 23, 42}; Create a list of numbers

int target = 15; Set the number to search for

boolean found = false; Assume, its not found yet

for (int number : numbers) { Go through each number in the list

if (number == target) { If the number matches target,

found = true; Set found to be true.

break; Stop searching.

if (found) { If found is true,

System.out.println(target + " is in the array."); Print that the number is found

} else { Otherwise,

System.out.println(target + " is not in the


Print that its not found
array.");

You might also like