Follow Us
Select Medium / माध्यम चुनें:
Eng (English) Hindi (हिन्दी)
ICSE • Class 9 • Information Technology • Ch 8
Estimated Time: 45 Mins
Study Progress: In Progress

Iterative constructs in Java

In ICSE Class 9 Computer Applications, "Iterative Constructs in Java" examines the computational loops that execute code blocks repeatedly until a terminating boolean condition is met. This comprehensive chapter explores the structural taxonomy of iterative constructs, contrasting Entry-Controlled Loops (for loop and while loop, where the test expression is validated before entering the body) with Exit-Controlled Loops (do-while loop, where the test expression is validated after the body executes, guaranteeing at least one execution). Students analyze the four essential elements of loop architecture (Initialization, Test Condition, Loop Body, and Update Expression), investigate loop variations (infinite loops, empty/null loops, comma-separated multiple expressions), and master Jump Statements (break for premature loop termination versus continue for skipping the current iteration). The guide provides exhaustive, board-mandated algorithmic implementations for core number programs: Factorial, Prime Number verification, Digit Extraction pipelines, Reverse Number, Palindrome Number, Armstrong Number, Special (Krishnamurthy) Number, Neon Number, and Duck Number, complete with dry-run trace matrices and CISCE marking rubrics.

How Did a Single Loop Variable Reaching 2,147,483,647 Break YouTube's Counter During the "Gangnam Style" Frenzy?

In December 2014, the viral music video "Gangnam Style" by Psy achieved something software engineers at Google thought was impossible: it literally broke YouTube's view counter! When YouTube was engineered, programmers used a standard 32-bit signed integer (`int`) to count video views. The maximum positive number a 32-bit signed integer can hold is $2^{31} - 1 = 2,147,483,647$. When the view count loop ticked past that number, the integer overflowed into a negative number: $-2,147,483,648$, displaying a bizarre glitch! Google engineers had to urgently update the database counter to a 64-bit signed integer (`long`), capable of holding over 9 quintillion views! In programming, loops are the workhorses of computation—they process millions of records per second, power physics engines, and simulate artificial intelligence. A single flaw in a loop condition can freeze a server in an infinite loop or trigger an overflow. Let us master iterative loops and algorithmic number theory in Java.

Why This Chapter Matters

Looping constructs and number manipulation algorithms represent over 50% of the practical programming section (Section B) in ICSE Computer Applications examinations. Every board paper features at least two full 15-mark programs requiring while/for loops for digit extraction, number series, or factor analysis.

Before You Begin (Prerequisites)

  • Arithmetic operators (+, -, *, /, %) and increment/decrement operators (++, --).
  • Relational and logical conditions.
  • Basic console input using Scanner.

What You Will Learn (Core Objectives)

  • Compare and contrast entry-controlled (`for`, `while`) and exit-controlled (`do-while`) loops.
  • Analyze the execution cycle of the four loop components: Initialization, Condition, Body, and Update.
  • Apply jump statements: predict behavior of `break` and `continue` across loop iterations.
  • Execute digit extraction algorithms (`n % 10` and `n / 10`) to compute sums, products, and digit counts.
  • Implement algorithms to check Palindrome, Armstrong, Prime, Special, Neon, and Duck numbers.
  • Trace and calculate the output of loop code snippets with trace tables.

Chapter Roadmap & Progression

1 1. Anatomy of a Loop: Entry-Control...
2 2. The Three Loop Constructs: Synta...
3 3. Jump Statements: break vs contin...
4 4. Digit Extraction Pipeline: The M...
5 5. Master ICSE Number Programs Cata...
6 6. Advanced Algorithmic Programs: P...
7 7. Comprehensive Number Programs: P...
8 8. Euclidean Algorithm for Highest...
9 9. Complete Source Code: Neon Numbe...
10 10. Automorphic Number Verification...
11 11. Comparing Loop Efficiency: Time...
12 12. Factorial of Large Numbers & Lo...

Complete Concept Guide (100% Curriculum Coverage)

