Overview
This unit explains looping (iterative) statements in Java, showing how they let a program repeat actions until a condition is met. Students learn the three main loop types—while, do-while and for—how to choose the right loop, how to control loop flow using break and continue, and how to avoid infinite loops. The unit covers counters and accumulators, nested loops, loop-based input validation, and simple patterns and table printing. Learning loops is essential because many real-world problems require repetition: processing lists, computing sums, generating patterns, or reading repeated input. Mastering loops helps students write shorter, clearer, and more efficient programs. This unit also introduces basic loop debugging strategies and good practice: initializing variables, updating loop counters, and keeping loop conditions correct. By the end, students will be able to write and trace loop-based programs, reason about termination, and use loops for practical tasks like calculating factorials, sums, and printing multiplication tables. The unit emphasises writing readable code with comments and using sample inputs to test edge cases, preparing students for board-level questions and later programming topics.
Learning Objectives
- Explain the purpose of a loop and identify situations where repetition is needed.
- Write and trace Java programs using while, do-while and for loops.
- Use break and continue statements to control loop execution.
- Detect and fix common loop errors including infinite loops and off-by-one mistakes.
- Apply nested loops to solve problems like printing patterns and tables.
- Use counters and accumulators within loops to compute sums, counts and averages.
- Validate user input using loops and implement simple menu-driven repetition.
- Read and interpret loop-related code and predict its output for given inputs.
Topics in this chapter
14 topics · tap a topic title to jump straight to it.
Introduction to Loops and Repetition
What is a loop?
A loop is a control structure that runs a set of statements repeatedly while a condition remains true. Programmers use loops whenever the same task must be carried out multiple times. Instead of writing the same statements again and again, a loop writes the action once and repeats it as needed. This saves time, reduces mistakes and makes programs easier to change.
Basic parts of a loop
Every loop typically has three parts: initialization, condition and update. Initialization prepares the starting values for variables the loop uses. The condition is a boolean expression checked before or after each repetition to decide whether to continue. The update changes loop variables so the condition will eventually become false. If the update is missing or incorrect, the loop might never stop.
Why loops matter
Many problems require repetition: summing a list of numbers, reading many student marks, finding an item in a collection, printing tables, or creating patterns of characters. Loops allow programs to handle any number of items without changing the program. Understanding loops is also essential before learning arrays, functions and more advanced algorithms.
Kinds of repetition
Sometimes we know how many times to repeat (for example, print 10 lines). Other times we repeat until some event happens (for example, until the user types "exit"). For known counts, counter-controlled loops are useful. For event-driven repetition, condition-controlled loops are suitable. Recognising which situation you have helps choose the right loop type.
Good habits
Always initialise loop variables before use, ensure updates move the condition towards termination, test loops with example values, and consider boundary cases like zero iterations. Add short comments explaining the purpose of a loop. When tracing or debugging, record the variable values for a few iterations to confirm the loop behaves as expected.
- Counting from 1 to 5: instead of five print statements, use a loop that prints and increments a counter.
- Repeating a prompt until user enters a valid age between 0 and 120.
- Summing the first 10 natural numbers with a loop and an accumulator variable.
- Printing the multiplication table for 7 by repeating multiplications from 1 to 10.
- Loop structure: initialize; while(condition) { body; update; }
- Ensure termination: update must change variables used in condition so condition can become false
The while Loop in Java
Syntax and basic idea
The while loop repeats a block while its boolean condition is true. In Java the form is:
while (condition) {
// statements
}
The condition is evaluated before each iteration. If it is false at the start, the loop body will not execute even once. This makes while suitable for repeating until a condition becomes true or false, when you cannot be sure how many times will be needed.
Initialization and update
Before entering a while loop, you should initialise any variables used in the condition. Inside the loop, update those variables so they move the condition towards becoming false. Forgetting to update the variable is the most common cause of infinite loops. For example, when counting, set int i = 1; and inside the loop do i++ to increment.
Common uses and examples
Use while to read until a sentinel value (such as -1) appears, validate input, or repeat a task until a condition holds. Example pattern: int n = readInt(); while (n != -1) { process(n); n = readInt(); } This reads numbers until the sentinel -1 is given.
Testing and corner cases
Always test a while loop with an input that makes the condition false immediately to ensure the body can be skipped properly. Also test with inputs that make the loop run once, and with multiple iterations. For loops that read user input, consider what happens if the user never gives the sentinel—might you need a maximum tries safeguard?
Practical tips
Use parentheses to make complex conditions clear. Comment what the loop does and why the specific condition is used. If the loop uses more than one variable in the condition, ensure each one is updated appropriately. When debugging, insert temporary prints showing the loop variables at the start or end of each iteration to see progression toward termination.
- Print numbers 1 to 5 using while: int i = 1; while (i <= 5) { System.out.println(i); i++; }
- Read integers until -1 entered: int n = readInt(); while (n != -1) { sum += n; n = readInt(); }
- Sum positive inputs until 0: int s=0; int x=readInt(); while(x!=0){ if(x>0) s+=x; x=readInt(); }
- while loop template: initialize; while(condition){ statements; update; }
- Pre-test loop: body may not execute if condition false initially
The do-while Loop in Java
Syntax and behaviour
The do-while loop executes the body first and then checks the condition. Java syntax is:
do {
// statements
} while (condition);
Because the condition is checked after the body, the loop runs at least once. This is useful when the body must execute once before evaluating whether to repeat.
Clear use cases
Typical uses include menus and prompts that must be shown at least once. For example, when you display a menu and then ask if the user wants to continue, the menu should appear at least one time. Input validation that requires the prompt before checking is another common scenario: you prompt the user, read the value, then decide whether to repeat.
Variable initialisation and scope
Because variables used in the condition are often assigned inside the do block, you must ensure that variables referenced after the loop are declared before it. For instance, int choice; do { choice = readInt(); } while (choice < 0); Here choice is declared before the loop so it can be tested and used later. Avoid relying on default values; make assignments explicit inside the body or before the loop.
Differences from while and practical conversion
do-while guarantees one execution. A while loop can be used instead by doing an initial action before the loop and then using while for further repetition. Converting do-while to while often requires an initial read or action outside the loop, which may be less elegant. Both can solve the same problems but choosing do-while sometimes makes intent clearer.
Common mistakes and corner cases
Because the body runs at least once, be cautious if the body performs critical operations that should only happen when some condition already holds. Ensure the post-condition is reachable; otherwise the loop could repeat many times. Test the case where the condition is false at the first check to confirm the loop does exactly one execution.
Debugging and tracing
When tracing a do-while, record the first execution separately from the repeated steps because the condition is checked afterwards. Use print statements if unsure how values change across iterations. Keep loop bodies short and maintain clear update points so the looping condition is easy to follow.
- Menu example: int choice; do { showMenu(); choice = readInt(); switch(choice){...} } while (choice != 0);
- Password prompt: do { pwd = readString(); } while (!pwd.equals(correct)); // asks at least once
- Read and sum non-negative numbers: do { n=readInt(); if(n>=0) sum+=n; } while(n>=0);
- do-while template: do { statements; } while(condition);
- Post-test loop: guarantees at least one execution of the body
The for Loop in Java
What is a for loop?
The for loop is a compact loop form that combines initialization, condition and update in a single header. Its Java form is:
for (initialization; condition; update) {
// body
}
It is most useful when the number of iterations is known beforehand or when using a counter simplifies the logic.
How it executes
Execution order is clear: first the initialization runs once, then the condition is tested. If the condition is true the body runs, then the update runs, returning control to test the condition again. This makes the for loop easy to reason about for fixed-count repetitions like "repeat 10 times" or "iterate over array indices".
Common forms and variants
The initialization and update parts can handle multiple variables: for (int i = 0, j = 10; i < j; i++, j--) { ... } Use different update steps such as i += 2, i-- or more complex expressions. You may declare the loop variable outside the for header if you need to use it after the loop ends. Use meaningful names if the loop represents something domain-specific, for example studentIndex instead of i.
Array traversal and for-each
for is commonly used to visit array indices: for (int i = 0; i < a.length; i++) { process(a[i]); } Java also provides a for-each form: for (Type item : array) { ... } which is concise and avoids index mistakes but does not give the index. Choose the form that suits the problem.
Errors and off-by-one traps
Off-by-one errors arise when deciding whether to use < or <=, or choosing wrong start/end values. When iterating arrays, remember indices run from 0 to length-1, so use i < a.length. Also avoid changing the loop variable inside the body unexpectedly; keep updates in the update clause when possible to maintain clarity.
Readability and best practice
Keep the for header simple and avoid heavy expressions in the condition. Use braces {} always, even for single-statement bodies, to prevent mistakes when modifying code. For loops express intent well when counting or indexing, so prefer them for these tasks and use comments to explain non-obvious choices.
- Print numbers 1 to 10: for (int i = 1; i <= 10; i++) { System.out.println(i); }
- Sum first n numbers: int sum = 0; for (int i = 1; i <= n; i++) sum += i;
- Loop with step: for (int i = 0; i < 10; i += 2) System.out.print(i + " ");
- for loop template: for(initialization; condition; update){ body }
- Execution order: initialization → condition check → body → update → repeat
Comparing while, do-while and for
Overview
While, do-while and for are three loop forms that serve similar purposes but differ in control style and readability. Understanding their differences helps you pick the most appropriate one for a task and write clearer programs. Each has strengths: while for condition-driven repetition, do-while for at-least-one execution, and for for counter-controlled repetition.
Pre-test vs post-test
The while loop is pre-test: it evaluates the condition before running the body. If the condition is false from the start the body never runs. The do-while loop is post-test: it runs the body once and then evaluates the condition, so it always runs at least once. Remember this when the first execution is important, for example when prompting a user. for is also pre-test (the condition is checked before each body run) but it groups the loop control parts in one line so it is concise for counting cases.
When to choose each
Choose for when iteration count is known or when you use an index (for arrays or fixed ranges). Choose while when repetition depends on a condition that may already be true or false and you might not execute at all (e.g., read until sentinel). Choose do-while when the action must happen once, for example showing an initial menu or prompt before checking whether to repeat.
Readability and maintenance
Pick the structure that most clearly expresses the intention. A for loop immediately shows start, end and step which helps readers understand the range. A while loop highlights the condition that controls repetition. A do-while signals that the first run is mandatory. Consistent style and comments reduce maintenance problems.
Converting between forms
You can usually rewrite one loop type in terms of another: for(init;cond;upd) {body} ≡ init; while(cond){ body; upd; } Converting do-while to while requires performing the first iteration before the while loop, which may be less neat. Although conversion is possible, prefer the structure that keeps code cleaner and avoids extra initial code.
Common errors
Off-by-one mistakes occur when using wrong comparison operators or start values. Infinite loops happen when updates are missing or move in the wrong direction. Using the form that matches the problem reduces the chance of these mistakes. Test with edge cases such as zero iterations or immediate exit to verify behaviour.
- Convert for to while: for(int i=0;i<3;i++) body; → int i=0; while(i<3){ body; i++; }
- Use while to read until a sentinel; use do-while to show a menu at least once.
- Replace a while-read pattern with do-while to ensure prompt displays before validation
- Equivalence: for(init;cond;update){body} ≡ init; while(cond){ body; update; }
Loop Control Statements: break and continue
Purpose and behaviour
break and continue are statements that alter the normal flow inside loops. They make control flow more flexible: break stops the loop completely, while continue skips the rest of the current iteration and proceeds to the next one. Used carefully, they simplify code; used carelessly, they can reduce clarity.
break in detail
When break executes, control jumps to the statement immediately after the innermost loop. This is useful when a desired result is found and further searching is unnecessary. For example, when searching an array for a key, break stops further checks and can improve efficiency. In switch statements break also exits the switch; remember that break’s meaning depends on its enclosing construct.
continue in detail
continue causes the loop to skip remaining statements in the current iteration and go to the next iteration. In a for loop the update expression runs after continue and before the next condition check; in a while or do-while loop continue jumps to the condition check. continue is useful to skip over invalid or unwanted cases without nesting the main logic inside large if blocks.
Nested loops and scope
Both break and continue affect only the innermost loop that contains them. If you need to exit an outer loop from an inner loop, common approaches are setting a boolean flag that outer loop checks, or using a labeled break in Java (advanced). Example flag pattern: boolean found=false; for(...) { for(...) { if(cond){ found=true; break; } } if(found) break; }
Readability considerations
Use break and continue where they make the logic clearer, such as avoiding deep nesting or handling special cases early. Add comments explaining why an early exit or skip is necessary. Overuse can scatter exit points and make reasoning about code harder, so prefer clear loop conditions when possible.
Examples and debugging
Example of break: for(i=0;i
- Search with break: for(int i=0;i<n;i++){ if(a[i]==key){ System.out.println(i); break; } }
- Skip even numbers: for(int i=1;i<=10;i++){ if(i%2==0) continue; System.out.print(i+" "); }
- Use flag to exit outer loop when inner loop finds result
- break; // exits the nearest enclosing loop immediately
- continue; // skips the remaining statements in the current iteration and proceeds
Avoiding Infinite Loops and Off-by-One Errors
Understanding infinite loops
An infinite loop keeps running because its terminating condition never becomes false. This occurs when loop variables are not updated, are updated incorrectly, or when the condition logic can never be satisfied. Infinite loops can make a program unresponsive; they must be avoided unless the loop is designed to run until an external event ends it (advanced cases).
Typical causes with examples
1) Missing update: int i = 1; while (i <= 5) { System.out.println(i); } // i never changes. 2) Wrong update direction: while (i > 0) { i++; } will increase i so condition stays true. 3) Incorrect condition: using the wrong relational operator or forgetting to consider boundary values can prevent termination.
Off-by-one errors explained
Off-by-one is a frequent mistake that makes a loop run one time too few or too many. It usually stems from incorrect choice between < and <=, or wrong start index. For arrays in Java, indices go from 0 to a.length - 1. Using <= a.length or starting from 1 when array is 0-indexed causes IndexOutOfBounds exceptions. For loops intended to run N times, commonly use for (int i = 0; i < N; i++) so exactly N iterations occur.
Techniques to avoid errors
- Plan the values your counter should take and include a small example to confirm first and last iterations.
- Write test cases for boundary inputs such as N = 0, N = 1 and large N.
- Prefer clear loop headers and keep updates visible; avoid hiding updates in complex expressions inside the body.
- When using arrays, always use i < a.length rather than i <= a.length.
Debugging strategies
Insert temporary print statements to display loop variables during initial iterations; this helps locate where progress stops. If suspicion of infinite loop exists, include a temporary safety check like if (iterationCount++ > 10000) break; to avoid hang while debugging. For off-by-one, manually trace the first few iterations and the final intended value to check correctness.
Best practices
Keep loops simple and comment expected bounds. Use descriptive names like startIndex and endIndex, and test thoroughly. With careful planning, tracing and tests, infinite loops and off-by-one mistakes become rare and easier to fix.
- Infinite loop example: while(true){ // ensure a break or exit condition exists }
- Array off-by-one: for(int i=0;i<=a.length;i++) causes IndexOutOfBounds; correct i<a.length
- Test with n=0 and n=1 to verify loops that run n times behave correctly
- To run body N times: for(int i=0;i<N;i++) { ... }
- Array valid indices: 0 to length-1
Counters and Accumulators
Definitions and purpose
A counter is a variable that counts occurrences, such as how many numbers in a list are even. An accumulator collects a running total, for example the sum of marks. Both patterns are essential in loop programming: counters count events and accumulators aggregate values.
Initialization and identity values
Always initialise counters to zero. For accumulators use an identity value appropriate to the operation: for sums use 0, for products use 1. Improper initialisation leads to incorrect results. For averages, keep both sum and count so you can compute average = (double) sum / count after verifying count > 0.
Common usage patterns
Counting pattern: initialize count=0; loop through items; if(item meets condition) count++; Accumulation pattern: initialize sum=0; for each item sum += item. These patterns often appear together in tasks like computing average, where sum and count are updated together.
Practical example
Suppose you read student marks until a sentinel value -1. Start sum=0 and count=0. For each mark >=0 add to sum and increment count. After the loop, if count>0 print average = (double)sum/count; otherwise report no data. This pattern demonstrates safe handling when input may be empty.
Edge cases and limits
Watch for division by zero when computing averages and integer overflow with very large sums. For Class 9 tasks numbers are small, but understanding these limitations is useful. When using an accumulator for product, be careful of zero values which make the product zero.
Readability
Use clear variable names like positiveCount, totalMarks or scoreSum. Add a brief comment describing the meaning of counters and accumulators used. This helps graders and peers quickly understand your logic in school programs and exams.
- Count evens: int count=0; for(int i=0;i<a.length;i++){ if(a[i]%2==0) count++; }
- Sum numbers: int sum=0; for(int i=1;i<=n;i++){ sum+=readInt(); }
- Average: if(count>0) average=(double)sum/count; else handle empty case
- sum = sum + value (or sum += value)
- average = (double)sum / count, provided count > 0
Nested Loops and Pattern Printing
Nested loops explained
Nested loops are loops placed inside other loops. The inner loop runs fully for each single iteration of the outer loop. This structure is useful when working with two-dimensional data (rows and columns) or when printing patterns that require repeated columns for each row.
How to structure nested loops
Use the outer loop to represent rows and the inner loop for columns. Use distinct loop variables for each level, commonly i for the outer loop and j for the inner loop. For a pattern of R rows and C columns: for (int i = 1; i <= R; i++) { for (int j = 1; j <= C; j++) { // print element } System.out.println(); } The inner loop prints items for one row and then a newline moves to the next row.
Pattern examples
Rectangle: print the same number of stars in each row. Triangle: make the inner loop limit depend on the outer loop index so each row has an increasing number of stars. Number patterns: print numbers that depend on i and j, such as printing j or i*j. Practising several small patterns builds confidence with nested loops.
Performance and counting iterations
Be aware nested loops multiply the number of iterations: if outer runs N times and inner M times, the body runs N×M times. For small values used in Class 9 tasks this is fine, but understanding this helps reason about runtime. Avoid unnecessarily deep nesting to keep programs efficient and readable.
Formatting output
Use System.out.print to print items in the same row and use System.out.println after the inner loop to move to the next line. Use spacing or tabs to align columns when printing tables. For centered or more complex shapes, print spaces first using another inner loop to position characters.
Practice technique
Draw the output grid on paper and label each cell with the pair (i,j) to see what should be printed. Then write the nested loops and check the produced output against the drawing. Small changes in inner loop limits create many useful patterns.
- 3x4 rectangle of stars: for(i=1;i<=3;i++){ for(j=1;j<=4;j++){ System.out.print("* "); } System.out.println(); }
- Right-angled triangle: for(i=1;i<=4;i++){ for(j=1;j<=i;j++){ System.out.print("* "); } System.out.println(); }
- Multiplication table 1..5: for(i=1;i<=5;i++){ for(j=1;j<=10;j++){ System.out.print((i*j)+" "); } System.out.println(); }
- Total iterations of nested loops: if outer runs N times and inner M times then N × M total body executions
Looping with Arrays and Strings
Why arrays and strings need loops
Arrays contain many values and strings contain many characters. To process each element or character we usually use a loop. Traversal lets us compute sums, find maximums, count occurrences or transform data. A for loop that uses an index or a for-each loop are common choices for arrays; for strings we use character access methods.
Array traversal patterns
Given an int[] a, visit every element with: for (int i = 0; i < a.length; i++) { // use a[i] } This form gives the index and allows both reading and writing array elements. Java also provides a for-each loop: for (int v : a) { // use v } which is shorter and reduces index mistakes, but does not provide position. Choose index-based loops when you need the index for computations like reversing or swapping elements.
Common array tasks
Find sum, minimum, maximum, count elements meeting a condition, and search for a value. When searching, stop early with break if the item is found. For empty arrays check a.length == 0 before accessing a[0] to avoid runtime errors. Update elements in-place when required by assigning to a[i].
Processing strings with loops
Strings are processed character by character using s.charAt(i) where i runs from 0 to s.length()-1. Typical tasks: counting vowels, checking digits, reversing a string, and testing palindromes. To reverse, iterate from s.length()-1 down to 0 and build a new string. For palindrome checks compare characters from both ends up to the midpoint.
Examples and careful points
Reversing via concatenation is simple: String rev = ""; for (int i = s.length() - 1; i >= 0; i--) rev += s.charAt(i); For long strings use StringBuilder for efficiency, but for Class 9 concatenation is acceptable. Remember strings are immutable in Java—operations produce new strings rather than change the original.
Edge cases and testing
Handle empty arrays and empty strings explicitly. When computing averages ensure a.length > 0. When reading user input for arrays, verify expected count and guard against invalid or missing values. Practice tracing array and string loops to understand index behaviour and prevent off-by-one errors.
- Iterate array: for(int i=0;i<a.length;i++){ System.out.println(a[i]); }
- For-each: for(int v : a){ sum += v; }
- Reverse string: String rev=""; for(int i=s.length()-1;i>=0;i--) rev += s.charAt(i);
- Array valid indices: 0 to a.length - 1
- String indices: first = 0, last = s.length() - 1
Loop-based Input Validation, Menus and Small Projects
Input validation using loops
Loops are often used to ensure user input meets requirements. Repeatedly ask the user for a value until it fits a valid range or format. Use a do-while loop if the prompt should appear at least once, or while if you may skip prompting under some conditions. Always give clear error messages and examples of valid input so the user knows what is expected.
Menu-driven programs
Menus let users choose actions repeatedly until they pick an exit option. A common pattern uses a do-while: do { display menu; choice = readInt(); switch(choice) { case 1: ...; break; ... } } while(choice != exitValue); This keeps the program interactive and controlled by user choices. Each menu option may itself use loops for tasks like data entry or processing.
Combining validation and menus
Within a menu option you may need further validation, such as ensuring marks are between 0 and 100. Use nested loops carefully and provide a way to return to the main menu. If input may be malformed, consider limiting retries to avoid infinite prompting and give the option to cancel.
Small project ideas and structure
1) Multiplication table generator: ask N and print tables 1..N with nested loops. 2) Number statistics: read numbers until sentinel -1, then print count, sum, average, min and max. 3) Simple quiz: present questions in a loop and keep score; allow retrying incorrect questions. For each project plan inputs, outputs and which loops are needed before coding.
Design and testing tips
Write pseudocode that describes loops and conditions, then implement small parts and test iteratively. Test menus for all choices including invalid options, and test validation loops with bad inputs to ensure messages and retries behave as intended. Include sample runs as comments to explain expected interactions.
User friendliness and clarity
Keep prompts clear, show examples of valid input, and display helpful messages on invalid input. Use simple formatting to make menu options easy to read. For school work, add comments describing each loop’s purpose so teachers can follow your logic when assessing programs.
- Age validation: int age; do{ age=readInt(); if(age<0||age>120) System.out.println("Invalid"); } while(age<0||age>120);
- Menu loop: do{ printMenu(); choice=readInt(); switch(choice){ case 1: ... } } while(choice!=0);
- Statistics program: read numbers until -1 sentinel and update sum, count, min and max
- Validation loop template: do{ input = read(); } while(!isValid(input));
Tracing, Dry Run and Exam-style Practice
What tracing is and why it helps
Tracing or dry running means following a program step by step on paper and recording the values of variables after each statement. This practice helps predict program output, detect logic errors and understand loop execution. Exam questions often ask for the result of tracing, so learning to trace clearly is important.
How to trace loops effectively
1) Write initial values of all variables before the loop starts. 2) For each iteration, note the condition result, record actions inside the body and any updates at the end. 3) Continue until the loop condition becomes false and state final values and outputs. Use a neat table with columns for iteration number and each variable to avoid confusion. Include outputs in a separate column as they occur.
Special attention for different loop types
For while loops show the condition check before listing body actions. For do-while mark the first iteration separately or note that body runs before the condition. For for loops ensure you show initialization, condition on each check, body actions and the update step; many tracing errors come from missing the update position.
Tracing nested loops
Include both indices in the table, for example i and j, and list ordered pairs visited. Small examples help: draw a 3×3 grid and label cells with (i,j) to visualise the order. Trace outputs produced by inner loop prints so you can produce the exact output sequence required by the question.
Exam strategies and common tasks
Practice tracing sums, factorials, string operations, pattern printing and array traversals. For program writing questions in exams, first write a short pseudocode describing loop behaviour, then write clear Java code with initialisation, condition and updates. For error correction questions, point to the line causing infinite loop or off-by-one, show corrected code and explain the fix briefly.
Practice routine
Create a set of small problems and time yourself tracing and writing solutions. Build a checklist: initialisation correct, loop condition logical, update present, body statements correct, final output verified. This routine improves speed and accuracy for board exams and school tests.
- Trace: int sum=0; for(int i=1;i<=4;i++){ sum+=i; } → iterations give sum 1,3,6,10 final sum=10
- Dry run nested loops by listing pairs (i,j) and the printed values in order
- Practice converting a do-while into equivalent while and trace both
Common Loop Problems: Sum, Factorial and GCD
Sum of first n numbers
Computing the sum 1 + 2 + ... + n is a frequent exercise. A loop solution uses an accumulator: initialize sum = 0, then loop a counter from 1 to n adding the counter to sum on each iteration. After the loop sum holds the result. Ensure the loop bounds are correct and test n = 0 and n = 1 as edge cases.
Factorial using loops
Factorial n! equals 1×2×...×n. Use an accumulator product initialized to 1. Loop i from 1 to n and multiply product by i on each iteration. For n = 0 define 0! = 1 by convention. Factorials grow quickly; in Class 9 use small n to avoid integer overflow. Always test n = 0 and n = 1 when writing the program.
GCD via loops
Euclid’s algorithm using the modulo operator is efficient: while (b != 0) { int r = a % b; a = b; b = r; } result is a. A simpler subtraction-based method is useful for understanding: while (a != b) { if (a > b) a -= b; else b -= a; } When the loop ends both variables equal the GCD. Explain which variant you use and test with different inputs.
Design approach
1) Identify if the number of iterations is known: use for when counting steps (sum, factorial). 2) Use while when termination depends on changing values (GCD). 3) Initialise accumulators and counters appropriately. 4) Handle edge cases and output clearly. 5) Trace with small numbers before running to confirm logic.
Testing and example inputs
Sum: test n=0 (sum=0), n=1 (sum=1), n=5 (sum=15). Factorial: test n=0 (1), n=4 (24). GCD: test equal numbers (gcd is number), co-prime numbers (gcd=1), and larger pairs to ensure loop terminates. For classroom tasks write comments and show sample runs for clarity.
- Sum: int sum=0; for(int i=1;i<=n;i++) sum += i;
- Factorial: int fact=1; for(int i=1;i<=n;i++) fact *= i; // 0! = 1
- GCD by subtraction: while(a!=b){ if(a>b) a=a-b; else b=b-a; } // gcd=a
- Factorial definition: n! = 1×2×...×n with 0! = 1
- Sum by loop: sum = Σ i for i from 1 to n computed iteratively
Good Coding Style, Debugging and Final Tips
Readability and naming
Use meaningful variable names like count, total, index, sum instead of single letters when purpose is not obvious. Good names make loops easier to read and understand. Keep loop bodies short and move complex logic to separate helper methods if allowed.
Formatting and braces
Always use braces {} for loop bodies even if they contain a single statement. Proper indentation and spacing increase clarity: for (int i = 0; i < n; i++) { ... } Use spaces around operators and after commas to improve readability.
Comments
Add short comments describing the loop's purpose: // count positive numbers in the list. Avoid obvious comments like // i++ increments i. Explain why boundary values are chosen or why a sentinel is used so readers quickly understand design decisions.
Debugging techniques
When a loop behaves unexpectedly, trace its first few iterations on paper or add print statements that show loop variables at key points. For suspected infinite loops include a temporary guard like if(iteration>10000) break; to stop runaway behaviour during testing. Check that all variables used in conditions are updated properly and that array indices are within valid ranges.
Testing strategy
Test loops with edge cases: zero iterations (n=0), single iteration (n=1), and typical multiple iterations. Test with invalid inputs where validation is required. For nested loops test smallest and slightly larger sizes to ensure pattern printing and spacing are correct. Keep a set of sample inputs and expected outputs as comments.
Final advice
Prefer the loop that clearly matches the problem: for for counting and array traversal, while for condition-driven repetition, do-while when one execution is required. Keep code simple, comment intent, and practice tracing and writing small programs. These habits prepare you for school exams and further programming topics.
- Use descriptive names: int positiveCount instead of int c when counting positives
- Comment header: // Print right-angled triangle of size n before the loop
- Always use braces to avoid mistakes when modifying code later
Key Concepts
- Loop
- A construct that repeats a block of code while a condition holds.
- while loop
- A pre-test loop that checks its condition before executing the body.
- do-while loop
- A post-test loop that executes the body at least once and then tests the condition.
- for loop
- A loop with initialization, condition and update in one header, used for counter-controlled repetition.
- break
- A statement that immediately exits the nearest enclosing loop.
- continue
- A statement that skips the rest of the current iteration and proceeds to the next one.
- Infinite loop
- A loop that never terminates because its condition never becomes false.
- Counter
- A variable that counts occurrences, usually incremented in a loop.
- Accumulator
- A variable that collects a running total or aggregate value during loop execution.
- Nested loop
- A loop inside another loop, producing multiple levels of repetition.
- Off-by-one error
- A bug where a loop runs one time too many or too few due to incorrect boundary conditions.
- Array traversal
- Using a loop to visit each element of an array.
- Trace (dry run)
- Manually following program execution step by step to record variable values.
- Sentinel
- A special value used to signal the end of input in a loop.
- Index
- An integer representing position in an array or string, starting at 0 in Java.
Practice Questions
-
Write a for loop to print numbers from 1 to 10. / 1 से 10 तक संख्याएँ प्रिंट करने के लिए एक for लूप लिखिए।
Show answer
for (int i = 1; i <= 10; i++) { System.out.println(i); } / for (int i = 1; i <= 10; i++) { System.out.println(i); }
-
What is the difference between while and do-while loops? / while और do-while लूप में क्या अंतर है?
Show answer
while checks the condition before executing the body (pre-test) and may not run the body at all; do-while executes the body first and checks the condition afterwards (post-test), so it runs at least once. / while शर्त को बॉडी चलाने से पहले जाँचता है (pre-test) और बॉडी कभी न भी चल सकती है; do-while पहले बॉडी चलाता है और बाद में शर्त जाँचता है (post-test), इसलिए यह कम-से-कम एक बार चलता है।
-
Trace the output: int i=1; int sum=0; while(i<=3){ sum+=i; i++; } System.out.println(sum); / आउटपुट ट्रेस कीजिए: int i=1; int sum=0; while(i<=3){ sum+=i; i++; } System.out.println(sum);
Show answer
Iterations: i=1 sum=0→1, i→2; i=2 sum=1→3, i→3; i=3 sum=3→6, i→4; loop ends. Output: 6. / पुनरावृत्तियाँ: i=1 sum=0→1, i→2; i=2 sum=1→3, i→3; i=3 sum=3→6, i→4; लूप समाप्त। आउटपुट: 6।
-
Give a program idea that uses nested loops and explain the role of each loop. / एक ऐसा प्रोग्राम बताइए जिसमें nested loops उपयोग होते हैं और प्रत्येक लूप की भूमिका समझाइए।
Show answer
Multiplication table generator: outer loop runs through table numbers (1 to N), inner loop runs multipliers (1 to 10). Outer loop selects which table to print; inner loop computes and prints each line of that table. / गुणन तालिका जनरेटर: बाहरी लूप तालिका संख्या (1 से N) पर चलता है, आंतरिक लूप गुणक (1 से 10) पर चलता है। बाहरी लूप चुनता है किस तालिका को प्रिंट करना है; आंतरिक लूप उस तालिका की प्रत्येक पंक्ति की गणना और प्रिंट करता है।
-
Write code to sum numbers read until the user enters 0. / उपयोगकर्ता 0 दर्ज करने तक पढ़ी गई संख्याओं का योग करने के लिए कोड लिखिए।
Show answer
int sum = 0; int n = readInt(); while (n != 0) { sum += n; n = readInt(); } System.out.println(sum); / int sum = 0; int n = readInt(); while (n != 0) { sum += n; n = readInt(); } System.out.println(sum);
-
Explain what continue does inside a loop with an example. / किसी लूप के अंदर continue क्या करता है, एक उदाहरण के साथ समझाइए।
Show answer
continue skips the rest of the current iteration and moves to the next one. Example: for(int i=1;i<=5;i++){ if(i==3) continue; System.out.print(i); } This prints 1 2 4 5 because when i==3 the print is skipped. / continue वर्तमान पुनरावृत्ति के शेष भाग को छोड़ देता है और अगले पर चला जाता है। उदाहरण: for(int i=1;i<=5;i++){ if(i==3) continue; System.out.print(i); } यह 1 2 4 5 प्रिंट करेगा क्योंकि i==3 पर प्रिंट छोड़ दिया जाता है।
-
Find the error: for(int i=0;i<=arr.length;i++) { System.out.println(arr[i]); } Explain and correct. / त्रुटि खोजिए: for(int i=0;i<=arr.length;i++) { System.out.println(arr[i]); } समझाइए और सुधार कीजिए।
Show answer
Error: using <= arr.length causes IndexOutOfBounds because valid indices are 0 to arr.length-1. Correct loop: for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } / त्रुटि: <= arr.length का उपयोग IndexOutOfBounds देता है क्योंकि वैध सूचकांक 0 से arr.length-1 तक होते हैं। सही लूप: for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); }
-
Write a loop to count how many even numbers are in an integer array. / एक लूप लिखिए जो एक integer array में कितनी सम संख्याएँ हैं, गिनती करे।
Show answer
int count = 0; for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) count++; } System.out.println(count); / int count = 0; for (int i = 0; i < a.length; i++) { if (a[i] % 2 == 0) count++; } System.out.println(count);
-
Trace this nested loop output: for(int i=1;i<=2;i++){ for(int j=1;j<=3;j++){ System.out.print(i+""+j+" "); } } / इस nested लूप का आउटपुट ट्रेस कीजिए: for(int i=1;i<=2;i++){ for(int j=1;j<=3;j++){ System.out.print(i+""+j+" "); } }
Show answer
Order of pairs printed: i=1 j=1 → 11, j=2 → 12, j=3 → 13; then i=2 j=1 → 21, j=2 → 22, j=3 → 23. Output: 11 12 13 21 22 23. / जोड़े प्रिंट होने का क्रम: i=1 j=1 → 11, j=2 → 12, j=3 → 13; फिर i=2 j=1 → 21, j=2 → 22, j=3 → 23। आउटपुट: 11 12 13 21 22 23।
-
Why is it important to test loop programs with edge cases like n=0 or n=1? / n=0 या n=1 जैसे किनारे मामले के साथ लूप प्रोग्रामों का परीक्षण करना क्यों महत्वपूर्ण है?
Show answer
Edge cases check that loops behave correctly when iterations are zero or minimal. They reveal off-by-one bugs, division by zero when computing averages, or invalid array access. Testing these ensures program correctness for all inputs. / किनारे मामला जाँचते हैं कि लूप शून्य या न्यूनतम पुनरावृत्ति पर सही व्यवहार करते हैं। वे off-by-one त्रुटियों, औसत निकालते समय शून्य से विभाजन, या अवैध array पहुँच जैसी समस्याएँ उजागर करते हैं। इन्हें टेस्ट करने से सभी इनपुट के लिए सहीपन सुनिश्चित होता है।
-
Write code to reverse a string using a loop. / किसी स्ट्रिंग को लूप का उपयोग करके उलटना (reverse) करने वाला कोड लिखिए।
Show answer
String s = readString(); String rev = ""; for (int i = s.length() - 1; i >= 0; i--) { rev += s.charAt(i); } System.out.println(rev); / String s = readString(); String rev = ""; for (int i = s.length() - 1; i >= 0; i--) { rev += s.charAt(i); } System.out.println(rev);
Related Laws & Principles
Explore allFoundational laws & principles connected to this chapter — tap to open in the Laws Explorer.