- Joined
- Nov 22, 2023
- Messages
- 16
- Reaction score
- 0
can anyone post some code for For Loop, Selection, Array and Method ?
public class ForLoopExample {
public static void main(String[] args) {
// For loop that prints numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
}
}
public class SelectionExample {
public static void main(String[] args) {
int number = 7;
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
public class ArrayExample {
public static void main(String[] args) {
// Array of integers
int[] numbers = {1, 2, 3, 4, 5};
// Loop through the array and print each element
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
public class MethodExample {
public static void main(String[] args) {
// Call the method with an argument
int result = square(5);
System.out.println("Square of 5 is: " + result);
}
// Method to calculate the square of a number
public static int square(int num) {
return num * num;
}
}
thanks !For loop
Java:public class ForLoopExample { public static void main(String[] args) { // For loop that prints numbers from 1 to 5 for (int i = 1; i <= 5; i++) { System.out.println("Number: " + i); } } }
Selection
Java:public class SelectionExample { public static void main(String[] args) { int number = 7; if (number % 2 == 0) { System.out.println(number + " is even."); } else { System.out.println(number + " is odd."); } } }
Array
Java:public class ArrayExample { public static void main(String[] args) { // Array of integers int[] numbers = {1, 2, 3, 4, 5}; // Loop through the array and print each element for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } } }
Method
Java:public class MethodExample { public static void main(String[] args) { // Call the method with an argument int result = square(5); System.out.println("Square of 5 is: " + result); } // Method to calculate the square of a number public static int square(int num) { return num * num; } }
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.