1. Anatomy of a Loop: Entry-Controlled vs Exit-Controlled

Loop Architecture
A. The Four Essential Components of Any Loop:
  1. 1. Initialization Expression: Sets the starting value of the loop control variable (e.g., int i = 1;). Executes once at the very beginning.
  2. 2. Test Expression (Condition): A boolean condition evaluated before (or after) each iteration. If true, the loop body executes; if false, the loop terminates.
  3. 3. Loop Body: The set of statements executed repeatedly during each iteration.
  4. 4. Update Expression: Modifies (increments/decrements) the loop control variable after each iteration (e.g., i++), steering the loop towards termination.
B. Entry-Controlled vs Exit-Controlled Loops:
FeatureEntry-Controlled Loops (for, while)Exit-Controlled Loop (do-while)
Condition Check Condition is evaluated before the loop body is executed. Condition is evaluated after the loop body has executed.
Minimum Executions 0 times (If condition is false initially, body never runs). At least 1 time (Body always executes once unconditionally).
Syntax Terminator No semicolon after loop header (e.g., for(...), while(...)). Mandatory semicolon after condition: do { ... } while(condition);
Ideal Use Case When iterations depend on a precondition or are known in advance. Interactive menu loops where prompt must be displayed at least once.

2. The Three Loop Constructs: Syntax & Execution Flow

Syntax & Mechanics
A. The `for` Loop (Definite Iteration):
for (initialization; test_condition; update_expression) {
    // Loop body statements
}

Execution Order: 1. Initialization → 2. Condition check → 3. Body execution → 4. Update expression → 5. Repeat from Step 2.

B. The `while` Loop (Indefinite Pre-Test):
initialization;
while (test_condition) {
    // Loop body statements
    update_expression;
}
C. The `do-while` Loop (Post-Test):
initialization;
do {
    // Loop body statements
    update_expression;
} while (test_condition); // Note the compulsory semicolon!
D. Loop Variations & Traps:
  • Infinite Loop: for(;;) { } or while(true) { } (Never terminates unless break is triggered).
  • The Null / Empty Loop Trap: Putting an accidental semicolon at the end of a loop header creates a loop with an empty body:
    int i;
    for (i = 1; i <= 5; i++); // Semicolon here isolates the loop!
    System.out.println(i);    // Prints 6 (prints once after loop finishes)!

3. Jump Statements: break vs continue

Control Transfer
A. The `break` Statement:

Forces the immediate and complete termination of the enclosing loop. Control jumps directly to the first statement outside the loop block.

for (int i = 1; i <= 10; i++) {
    if (i == 5) break; // Exits loop completely when i reaches 5
    System.out.print(i + " ");
} // Output: 1 2 3 4
B. The `continue` Statement:

Skips the remaining statements of the current iteration and transfers control immediately to the next iteration (jumping directly to the update expression in a for loop, or to the condition in a while loop).

for (int i = 1; i <= 5; i++) {
    if (i == 3) continue; // Skips printing 3
    System.out.print(i + " ");
} // Output: 1 2 4 5

4. Digit Extraction Pipeline: The Mathematical Core

Algorithmic Engine
A. The Universal Digit Extraction Algorithm:

To process individual digits of an integer $N$ from right to left:

int n = 153;
while (n > 0) {
    int digit = n % 10; // Extract the rightmost (last) digit
    // Process the extracted digit (sum, reverse, count, etc.)
    n = n / 10;         // Strip/remove the rightmost digit
}
B. Trace Table for Digit Extraction ($N = 153$):
Iterationn at startdigit = n % 10Operation (e.g. sum += digit)n = n / 10Condition (n > 0)
115330 + 3 = 315true
21553 + 5 = 81true
3118 + 1 = 90false (Loop terminates)

5. Master ICSE Number Programs Catalog

