Java Control Structures: Loops, Conditionals, and Logic Flow

Java Control Structures: Loops, Conditionals, and Logic Flow

This section focuses on reading Java code that demonstrates control structures - the building blocks that control how your program flows and makes decisions.

Reading Strategy: For control structures, always trace through the logic step by step. Pay attention to conditions, loop boundaries, and how variables change over time.

How to Read Control Structure Code

Start with the conditions - Understand what triggers each branch Trace execution paths - Follow different scenarios through the code Monitor variable changes - See how values change in loops and conditions Recognize patterns - Look for common control structure idioms

Example 1: Complex Conditional Logic with Grade Processing

Code to Read:

  1public class GradeProcessor {
  2    
  3    public static void processStudentGrades() {
  4        // Array of test scores to process
  5        int[] scores = {95, 78, 82, 67, 91, 88, 45, 92, 76, 89};
  6        
  7        // Initialize counters and accumulators
  8        int totalPoints = 0;
  9        int bonusPoints = 0;
 10        int failedTestCount = 0;
 11        int[] gradeCounts = new int[5];  // Count A, B, C, D, F grades
 12        
 13        System.out.println("=== Processing Individual Scores ===");
 14        
 15        // Enhanced for loop to process each score
 16        for (int i = 0; i < scores.length; i++) {
 17            int score = scores[i];
 18            totalPoints += score;
 19            
 20            System.out.print("Test " + (i + 1) + ": " + score + " - ");
 21            
 22            // Nested conditional structure for grade assignment
 23            char letterGrade;
 24            String performance;
 25            
 26            if (score >= 90) {
 27                letterGrade = 'A';
 28                performance = "Excellent";
 29                gradeCounts[0]++;
 30                
 31                // Bonus points for exceptional performance
 32                if (score >= 95) {
 33                    int bonus = 2;
 34                    bonusPoints += bonus;
 35                    System.out.println(letterGrade + " (" + performance + ") +bonus: " + bonus);
 36                } else {
 37                    System.out.println(letterGrade + " (" + performance + ")");
 38                }
 39                
 40                // Extra bonus for perfect score
 41                if (score == 100) {
 42                    int perfectBonus = 5;  // Additional bonus
 43                    bonusPoints += perfectBonus;
 44                    System.out.println("    Perfect score bonus: +" + perfectBonus + " points!");
 45                }
 46            } else if (score >= 80) {
 47                letterGrade = 'B';
 48                performance = "Good";
 49                gradeCounts[1]++;
 50                System.out.println(letterGrade + " (" + performance + ")");
 51            } else if (score >= 70) {
 52                letterGrade = 'C';
 53                performance = "Satisfactory";
 54                gradeCounts[2]++;
 55                System.out.println(letterGrade + " (" + performance + ")");
 56            } else if (score >= 60) {
 57                letterGrade = 'D';
 58                performance = "Needs Improvement";
 59                gradeCounts[3]++;
 60                System.out.println(letterGrade + " (" + performance + ")");
 61            } else {
 62                letterGrade = 'F';
 63                performance = "Failed";
 64                gradeCounts[4]++;
 65                failedTestCount++;
 66                System.out.println(letterGrade + " (" + performance + ")");
 67            }
 68        }
 69        
 70        // Calculate statistics
 71        double averageScore = (double) totalPoints / scores.length;  // Cast to avoid integer division
 72        double adjustedAverage = (double) (totalPoints + bonusPoints) / scores.length;
 73        
 74        // Determine overall performance using compound conditions
 75        String overallGrade;
 76        String recommendation;
 77        
 78        if (averageScore >= 90 && failedTestCount == 0) {
 79            overallGrade = "Outstanding";
 80            recommendation = "Excellent work! Consider advanced coursework.";
 81        } else if (averageScore >= 80 && failedTestCount <= 1) {
 82            overallGrade = "Strong";
 83            recommendation = "Good performance. Keep up the good work!";
 84        } else if (averageScore >= 70 || (averageScore >= 65 && bonusPoints > 0)) {
 85            overallGrade = "Satisfactory";
 86            recommendation = "Adequate progress. Focus on consistent improvement.";
 87        } else if (failedTestCount > scores.length / 2) {  // More than half failed
 88            overallGrade = "Concerning";
 89            recommendation = "Significant struggles. Recommend tutoring and study group.";
 90        } else {
 91            overallGrade = "Needs Improvement";
 92            recommendation = "Some challenges noted. Additional support recommended.";
 93        }
 94        
 95        // Create detailed report
 96        System.out.println("\n=== Grade Report ===");
 97        System.out.println("Total tests: " + scores.length);
 98        System.out.printf("Average score: %.1f%n", averageScore);  // printf formatting
 99        
100        if (bonusPoints > 0) {
101            System.out.println("Bonus points earned: " + bonusPoints);
102            System.out.printf("Adjusted average: %.1f%n", adjustedAverage);
103        }
104        
105        System.out.println("Overall grade: " + overallGrade);
106        System.out.println("Recommendation: " + recommendation);
107        
108        // Show grade distribution using loops and conditionals
109        System.out.println("\nGrade Distribution:");
110        String[] gradeLetters = {"A", "B", "C", "D", "F"};
111        String[] symbols = {"✓", "✓", "○", "○", "✗"};  // Different symbols for different grades
112        
113        for (int i = 0; i < gradeCounts.length; i++) {
114            if (gradeCounts[i] > 0) {
115                double percentage = ((double) gradeCounts[i] / scores.length) * 100;
116                System.out.printf("  %s %s: %d tests (%.1f%%)%n", 
117                    symbols[i], gradeLetters[i], gradeCounts[i], percentage);
118            }
119        }
120        
121        // Warning for failed tests using conditional
122        if (failedTestCount > 0) {
123            System.out.println("\n⚠️  Failed " + failedTestCount + " out of " + scores.length + " tests");
124            System.out.println("   Consider retaking these assessments.");
125        }
126    }
127    
128    public static void main(String[] args) {
129        processStudentGrades();
130    }
131}

