Java Program For Running a Loop from 1-100
Apr 3, 2024
Make sure to subscribe to our newsletter and be the first to know the news.
Apr 3, 2024
Make sure to subscribe to our newsletter and be the first to know the news.
Looping is a fundamental programming concept that allows repetitive execution of a block of code based on a specified condition or a fixed number of iterations. In Java, looping constructs such as "for" and "while" loops facilitate efficient iteration through collections, arrays, or performing tasks repeatedly until certain conditions are met.
Understanding the code
1. The code initializes variables start and end to represent the range of numbers to be iterated over (from 1 to 100 in this case).
2. Within the main method, a "for" loop is utilized to iterate over each number within the specified range.
3. Inside the loop, each number is evaluated to determine whether it's even or odd using the modulus operator (%). If the number is even, its square is computed and displayed along with a message indicating it's an even number. If the number is odd, its cube is computed and displayed along with a corresponding message.
4. The code prints out the computed values along with appropriate messages for each number, showcasing the use of looping constructs to efficiently perform repetitive tasks.
public class LoopingExample {
public static void main(String[] args) {
int start=1;
int end=100;
for (int number=start;number<=end;number++){
if(number%2==0){
System.out.println("Even Number-"+number+" || Square:"+(number*number));
}
else{
System.out.println("Odd Number-"+number+" || Cube:"+(number*number*number));
}
}
}
}
Conclusion : In conclusion, the provided Java code demonstrates the power and versatility of looping constructs in automating repetitive tasks and streamlining program execution. By employing a "for" loop, the code efficiently iterates over a range of numbers from 1 to 100, evaluating each number to determine whether it's even or odd. This example showcases how looping constructs enhance the readability and efficiency of code by automating repetitive computations and tasks.