Board Programs
Complete Reference Algorithms:
Number TypeDefinition & ExampleCore Algorithmic Logic
Prime Number A number greater than 1 having exactly two factors (1 and itself). e.g., 7, 13, 29. Count factors from 1 to N. If count == 2, it is prime.
Palindrome Number A number that remains identical when its digits are reversed. e.g., 121, 1331. Extract digits, compute rev = rev * 10 + digit. Check rev == originalNumber.
Armstrong Number Sum of cubes of each individual digit equals the original number. e.g., $153 = 1^3 + 5^3 + 3^3 = 153$. Extract digits, compute sum += digit * digit * digit. Check sum == originalNumber.
Special Number (Krishnamurthy) Sum of factorials of each individual digit equals original number. e.g., $145 = 1! + 4! + 5! = 145$. Extract digits, compute factorial of each digit, add to sum. Check sum == originalNumber.
Neon Number Sum of digits of square of the number equals the original number. e.g., $9^2 = 81 ightarrow 8 + 1 = 9$. Compute sq = n * n. Extract digits of sq and sum them. Check sum == n.
Duck Number A positive number containing at least one zero, but not starting with zero. e.g., 204, 1005. Extract digits of $N$. If digit == 0, set flag. Ensure first digit is non-zero.

6. Advanced Algorithmic Programs: Prime, Fibonacci & Special Numbers

Algorithmic Implementations
A. Armstrong Number Verification:
import java.util.Scanner;

public class ArmstrongCheck {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int num = in.nextInt();
        int temp = num;
        int sumOfCubes = 0;

        while (temp > 0) {
            int digit = temp % 10;
            sumOfCubes += (digit * digit * digit);
            temp /= 10;
        }

        if (sumOfCubes == num) {
            System.out.println(num + " is an Armstrong Number.");
        } else {
            System.out.println(num + " is NOT an Armstrong Number.");
        }
    }
}
B. Generating the Fibonacci Series (0, 1, 1, 2, 3, 5, 8, 13...):
public class FibonacciDemo {
    public static void main(String[] args) {
        int n = 10; // Number of terms
        int first = 0, second = 1;
        System.out.print("Fibonacci Series: " + first + " " + second + " ");
        for (int i = 3; i <= n; i++) {
            int next = first + second;
            System.out.print(next + " ");
            first = second;
            second = next;
        }
        System.out.println();
    }
}

7. Comprehensive Number Programs: Palindrome & Special Number

Complete Number Implementations
A. Palindrome Number Checker:
import java.util.Scanner;

public class PalindromeCheck {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        int n = in.nextInt();
        int original = n;
        int reversed = 0;

        while (n > 0) {
            int digit = n % 10;
            reversed = reversed * 10 + digit;
            n /= 10;
        }

        if (reversed == original) {
            System.out.println(original + " is a Palindrome Number.");
        } else {
            System.out.println(original + " is NOT a Palindrome Number.");
        }
    }
}
B. Special (Krishnamurthy) Number Checker (145 = 1! + 4! + 5!):
public class SpecialNumberCheck {
    public static void main(String[] args) {
        int n = 145;
        int temp = n;
        int sumOfFactorials = 0;

        while (temp > 0) {
            int digit = temp % 10;
            // Compute factorial of extracted digit
            int fact = 1;
            for (int i = 1; i <= digit; i++) {
                fact *= i;
            }
            sumOfFactorials += fact;
            temp /= 10;
        }

        if (sumOfFactorials == n) {
            System.out.println(n + " is a Special (Krishnamurthy) Number.");
        } else {
            System.out.println(n + " is NOT a Special Number.");
        }
    }
}

8. Euclidean Algorithm for Highest Common Factor (HCF) & LCM

Euclidean Algorithm
A. Calculating HCF/GCD and LCM using while loop:
import java.util.Scanner;

public class HcfLcmDemo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter two positive integers: ");
        int a = in.nextInt();
        int b = in.nextInt();

        int num1 = a, num2 = b;
        // Euclidean remainder loop
        while (num2 != 0) {
            int remainder = num1 % num2;
            num1 = num2;
            num2 = remainder;
        }
        int hcf = num1;
        int lcm = (a * b) / hcf; // Mathematical relationship: Product = HCF * LCM

        System.out.println("Highest Common Factor (HCF) = " + hcf);
        System.out.println("Lowest Common Multiple (LCM) = " + lcm);
    }
}

