Looping in java (class 8)
A for loop is a control structure that allows you to repeat a block of code a specific number of times.
In Java, the syntax is:
🧩 Explanation of each part
-
Initialization → executed once before the loop starts.
(Usually used to declare and set a loop variable.) -
Condition → checked before each iteration. If it’s
true
, the loop runs. -
Update → executed after every iteration (to change the loop variable).
⚙️ Real-time Example
Imagine you are a teacher and want to display the names of 5 students in order.
Instead of writing 5 print statements, you can use a for loop.
💻 Example 1 – Simple counting
Output:
💼 Example 2 – Real-time situation (Printing bills)
Suppose you run a store and you want to print 10 bills in a day.
Output:
🧮 Example 3 – Calculate sum of first 10 natural numbers
Output:
Comments
Post a Comment