What to Notice:

Multi-Level Conditional Logic

Nested if-else structures:

  • Main grade assignment (if (score >= 90))
  • Bonus calculation within grade categories (if (score >= 95))
  • Special case handling (if (score == 100))

Compound boolean expressions:

  • averageScore >= 90 && failedTestCount == 0 - requires both conditions
  • averageScore >= 70 || (averageScore >= 65 && bonusPoints > 0) - complex OR logic with grouped conditions
Loop Patterns and Array Processing

Enhanced for loop: for (int i = 0; i < scores.length; i++) - standard indexed iteration

  • Access both index (i) and value (scores[i])
  • Used when you need position information

Array accumulation patterns:

  • totalPoints += score - running total
  • gradeCounts[1]++ - frequency counting
  • failedTestCount++ - conditional counting
Type Casting and Calculations

Explicit casting: (double) totalPoints / scores.length

  • Prevents integer division truncation
  • Ensures accurate decimal results

Formatted output: System.out.printf("%.1f%n", averageScore)

  • %.1f formats to 1 decimal place
  • %n is platform-independent newline
Variable Scope and Lifecycle

Loop-local variables: char letterGrade, String performance declared inside loop

  • New instances created each iteration
  • Only accessible within loop body

Method-level arrays: gradeCounts, scores accessible throughout method

  • Arrays maintain state across loop iterations

Trace Through Example:

 1// First iteration (i=0, score=95):
 2totalPoints = 0 + 95 = 95
 3score >= 90  true  letterGrade = 'A'
 4score >= 95  true  bonusPoints = 0 + 2 = 2
 5gradeCounts[0] = 0 + 1 = 1
 6
 7// Second iteration (i=1, score=78):
 8totalPoints = 95 + 78 = 173
 9score >= 90  false
10score >= 80  false  
11score >= 70  true  letterGrade = 'C'
12gradeCounts[2] = 0 + 1 = 1
13
14// Final calculations:
15averageScore = 173.0 / 2 = 86.5 (with proper casting)
16failedTestCount == 0 && averageScore >= 80  "Strong" grade

Example 2: Different Loop Types and Patterns

Code to Read:

 1public class LoopDemonstration {
 2    
 3    public static void demonstrateLoopTypes() {
 4        System.out.println("=== Loop Types Demonstration ===");
 5        
 6        // Standard for loop
 7        System.out.println("1. Standard for loop (counting):");
 8        for (int i = 1; i <= 5; i++) {
 9            System.out.print(i + " ");
10        }
11        System.out.println();
12        
13        // Enhanced for loop (for-each)
14        System.out.println("2. Enhanced for loop (for-each):");
15        int[] numbers = {10, 20, 30, 40, 50};
16        for (int number : numbers) {
17            System.out.print(number + " ");
18        }
19        System.out.println();
20        
21        // While loop
22        System.out.println("3. While loop:");
23        int count = 1;
24        while (count <= 3) {
25            System.out.print("Round " + count + " ");
26            count++;
27        }
28        System.out.println();
29        
30        // Do-while loop
31        System.out.println("4. Do-while loop (executes at least once):");
32        int value = 1;
33        do {
34            System.out.print("Value: " + value + " ");
35            value++;
36        } while (value <= 3);
37        System.out.println();
38        
39        // Nested loops
40        System.out.println("5. Nested loops (multiplication table):");
41        for (int i = 1; i <= 3; i++) {
42            for (int j = 1; j <= 3; j++) {
43                System.out.print(i * j + "\t");
44            }
45            System.out.println();  // New line after each row
46        }
47    }
48    
49    public static void main(String[] args) {
50        demonstrateLoopTypes();
51    }
52}

What to Notice:

Loop Type Selection

Standard for loop: Best when you need an index or specific iteration count

  • for (int i = 1; i <= 5; i++) - controlled iteration with counter

Enhanced for loop: Best for processing all elements without needing index

  • for (int number : numbers) - cleaner syntax, no array bounds to manage

While loop: Best when iteration depends on a condition that might change

  • Check condition before each iteration
  • Risk of infinite loop if condition never becomes false

Do-while loop: Guarantees at least one execution

  • Check condition after each iteration
  • Useful for input validation or menu systems
Nested Loop Patterns

Outer loop controls rows: for (int i = 1; i <= 3; i++) Inner loop controls columns: for (int j = 1; j <= 3; j++)

Execution order:

  • i=1, j=1,2,3 → first row
  • i=2, j=1,2,3 → second row
  • i=3, j=1,2,3 → third row

Time complexity: O(n×m) where n and m are loop bounds


Practice Exercises

Reading Exercise 1: Trace through the grade processor with these scores: [85, 92, 67, 78]. Calculate the expected totalPoints, bonusPoints, and overallGrade.

Reading Exercise 2: Predict the output of each loop type. What would happen if you changed the loop conditions?

Reading Exercise 3: Identify all the places where the code makes decisions based on calculated values rather than direct input.

← Previous: Beginner Basics Next: Fundamentals →