9. Complete Source Code: Neon Number & Duck Number Verification

Special Number Logic
A. Neon Number Program (9² = 81 → 8 + 1 = 9):
public class NeonNumber {
    public static void main(String[] args) {
        int n = 9;
        int sq = n * n;
        int sum = 0;
        while (sq > 0) {
            sum += sq % 10;
            sq /= 10;
        }
        if (sum == n) System.out.println(n + " is a Neon Number.");
        else System.out.println(n + " is NOT a Neon Number.");
    }
}

10. Automorphic Number Verification in Java

Automorphic Number
A. What is an Automorphic Number?

An Automorphic Number is a number whose square ends in the same digits as the number itself. For example: $5^2 = 25$ (ends in 5), $6^2 = 36$ (ends in 6), $25^2 = 625$ (ends in 25), and $76^2 = 5776$ (ends in 76).

int n = 25;
int sq = n * n;
int temp = n;
int divisor = 1;
// Find divisor (10, 100, etc.) matching digit count of n
while (temp > 0) {
    divisor *= 10;
    temp /= 10;
}
if (sq % divisor == n) {
    System.out.println(n + " is an Automorphic Number.");
} else {
    System.out.println(n + " is NOT an Automorphic Number.");
}

11. Comparing Loop Efficiency: Time Complexity Overview

Algorithmic Efficiency
A. Prime Number Verification Efficiency:

Checking divisors from 2 up to $N-1$ takes $O(N)$ operations. A superior mathematical optimization checks divisors only up to $\sqrt{N}$ (i * i <= N), reducing iterations from 1,000,000 down to just 1,000 checks for $N = 1,000,000$, resulting in a 1,000-fold performance acceleration!

12. Factorial of Large Numbers & Long Data Type Guidance

Precision Tip

Factorial values grow with extreme exponential speed. While a standard 32-bit int can hold factorials up to 12! (479,001,600), computing 13! overflows an int! Therefore, always declare the factorial accumulator as a 64-bit long variable when calculating factorials up to 20!.

Common Misconceptions & Examiner Traps

Common Misconception

Confusing assignment (=) with equality comparison (==) or using invalid identifiers.

Scientific Reality & Correction

Use == for comparison and verify that identifiers follow standard Java naming conventions.

Common Misconception

Omitting break in switch-case or unconsumed newline buffer skipping in Scanner.

Scientific Reality & Correction

Always include break in case blocks to prevent fall-through and flush the buffer before nextLine().

Iterative Constructs: Entry-Controlled vs Exit-Controlled & Digit Extraction

Iterative Constructs: Entry-Controlled vs Exit-Controlled & Digit Extraction ENTRY-CONTROLLED (for / while) 1. Initialization: int i = 1; Executes once at loop start 2. Condition Check: i <= N Evaluated BEFORE body! If false → 0 executions If true → proceed to Loop Body 3. Loop Body Statements Executes work (calculations, printing) 4. Update Expression: i++ Modifies variable → returns to Condition EXIT-CONTROLLED & DIGIT EXTRACTION do-while (Exit-Controlled): Guarantees AT LEAST 1 execution! Body runs first, condition evaluated at bottom. do { ... } while(condition); // Semicolon! DIGIT EXTRACTION PIPELINE: while (n > 0) { int digit = n % 10; // Extract last rev = rev * 10 + digit; // Reverse n = n / 10; // Strip last } JUMP STATEMENTS: break exits loop completely | continue skips current iteration

Chapter Summary & 10 Key Takeaways

Takeaway 1
Entry vs Exit Controlled: for and while evaluate the condition before entering the loop (0 min executions); do-while evaluates at the end (1 min execution).
Takeaway 2
Four Loop Elements: 1. Initialization, 2. Test Condition, 3. Loop Body, and 4. Update Expression.
Takeaway 3
Semicolon on do-while: The do-while loop requires a terminating semicolon after its condition (do { ... } while(condition);).
Takeaway 4
Null Loop Trap: Placing a semicolon immediately after a for loop header isolates the loop body, executing the body only once after the loop finishes.
Takeaway 5
The break Statement: Unconditionally terminates the loop and jumps to the first statement following the closing brace.
Takeaway 6
The continue Statement: Bypasses the rest of the current iteration and jumps directly to the update expression (for loop) or condition (while loop).
Takeaway 7
Digit Extraction Core: int digit = n % 10 extracts the last digit; n = n / 10 eliminates the last digit.
Takeaway 8
Reverse Formula: rev = rev * 10 + digit builds the reversed integer during digit extraction.
Takeaway 9
Palindrome & Armstrong: Palindrome compares reversed integer to original; Armstrong compares sum of cubed digits to original.
Takeaway 10
Prime Number Check: A number N is prime if it has exactly two factors (1 and N). Optimized by checking divisors up to Math.sqrt(N).

Check Your Understanding (Diagnostic Practice Questions)

Diagnostic questions testing core conceptual clarity. Answers are hidden initially — solve each problem first, then click to reveal the step-by-step verified solution.

1
How many times will the body of a do-while loop execute if the condition is false from the start?
Reveal Answer & Explanation
Answer: At least once. A do-while loop is exit-controlled; the loop body executes unconditionally before the test condition is evaluated at the bottom.
ICSE Computer Applications Marking Scheme
2
Differentiate between the "break" and "continue" statements in Java loops.
Reveal Answer & Explanation
Answer: "break" immediately terminates the entire loop and transfers control outside the loop block. "continue" skips only the remaining statements of the current iteration and immediately proceeds to the next iteration (updating the loop variable).
ICSE Computer Applications Marking Scheme
3
What will be the output of the following code snippet: "int i; for (i = 1; i <= 5; i++); System.out.println(i);"?
Reveal Answer & Explanation
Answer:
  1. The semicolon immediately following "for(i = 1; i <= 5; i++);" creates an empty (null) loop. The loop iterates internally until i reaches 6, after which the println statement executes once, printing 6.

ICSE Computer Applications Marking Scheme
4
Explain the mathematical purpose of "n % 10" and "n / 10" in digit extraction algorithms.
Reveal Answer & Explanation
Answer: "n % 10" extracts the rightmost (last) digit of an integer using the modulus operator. "n / 10" truncates and removes the rightmost digit using integer division.
ICSE Computer Applications Marking Scheme
5
What is an Armstrong Number? Give an example.
Reveal Answer & Explanation
Answer: An Armstrong number is an integer such that the sum of the cubes of its individual digits is equal to the number itself. For example, 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.
ICSE Computer Applications Marking Scheme
6
What is a "Duck Number" in Java programming?
Reveal Answer & Explanation
Answer: A Duck number is a positive integer that contains at least one zero, but does not begin with zero (e.g., 204, 3050, 102). Numbers like 012 are not duck numbers.
ICSE Computer Applications Marking Scheme
7
Convert the following while loop into an equivalent for loop: "int i = 1; while(i <= 10) { System.out.println(i); i += 2; }"
Reveal Answer & Explanation
Answer: for (int i = 1; i <= 10; i += 2) { System.out.println(i); }
ICSE Computer Applications Marking Scheme
8
What causes an "Infinite Loop"? Give one example using a while loop.
Reveal Answer & Explanation
Answer: An infinite loop occurs when the loop's test condition never evaluates to false, often due to an omitted or flawed update expression (e.g., "int i = 1; while(i > 0) { i++; }" or "while(true) { }").
ICSE Computer Applications Marking Scheme
Finished Studying This Chapter?
READY TO PRACTICE?

Timed CBT Practice Tests (Exam Simulator)

Put your concepts to the test with official curriculum-aligned Foundation and Advanced practice tests. Get instant accuracy scores, time metrics, and step-by-step verified explanations.