๐Ÿ”ง [5] Operators & Control Flow โ€” Decision Making in Java!

โœจ Introduction

Ready to make your code a little smarter? ๐Ÿš€ Once you've got a handle on variables and data types, the next big leap is teaching your program how to think, decide, and act.

That's where operators and control flow come in. Whether it's doing some quick math ๐Ÿงฎ, checking conditions ๐Ÿค”, or repeating tasks ๐Ÿ” โ€” these tools help your program react to the world like a mini decision-maker.

In this guide, you'll explore Java's powerful tools like arithmetic, logical, and comparison operators. Then we'll dive into decision-making structures like if and switch, and loop through tasks using for, while, and do-while loops.

By the end, you'll have the building blocks to control your program's flow and bring logic to life! ๐Ÿ’ก

โž• Java Operators Overview

๐Ÿงฎ Arithmetic Operators

These perform basic math operations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Remainder (Modulus) a % b

๐Ÿ”Ž Relational (Comparison) Operators

These operators are used in conditions to compare values.

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

๐Ÿง  Logical Operators

These operators combine multiple conditions together.

Operator Description Example
&& AND (both conditions must be true) a > 5 && b < 10
|| OR (at least one condition is true) a > 5 || b < 10
! NOT (reverses the condition) !isReady

๐Ÿงช Examples of Operators โ€” Building Logic

๐Ÿงฎ Arithmetic Operators

int a = 12, b = 4;

System.out.println(a + b); // โž• 16 (Addition)
System.out.println(a - b); // โž– 8  (Subtraction)
System.out.println(a * b); // โœ–๏ธ 48 (Multiplication)
System.out.println(a / b); // โž— 3  (Division)
System.out.println(a % b); // ๐Ÿ” 0  (Remainder)

๐Ÿ”Ž Relational (Comparison) Operators

int x = 7, y = 10;

System.out.println(x == y);  // โ“ false (7 is not equal to 10)
System.out.println(x != y);  // โœ… true  (7 is not equal to 10)
System.out.println(x > y);   // โŒ false (7 is not greater than 10)
System.out.println(x < y);   // โœ… true  (7 is less than 10)
System.out.println(x <= 7);  // โœ… true  (7 is less than or equal to 7)

๐Ÿง  Logical Operators

boolean isAdult = true;
boolean hasTicket = false;
int score = 85;

System.out.println(isAdult && hasTicket);         // โŒ false (only one is true)
System.out.println(isAdult || hasTicket);         // โœ… true (at least one is true)
System.out.println(!(score > 50));                // โŒ false (score is greater than 50, negated)
System.out.println(score > 80 && score < 100);    // โœ… true (both conditions met)
System.out.println(score < 50 || score > 90);     // โŒ false (neither condition is true)

๐Ÿงฉ Practice Questions โ€” Try It Yourself

๐Ÿงฎ Arithmetic Operator Questions

// Q1: Add two numbers: 12 and 8
// Q2: Subtract 5 from 20
// Q3: Multiply 7 and 6
// Q4: Divide 100 by 25
// Q5: Find the remainder when 22 is divided by 7

// Hint: Use +, -, *, /, % operators respectively

๐Ÿ”Ž Relational Operator Questions

// Q1: Check if 10 is equal to 10
// Q2: Check if 15 is not equal to 20
// Q3: Is 100 greater than 99?
// Q4: Is 25 less than 15?
// Q5: Is 30 greater than or equal to 30?

// Hint: Use ==, !=, >, <, >=, <=

๐Ÿง  Logical Operator Questions

// Q1: Check if a person is an adult (age >= 18) AND has a valid ID
// Q2: Check if a student passed (marks > 40) OR has grace marks
// Q3: Reverse the condition: "isRaining"
// Q4: Check if temperature > 20 AND < 35
// Q5: Check if a number is either less than 0 OR greater than 100

// Hint: Use &&, ||, ! for combining conditions

๐Ÿ“ Answers with Explanations

๐Ÿงฎ Arithmetic Operator Answers

// Q1
System.out.println(12 + 8); // โž• 20
// โœ… Explanation: Adds two integers.
// โŒ Common Mistake: Using strings instead: "12" + "8" gives "128"

// Q2
System.out.println(20 - 5); // โž– 15
// โœ… Explanation: Subtracts 5 from 20.
// โŒ Common Mistake: Reversing the operands: 5 - 20 = -15

// Q3
System.out.println(7 * 6); // โœ–๏ธ 42
// โœ… Explanation: Multiplies 7 and 6.
// โŒ Common Mistake: Typing x instead of *

// Q4
System.out.println(100 / 25); // โž— 4
// โœ… Explanation: Integer division; no decimals here.
// โŒ Common Mistake: Using 0 as divisor (runtime error)

// Q5
System.out.println(22 % 7); // ๐Ÿ” 1
// โœ… Explanation: 7 fits in 22 three times (21), remainder is 1.
// โŒ Common Mistake: Confusing modulus with division

๐Ÿ”Ž Relational Operator Answers

// Q1
System.out.println(10 == 10); // โœ… true
// โœ… Explanation: Both sides are equal.
// โŒ Common Mistake: Using = instead of ==

// Q2
System.out.println(15 != 20); // โœ… true
// โœ… Explanation: 15 is not equal to 20.
// โŒ Common Mistake: Reversing != to == by habit

// Q3
System.out.println(100 > 99); // โœ… true
// โœ… Explanation: 100 is greater than 99.
// โŒ Common Mistake: Using < accidentally

// Q4
System.out.println(25 < 15); // โœ… false
// โœ… Explanation: 25 is not less than 15.
// โŒ Common Mistake: Reading it backwards

// Q5
System.out.println(30 >= 30); // โœ… true
// โœ… Explanation: 30 is equal to 30, so โ‰ฅ is true.
// โŒ Common Mistake: Confusing >= with >

๐Ÿง  Logical Operator Answers

// Q1
int age = 20;
boolean hasID = true;
System.out.println(age >= 18 && hasID); // โœ… true
// โœ… Explanation: Both conditions are true
// โŒ Common Mistake: Using & instead of &&

// Q2
int marks = 35;
boolean grace = true;
System.out.println(marks > 40 || grace); // โœ… true
// โœ… Explanation: One condition is true (grace)
// โŒ Common Mistake: Using && instead of ||

// Q3
boolean isRaining = true;
System.out.println(!isRaining); // โœ… false
// โœ… Explanation: ! reverses true to false
// โŒ Common Mistake: Writing ! without parentheses or variable

// Q4
int temp = 25;
System.out.println(temp > 20 && temp < 35); // โœ… true
// โœ… Explanation: 25 is in the range 21-34
// โŒ Common Mistake: Using || instead of &&

// Q5
int number = -5;
System.out.println(number < 0 || number > 100); // โœ… true
// โœ… Explanation: One condition is true (number < 0)
// โŒ Common Mistake: Not grouping conditions properly

๐Ÿ’ก Tip: Practice modifying the values above and observe how the output changes โ€” this is the best way to master logic!

๐Ÿงฉ Word Problems: Build DSA Thinking Using Java Operators

๐Ÿงฎ Arithmetic Operators โ€” 5 Problems

  1. Shopping Cart Total: You bought 3 notebooks for โ‚น40 each and 2 pens for โ‚น15 each. Find the total bill amount.
  2. Average Marks: Your scores in 3 subjects are 78, 85, and 92. Find the average score.
  3. Area of Rectangle: Given length = 15 units and width = 8 units, calculate the area.
  4. Splitting Bill: You have โ‚น1,000 and want to divide it equally among 4 friends. How much will each get?
  5. Leftover Chocolates: You bought 53 chocolates. If each kid gets 6, how many are left after distribution?

๐Ÿ”Ž Relational Operators โ€” 5 Problems

  1. Age Eligibility: Check if a person aged 17 is eligible to vote (must be 18 or older).
  2. Exam Pass Check: A student scores 43 marks. Pass mark is 40. Did they pass?
  3. Speeding Fine: A car is going at 95 km/h in a 90 km/h zone. Should it get fined?
  4. Same Numbers: Check if two entered numbers are exactly the same.
  5. Budget Check: You want to buy a phone for โ‚น25,000. Your budget is โ‚น20,000. Is it affordable?

๐Ÿง  Logical Operators โ€” 5 Problems

  1. Exam Criteria: You passed both theory (โ‰ฅ40) and practical (โ‰ฅ35). Check if you passed overall.
  2. Discount Eligibility: You're eligible for a discount if you're a student or a senior citizen. Write logic for that.
  3. Temperature Range: Check if temperature is between 20ยฐC and 30ยฐC (inclusive).
  4. Weekend Checker: Today is Saturday. Write a condition that checks if today is Saturday or Sunday.
  5. Security Check: You're not allowed if you're on the banned list. Write a NOT condition to allow entry if not banned.

โœ… Answers: Word Problems on Operators

๐Ÿงฎ Arithmetic Operator Answers

// Q1
int total = (3 * 40) + (2 * 15);
System.out.println("Total Bill: โ‚น" + total); // โ‚น150

// Q2
int avg = (78 + 85 + 92) / 3;
System.out.println("Average Marks: " + avg); // 85

// Q3
int area = 15 * 8;
System.out.println("Area: " + area); // 120

// Q4
int eachGets = 1000 / 4;
System.out.println("Each gets: โ‚น" + eachGets); // โ‚น250

// Q5
int leftover = 53 % 6;
System.out.println("Leftover chocolates: " + leftover); // 5

๐Ÿ”Ž Relational Operator Answers

// Q1
int age = 17;
System.out.println(age >= 18); // false

// Q2
int marks = 43;
System.out.println(marks >= 40); // true

// Q3
int speed = 95;
System.out.println(speed > 90); // true

// Q4
int a = 10, b = 10;
System.out.println(a == b); // true

// Q5
int price = 25000, budget = 20000;
System.out.println(price <= budget); // false

๐Ÿง  Logical Operator Answers

// Q1
int theory = 45, practical = 37;
System.out.println(theory >= 40 && practical >= 35); // true

// Q2
boolean isStudent = true;
boolean isSenior = false;
System.out.println(isStudent || isSenior); // true

// Q3
int temp = 25;
System.out.println(temp >= 20 && temp <= 30); // true

// Q4
String day = "Saturday";
System.out.println(day.equals("Saturday") || day.equals("Sunday")); // true

// Q5
boolean isBanned = false;
System.out.println(!isBanned); // true (entry allowed)

๐Ÿง  15 Arithmetic Challenger Problems

  1. Train Distance: A train travels at 60 km/h. How far will it go in 5.5 hours?
  2. Currency Converter: Convert โ‚น500 to USD (Assume 1 USD = โ‚น82).
  3. Square Perimeter: Find the perimeter of a square with side length 19 cm.
  4. Apple Distribution: You have 365 apples. Distribute equally among 12 baskets. How many does each get?
  5. Mobile Data Usage: You have 1.5GB per day for 30 days. What's the total monthly data?
  6. Library Fine: โ‚น2 fine/day. You returned a book 18 days late. Total fine?
  7. Bill Split with Tip: Your total bill is โ‚น750. Tip is 10%. Split among 5 friends.
  8. Simple Interest: โ‚น1000 at 5% annual interest for 2 years.
  9. Discount Price: Original price is โ‚น800. Discount = 15%. What's the new price?
  10. Circle Area: Radius is 7 cm. Use 3.14 as ฯ€.
  11. Temperature Convert: Convert 100ยฐC to Fahrenheit (F = C ร— 9/5 + 32).
  12. Electricity Bill: Unit rate = โ‚น6.5. Total units = 175. Total bill?
  13. Marks Percentage: You scored 540/600. What's your percentage?
  14. Speed Calculation: You ran 400m in 50 seconds. What's the speed in m/s?
  15. Time Taken: Distance = 900 km, Speed = 60 km/h. Time taken?

๐Ÿงฎ Arithmetic Operator Answers

public class ArithmeticChallengerAnswers {
    public static void main(String[] args) {
        // Q1: Train Distance
        double distance = 60 * 5.5;
        System.out.println("Q1 - Distance Travelled: " + distance + " km"); // 330.0 km

        // Q2: Currency Converter
        double usd = 500.0 / 82;
        System.out.println("Q2 - USD Amount: $" + usd); // ~$6.10

        // Q3: Square Perimeter
        int perimeter = 4 * 19;
        System.out.println("Q3 - Perimeter: " + perimeter + " cm"); // 76 cm

        // Q4: Apple Distribution
        int applesEach = 365 / 12;
        System.out.println("Q4 - Apples per basket: " + applesEach); // 30

        // Q5: Mobile Data Usage
        double totalData = 1.5 * 30;
        System.out.println("Q5 - Total Monthly Data: " + totalData + " GB"); // 45.0 GB

        // Q6: Library Fine
        int fine = 2 * 18;
        System.out.println("Q6 - Total Fine: โ‚น" + fine); // โ‚น36

        // Q7: Bill Split with Tip
        double totalWithTip = 750 + (0.10 * 750);
        double perPerson = totalWithTip / 5;
        System.out.println("Q7 - Each Pays: โ‚น" + perPerson); // โ‚น165.0

        // Q8: Simple Interest
        // Formula:
        // SI = (P ร— R ร— T) / 100
        // Where:
        // P = Principal amount
        // R = Rate of interest (annual)
        // T = Time in years

        double si = (1000 * 5 * 2) / 100.0;
        System.out.println("Q8 - Simple Interest: โ‚น" + si); // โ‚น100.0

        // Q9: Discount Price
        double discount = 0.15 * 800;
        double newPrice = 800 - discount;
        System.out.println("Q9 - Discounted Price: โ‚น" + newPrice); // โ‚น680.0

        // Q10: Circle Area
        // Formula:
        // A = ฯ€ ร— rยฒ
        // Where:
        // A = Area of the circle
        // ฯ€ = Pi (approximately 3.1416)
        // r = Radius of the circle

        double area = 3.14 * 7 * 7;
        System.out.println("Q10 - Circle Area: " + area + " cmยฒ"); // 153.86 cmยฒ

        // Q11: Temperature Convert
        // Temperature Conversion: Celsius to Fahrenheit
        // Formula:
        // F = (C ร— 9/5) + 32
        // Where:
        // C = Temperature in Celsius
        // F = Temperature in Fahrenheit

        double fahrenheit = (100 * 9.0/5.0) + 32;
        System.out.println("Q11 - Fahrenheit: " + fahrenheit + "ยฐF"); // 212.0ยฐF

        // Q12: Electricity Bill
        double bill = 6.5 * 175;
        System.out.println("Q12 - Electricity Bill: โ‚น" + bill); // โ‚น1137.5

        // Q13: Marks Percentage
        double percent = (540.0 / 600.0) * 100;
        System.out.println("Q13 - Percentage: " + percent + "%"); // 90.0%

        // Q14: Speed Calculation
        double speed = 400.0 / 50.0;
        System.out.println("Q14 - Speed: " + speed + " m/s"); // 8.0 m/s

        // Q15: Time Taken
        double time = 900.0 / 60.0;
        System.out.println("Q15 - Time Taken: " + time + " hours"); // 15.0 hours
    }
}

๐Ÿ”Ž 15 Relational Challenger Problems

  1. Eligibility Check: Check if someone who is 12 is a teenager (13-19).
  2. Perfect Score: Check if a student's score is exactly 100.
  3. Profit or Loss: Selling price = โ‚น950, cost price = โ‚น1000. Was it a loss?
  4. Equal Sides: Check if a triangle with sides 5, 5, 5 is equilateral.
  5. Even Age: Check if an age is even (divisible by 2).
  6. Greater Amount: Compare two bank balances: โ‚น15,400 and โ‚น16,000.
  7. Top Rank: A student scores the highest in class. Check if score equals max score.
  8. Loan Limit: User requests โ‚น50,000. Max allowed is โ‚น40,000. Approve?
  9. Rectangle or Square: Check if length and breadth are equal.
  10. Temperature Comparison: Is today hotter than yesterday?
  11. Speed Violation: Check if car exceeds 80 km/h speed limit.
  12. Correct Pin: Verify if entered PIN matches the correct one.
  13. Attendance Requirement: Is 72% attendance enough for required 75%?
  14. Minimum Age: Check if user is at least 21 to rent a car.
  15. Three Equal Numbers: Are all 3 entered numbers the same?

๐Ÿ”Ž Relational Operator Answers

public class RelationalChallengerAnswers {
    public static void main(String[] args) {
        // Q1: Eligibility Check (Teenager: age 13-19)
        int age = 12;
        boolean isTeenager = age >= 13 && age <= 19;
        System.out.println("Q1 - Is Teenager? " + isTeenager); // false

        // Q2: Perfect Score
        int score = 100;
        boolean isPerfect = score == 100;
        System.out.println("Q2 - Is Perfect Score? " + isPerfect); // true

        // Q3: Profit or Loss
        int sp = 950, cp = 1000;
        boolean isLoss = sp < cp;
        System.out.println("Q3 - Was it a Loss? " + isLoss); // true

        // Q4: Equal Sides
        int s1 = 5, s2 = 5, s3 = 5;
        boolean isEquilateral = (s1 == s2) && (s2 == s3);
        System.out.println("Q4 - Is Equilateral? " + isEquilateral); // true

        // Q5: Even Age
        int ageCheck = 24;
        boolean isEven = ageCheck % 2 == 0;
        System.out.println("Q5 - Is Even Age? " + isEven); // true

        // Q6: Greater Amount
        int balance1 = 15400, balance2 = 16000;
        boolean isSecondGreater = balance2 > balance1;
        System.out.println("Q6 - Is โ‚น16000 greater than โ‚น15400? " + isSecondGreater); // true

        // Q7: Top Rank
        int studentScore = 98, maxScore = 98;
        boolean isTopRanker = studentScore == maxScore;
        System.out.println("Q7 - Is Top Ranker? " + isTopRanker); // true

        // Q8: Loan Limit
        int requested = 50000, maxAllowed = 40000;
        boolean isApproved = requested <= maxAllowed;
        System.out.println("Q8 - Loan Approved? " + isApproved); // false

        // Q9: Rectangle or Square
        int length = 10, breadth = 10;
        boolean isSquare = length == breadth;
        System.out.println("Q9 - Is Square? " + isSquare); // true

        // Q10: Temperature Comparison
        int todayTemp = 37, yesterdayTemp = 35;
        boolean isHotter = todayTemp > yesterdayTemp;
        System.out.println("Q10 - Is Today Hotter? " + isHotter); // true

        // Q11: Speed Violation
        int speed = 85;
        boolean isOverSpeeding = speed > 80;
        System.out.println("Q11 - Speeding Violation? " + isOverSpeeding); // true

        // Q12: Correct Pin
        int enteredPin = 1234, correctPin = 1234;
        boolean isPinCorrect = enteredPin == correctPin;
        System.out.println("Q12 - Is Pin Correct? " + isPinCorrect); // true

        // Q13: Attendance Requirement
        double attendance = 72.0, required = 75.0;
        boolean meetsRequirement = attendance >= required;
        System.out.println("Q13 - Meets Attendance Requirement? " + meetsRequirement); // false

        // Q14: Minimum Age
        int userAge = 21;
        boolean canRentCar = userAge >= 21;
        System.out.println("Q14 - Can Rent Car? " + canRentCar); // true

        // Q15: Three Equal Numbers
        int a = 7, b = 7, c = 7;
        boolean allEqual = (a == b) && (b == c);
        System.out.println("Q15 - Are All Numbers Equal? " + allEqual); // true
    }
}

๐Ÿง  15 Logical Challenger Problems

  1. Voter Eligibility: Check if person is Indian and 18+ to vote.
  2. Scholarship Criteria: Marks โ‰ฅ 90 or family income < โ‚น2,00,000.
  3. Loan Approval: Age โ‰ฅ 25 and salary โ‰ฅ โ‚น30,000.
  4. Attendance Alert: Attendance < 75% or marks < 40 โ†’ Show warning?
  5. Exam Cheating Detector: isCheating = true โ†’ Block exam using !.
  6. Working Hours: Check if employee worked between 9AM and 6PM.
  7. Valid User: User must have username and password to log in.
  8. Age or Membership: Entry allowed if age โ‰ฅ 60 or isPremiumMember.
  9. Not Empty String: isEmpty = false โ†’ Allow form submit?
  10. Account Active: Active user and email verified โ†’ Allow access.
  11. Shopping Deal: Add to cart if product in stock and discount โ‰ฅ 10%.
  12. Logical Puzzle: (a > b) and (b > c) โ†’ is a > c?
  13. Event Entry: Age โ‰ฅ 18 and hasTicket or isGuest.
  14. Security Alert: !isVerified โ†’ Show warning popup.
  15. Salary Range: Is salary between โ‚น25,000 and โ‚น50,000?

๐Ÿง  Logical Operator Answers

public class LogicalChallengerAnswers {
    public static void main(String[] args) {
        // Q1: Voter Eligibility
        boolean isIndian = true;
        int age = 20;
        boolean canVote = isIndian && age >= 18;
        System.out.println("Q1 - Can Vote? " + canVote); // true

        // Q2: Scholarship Criteria
        int marks = 85;
        int income = 180000;
        boolean getsScholarship = marks >= 90 || income < 200000;
        System.out.println("Q2 - Eligible for Scholarship? " + getsScholarship); // true

        // Q3: Loan Approval
        int personAge = 28;
        int salary = 32000;
        boolean loanApproved = personAge >= 25 && salary >= 30000;
        System.out.println("Q3 - Loan Approved? " + loanApproved); // true

        // Q4: Attendance Alert
        double attendance = 70.0;
        double testMarks = 38.0;
        boolean showWarning = attendance < 75 || testMarks < 40;
        System.out.println("Q4 - Show Warning? " + showWarning); // true

        // Q5: Exam Cheating Detector
        boolean isCheating = true;
        boolean allowExam = !isCheating;
        System.out.println("Q5 - Allow Exam? " + allowExam); // false

        // Q6: Working Hours

        // Define the hour someone checks in
        int checkInHour = 10; // This means the person checked in at 10 AM
        
        // Define the working hours using a logical AND (&&) condition
        // Check if the check-in time is between 9 AM and 6 PM (inclusive)
        // This means the time must be greater than or equal to 9 AND less than or equal to 18
        boolean isWorkingHours = checkInHour >= 9 && checkInHour <= 18;
        
        // Explanation:
        // - checkInHour >= 9     โ†’ Is 10 greater than or equal to 9? โœ… Yes
        // - checkInHour <= 18    โ†’ Is 10 less than or equal to 18? โœ… Yes
        // - Since both conditions are true, the result is true
        
        System.out.println("Q6 - Within Working Hours? " + isWorkingHours); // Output: true

        // Q7: Valid User
        boolean hasUsername = true;
        boolean hasPassword = true;
        boolean canLogin = hasUsername && hasPassword;
        System.out.println("Q7 - Can Login? " + canLogin); // true

        // Q8: Age or Membership
        int userAge = 45;
        boolean isPremiumMember = true;
        boolean allowEntry = userAge >= 60 || isPremiumMember;
        System.out.println("Q8 - Entry Allowed? " + allowEntry); // true

        // Q9: Not Empty String
        boolean isEmpty = false;
        boolean canSubmit = !isEmpty;
        System.out.println("Q9 - Allow Form Submit? " + canSubmit); // true

        // Q10: Account Active
        boolean isActive = true;
        boolean isEmailVerified = true;
        boolean allowAccess = isActive && isEmailVerified;
        System.out.println("Q10 - Access Granted? " + allowAccess); // true

        // Q11: Shopping Deal
        boolean inStock = true;
        int discount = 15;
        boolean addToCart = inStock && discount >= 10;
        System.out.println("Q11 - Add to Cart? " + addToCart); // true

        // Q12: Logical Puzzle

        int a = 10, b = 8, c = 5;
        
        // We are checking three comparisons:
        // 1. a > b โ†’ Is 'a' greater than 'b'? โ†’ true
        // 2. b > c โ†’ Is 'b' greater than 'c'? โ†’ true
        // 3. a > c โ†’ Is 'a' greater than 'c'? โ†’ true

        // โœ… In mathematics, if (a > b) and (b > c), we can conclude (a > c).
        //    This is called a *transitive relation*.

        // โœ… So in theory, we don't need to check (a > c) separately โ€”
        //    it will always be true if the first two are true.

        // ๐Ÿ›ก๏ธ BUT in real-world code, values may change,
        //    and logic may evolve โ€” so including (a > c) as an explicit condition:
        //    - Makes your logic clearer to other programmers
        //    - Acts as a safety check in case 'b' gets changed unexpectedly
        //    - Helps avoid bugs from assuming transitivity in changing contexts
        
        boolean isAGreaterThanC = (a > b) && (b > c) && (a > c);
        
        System.out.println("Q12 - Is a > c? " + isAGreaterThanC); // Output: true

        // Q13: Event Entry
        int guestAge = 17;
        boolean hasTicket = false;
        boolean isGuest = true;
        boolean canEnter = (guestAge >= 18 && hasTicket) || isGuest;
        System.out.println("Q13 - Can Enter Event? " + canEnter); // true

        // Q14: Security Alert
        boolean isVerified = false;
        boolean showPopup = !isVerified;
        System.out.println("Q14 - Show Security Alert? " + showPopup); // true

        // Q15: Salary Range
        int empSalary = 42000;
        boolean isInRange = empSalary >= 25000 && empSalary <= 50000;
        System.out.println("Q15 - Salary in Range? " + isInRange); // true
    }
}

๐Ÿ”€ Control Flow Statements

โœ… if / else if / else

Use this when you want your program to make decisions based on certain conditions.

int number = 7;

if (number > 0) {
    System.out.println("Positive");
} else if (number < 0) {
    System.out.println("Negative");
} else {
    System.out.println("Zero");
}

โœ… Explanation: The program checks if the number is positive, negative, or zero and prints the appropriate result.

โŒ Expected Mistake: Writing if (number = 0) instead of if (number == 0). The first one assigns 0 instead of comparing it.

๐ŸŒ€ switch Statement

Use switch when you have multiple exact values to check against a single variable.

int day = 3;

switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    case 3: System.out.println("Wednesday"); break;
    default: System.out.println("Invalid Day");
}

โœ… Explanation: This prints the day name based on the number. The break is important to stop the flow after each match.

โŒ Expected Mistake: Omitting break will cause multiple cases to execute (called "fall-through").

๐Ÿ” Loops โ€” Repeat Until You're Done

โžก๏ธ for Loop

Best when you know how many times to repeat something. It has three parts: initialization, condition, and update.

for (int i = 1; i <= 5; i++) {
    System.out.println("Count: " + i);
}

โœ… Explanation: This prints numbers 1 to 5. Loop starts at 1 and runs while i <= 5.

โŒ Expected Mistake: Accidentally putting i++ in the condition (like i++ <= 5), which changes value before the check.

๐Ÿ” while Loop

Use when you don't know how many times the loop should run โ€” the condition is checked before each run.

int i = 1;
while (i <= 3) {
    System.out.println("Looping: " + i);
    i++;
}

โœ… Explanation: Repeats the loop until i becomes greater than 3.

โŒ Expected Mistake: Forgetting i++ causes an infinite loop.

๐Ÿ”‚ do-while Loop

This loop runs at least once, even if the condition is false.

int i = 1;
do {
    System.out.println("Running: " + i);
    i++;
} while (i <= 3);

โœ… Explanation: The code inside do runs once before the condition is even checked.

โŒ Expected Mistake (Misunderstanding): A beginner might think: "If the condition is false from the beginning, the code inside should never run."

๐Ÿ”ด But that would be true for a while loop โ€” not for a do-while. In a do-while loop, the block of code runs at least once before the condition is checked. So even if the condition is false initially, the code still executes once.

๐Ÿšซ Common Mistake in Loop Understanding:

Concept Mistake
do-while Assuming the condition is checked before running the loop
Truth The loop body always runs at least once, no matter the condition
Common Error Thinking it behaves like a while loop (which doesn't run at all if false)

๐ŸŽฏ 15 Best if, else if, and else Concept Challenges

  1. Grade Checker: Write a program that takes student marks as input and prints:
  2. Temperature Advice: Given a temperature value, print:
  3. Even/Odd Check: Given a number, check whether it's even or odd and print "Even" or "Odd".
  4. Age Category: Given a person's age, print:
  5. Login Status: If a user is not logged in, print "Login Required"; else, print "Welcome back".
  6. Number Sign: Given a number, print:
  7. Day Checker: Given a number (1-7), print the corresponding weekday:
  8. BMI Category: Given the BMI value, print:
  9. Exam Result: Based on marks:
  10. Traffic Light: Based on traffic signal color (red/yellow/green), print:
  11. Movie Rating: Based on rating:
  12. Password Strength: Based on password length:
  13. Bill Discount: Based on total bill:
  14. Voting Zone: Based on city:
  15. Student Category: Based on age:

๐Ÿ”€ if, else if, and else Challenge Solutions

public class IfElseChallengerAnswers {
    public static void main(String[] args) {

        // Q1: Grade Checker
        int marks = 85;
        if (marks >= 90) {
            System.out.println("Q1 - Grade: A");
        } else if (marks >= 80) {
            System.out.println("Q1 - Grade: B");
        } else if (marks >= 70) {
            System.out.println("Q1 - Grade: C");
        } else {
            System.out.println("Q1 - Grade: Fail");
        }

        // Q2: Temperature Advice
        int temp = 15;
        if (temp < 10) {
            System.out.println("Q2 - Too Cold");
        } else if (temp <= 25) {
            System.out.println("Q2 - Moderate");
        } else {
            System.out.println("Q2 - Hot");
        }

        // Q3: Even/Odd Check
        int num = 13;
        if (num % 2 == 0) {
            System.out.println("Q3 - Even");
        } else {
            System.out.println("Q3 - Odd");
        }

        // Q4: Age Category
        int age = 65;
        if (age <= 12) {
            System.out.println("Q4 - Child");
        } else if (age <= 19) {
            System.out.println("Q4 - Teen");
        } else if (age <= 59) {
            System.out.println("Q4 - Adult");
        } else {
            System.out.println("Q4 - Senior");
        }

        // Q5: Login Status
        boolean isLoggedIn = false;
        if (!isLoggedIn) {
            System.out.println("Q5 - Login Required");
        } else {
            System.out.println("Q5 - Welcome back");
        }

        // Q6: Number Sign
        int value = 0;
        if (value > 0) {
            System.out.println("Q6 - Positive");
        } else if (value == 0) {
            System.out.println("Q6 - Zero");
        } else {
            System.out.println("Q6 - Negative");
        }

        // Q7: Day Checker
        int day = 3;
        if (day == 1) {
            System.out.println("Q7 - Monday");
        } else if (day == 2) {
            System.out.println("Q7 - Tuesday");
        } else if (day == 3) {
            System.out.println("Q7 - Wednesday");
        } else if (day == 4) {
            System.out.println("Q7 - Thursday");
        } else if (day == 5) {
            System.out.println("Q7 - Friday");
        } else if (day == 6) {
            System.out.println("Q7 - Saturday");
        } else if (day == 7) {
            System.out.println("Q7 - Sunday");
        } else {
            System.out.println("Q7 - Not a valid day");
        }

        // Q8: BMI Category
        double bmi = 27.5;
        if (bmi < 18.5) {
            System.out.println("Q8 - Underweight");
        } else if (bmi < 25) {
            System.out.println("Q8 - Normal");
        } else if (bmi < 30) {
            System.out.println("Q8 - Overweight");
        } else {
            System.out.println("Q8 - Obese");
        }

        // Q9: Exam Result
        int studentMarks = 68;
        if (studentMarks >= 90) {
            System.out.println("Q9 - Distinction");
        } else if (studentMarks >= 60) {
            System.out.println("Q9 - Passed");
        } else {
            System.out.println("Q9 - Failed");
        }

        // Q10: Traffic Light
        String light = "yellow";
        if (light.equals("red")) {
            System.out.println("Q10 - Stop");
        } else if (light.equals("yellow")) {
            System.out.println("Q10 - Ready");
        } else if (light.equals("green")) {
            System.out.println("Q10 - Go");
        } else {
            System.out.println("Q10 - Invalid Signal");
        }

        // Q11: Movie Rating
        double rating = 4.7;
        if (rating >= 4.5) {
            System.out.println("Q11 - Excellent");
        } else if (rating >= 3.5) {
            System.out.println("Q11 - Good");
        } else if (rating >= 2.5) {
            System.out.println("Q11 - Average");
        } else {
            System.out.println("Q11 - Poor");
        }

        // Q12: Password Strength
        String password = "hello123";
        if (password.length() >= 12) {
            System.out.println("Q12 - Strong Password");
        } else if (password.length() >= 8) {
            System.out.println("Q12 - Moderate Password");
        } else {
            System.out.println("Q12 - Weak Password");
        }

        // Q13: Bill Discount
        int totalBill = 4500;
        if (totalBill >= 5000) {
            System.out.println("Q13 - 20% Discount");
        } else if (totalBill >= 3000) {
            System.out.println("Q13 - 10% Discount");
        } else {
            System.out.println("Q13 - No Discount");
        }

        // Q14: Voting Zone
        String state = "Delhi";
        if (state.equals("Delhi")) {
            System.out.println("Q14 - Vote in Zone A");
        } else if (state.equals("Mumbai")) {
            System.out.println("Q14 - Vote in Zone B");
        } else {
            System.out.println("Q14 - Vote in Zone C");
        }

        // Q15: Student Category by Age
        int studentAge = 21;
        if (studentAge <= 5) {
            System.out.println("Q15 - Toddler");
        } else if (studentAge <= 12) {
            System.out.println("Q15 - School Student");
        } else if (studentAge <= 18) {
            System.out.println("Q15 - High School");
        } else {
            System.out.println("Q15 - College Student");
        }
    }
}
import java.util.Scanner;

public class IfElseChallengerAnswersInteractive {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        // Q1: Grade Checker
        System.out.print("Q1 - Enter marks: ");
        int marks = sc.nextInt();
        if (marks >= 90) {
            System.out.println("Grade: A");
        } else if (marks >= 80) {
            System.out.println("Grade: B");
        } else if (marks >= 70) {
            System.out.println("Grade: C");
        } else {
            System.out.println("Grade: Fail");
        }

        // Q2: Temperature Advice
        System.out.print("Q2 - Enter temperature: ");
        int temp = sc.nextInt();
        if (temp < 10) {
            System.out.println("Too Cold");
        } else if (temp <= 25) {
            System.out.println("Moderate");
        } else {
            System.out.println("Hot");
        }

        // Q3: Even/Odd Check
        System.out.print("Q3 - Enter a number: ");
        int num = sc.nextInt();
        if (num % 2 == 0) {
            System.out.println("Even");
        } else {
            System.out.println("Odd");
        }

        // Q4: Age Category
        System.out.print("Q4 - Enter age: ");
        int age = sc.nextInt();
        if (age <= 12) {
            System.out.println("Child");
        } else if (age <= 19) {
            System.out.println("Teen");
        } else if (age <= 59) {
            System.out.println("Adult");
        } else {
            System.out.println("Senior");
        }

        // Q5: Login Status
        System.out.print("Q5 - Are you logged in? (true/false): ");
        boolean isLoggedIn = sc.nextBoolean();
        if (!isLoggedIn) {
            System.out.println("Login Required");
        } else {
            System.out.println("Welcome back");
        }

        // Q6: Number Sign
        System.out.print("Q6 - Enter a number: ");
        int value = sc.nextInt();
        if (value > 0) {
            System.out.println("Positive");
        } else if (value == 0) {
            System.out.println("Zero");
        } else {
            System.out.println("Negative");
        }

        // Q7: Day Checker
        System.out.print("Q7 - Enter day number (1-7): ");
        int day = sc.nextInt();
        if (day == 1) {
            System.out.println("Monday");
        } else if (day == 2) {
            System.out.println("Tuesday");
        } else if (day == 3) {
            System.out.println("Wednesday");
        } else if (day == 4) {
            System.out.println("Thursday");
        } else if (day == 5) {
            System.out.println("Friday");
        } else if (day == 6) {
            System.out.println("Saturday");
        } else if (day == 7) {
            System.out.println("Sunday");
        } else {
            System.out.println("Not a valid day");
        }

        // Q8: BMI Category
        System.out.print("Q8 - Enter your BMI: ");
        double bmi = sc.nextDouble();
        if (bmi < 18.5) {
            System.out.println("Underweight");
        } else if (bmi < 25) {
            System.out.println("Normal");
        } else if (bmi < 30) {
            System.out.println("Overweight");
        } else {
            System.out.println("Obese");
        }

        // Q9: Exam Result
        System.out.print("Q9 - Enter exam marks: ");
        int studentMarks = sc.nextInt();
        if (studentMarks >= 90) {
            System.out.println("Distinction");
        } else if (studentMarks >= 60) {
            System.out.println("Passed");
        } else {
            System.out.println("Failed");
        }

        // Q10: Traffic Light
        System.out.print("Q10 - Enter signal (red/yellow/green): ");
        sc.nextLine(); // consume leftover newline
        String light = sc.nextLine();
        if (light.equalsIgnoreCase("red")) {
            System.out.println("Stop");
        } else if (light.equalsIgnoreCase("yellow")) {
            System.out.println("Ready");
        } else if (light.equalsIgnoreCase("green")) {
            System.out.println("Go");
        } else {
            System.out.println("Invalid Signal");
        }

        // Q11: Movie Rating
        System.out.print("Q11 - Enter movie rating (0.0 - 5.0): ");
        double rating = sc.nextDouble();
        if (rating >= 4.5) {
            System.out.println("Excellent");
        } else if (rating >= 3.5) {
            System.out.println("Good");
        } else if (rating >= 2.5) {
            System.out.println("Average");
        } else {
            System.out.println("Poor");
        }

        // Q12: Password Strength
        System.out.print("Q12 - Enter your password: ");
        sc.nextLine(); // consume newline
        String password = sc.nextLine();
        if (password.length() >= 12) {
            System.out.println("Strong Password");
        } else if (password.length() >= 8) {
            System.out.println("Moderate Password");
        } else {
            System.out.println("Weak Password");
        }

        // Q13: Bill Discount
        System.out.print("Q13 - Enter total bill amount: ");
        int totalBill = sc.nextInt();
        if (totalBill >= 5000) {
            System.out.println("20% Discount");
        } else if (totalBill >= 3000) {
            System.out.println("10% Discount");
        } else {
            System.out.println("No Discount");
        }

        // Q14: Voting Zone
        System.out.print("Q14 - Enter your city (Delhi/Mumbai/etc): ");
        sc.nextLine(); // consume newline
        String state = sc.nextLine();
        if (state.equalsIgnoreCase("Delhi")) {
            System.out.println("Vote in Zone A");
        } else if (state.equalsIgnoreCase("Mumbai")) {
            System.out.println("Vote in Zone B");
        } else {
            System.out.println("Vote in Zone C");
        }

        // Q15: Student Category by Age
        System.out.print("Q15 - Enter student age: ");
        int studentAge = sc.nextInt();
        if (studentAge <= 5) {
            System.out.println("Toddler");
        } else if (studentAge <= 12) {
            System.out.println("School Student");
        } else if (studentAge <= 18) {
            System.out.println("High School");
        } else {
            System.out.println("College Student");
        }

        sc.close();
    }
}

๐ŸŽฏ 15 Best Switch-Case Concept Challenges

  1. Day of the Week: Given an integer from 1 to 7, print the name of the corresponding day (e.g., 1 = Monday, 2 = Tuesday, ..., 7 = Sunday). If the number is outside this range, print "Invalid day".
  2. Grade Evaluator: Given a character representing a grade ('A', 'B', 'C', 'D', 'F'), print the corresponding performance (e.g., 'A' = Excellent). If it's any other character, print "Invalid grade".
  3. Month Name: Given a number from 1 to 12, print the name of the corresponding month. For any number outside this range, print "Invalid month".
  4. Traffic Signal: Given a traffic signal color ("red", "yellow", "green"), print its corresponding action ("Stop", "Wait", "Go"). If the input doesn't match any of these, print "Invalid signal".
  5. Calculator Operation: Given two integers and a character representing an operator ('+', '-', '*', '/'), perform the corresponding arithmetic operation. If the operator is invalid, print "Invalid operator". Handle division by zero.
  6. Browser Detection: Given a browser name ("Chrome", "Firefox", "Safari"), print "Supported". For any other browser name, print "Not supported".
  7. Vowel or Consonant: Given a character (either uppercase or lowercase), check whether it's a vowel ('a', 'e', 'i', 'o', 'u'). If so, print "Vowel". Otherwise, print "Consonant".
  8. Level Description: Given a level number (1, 2, or 3), print the difficulty description: 1 = Easy, 2 = Medium, 3 = Hard. If the input is not 1-3, print "Unknown Level".
  9. Shape Sides: Given a shape name ("Triangle", "Square", "Pentagon"), print the number of sides. For any other shape, print "Unknown shape".
  10. Currency Symbol: Given a currency code ("USD", "EUR", "JPY"), print the corresponding symbol ("$", "โ‚ฌ", "ยฅ"). If the code is not recognized, print "Unknown currency".
  11. Season Finder: Given a short month name ("Jan", "Feb", ..., "Dec"), print the corresponding season: If the month name is invalid, print "Invalid month".
  12. Language Greeting: Given a language name ("English", "Spanish", "French"), print a greeting in that language. If it's not one of these, print "Language not supported".
  13. Menu Selection: Given a menu option number (1, 2, or 3), print the corresponding label: 1 = Start, 2 = Settings, 3 = Exit. If the option is not in the range, print "Invalid Option".
  14. Planet Order: Given a number from 1 to 8, print the corresponding planet's name in order from the Sun: 1 = Mercury, 2 = Venus, ..., 8 = Neptune. If the number is outside 1-8, print "Invalid planet number".
  15. File Extension: Given a file extension:

๐Ÿง  Switch-Case Challenge Solutions

public class SwitchCaseChallengerAnswers {
    public static void main(String[] args) {

        // Q1: Day of the Week
        int day = 3;
        switch (day) {
            case 1: System.out.println("Q1 - Monday"); break;
            case 2: System.out.println("Q1 - Tuesday"); break;
            case 3: System.out.println("Q1 - Wednesday"); break;
            case 4: System.out.println("Q1 - Thursday"); break;
            case 5: System.out.println("Q1 - Friday"); break;
            case 6: System.out.println("Q1 - Saturday"); break;
            case 7: System.out.println("Q1 - Sunday"); break;
            default: System.out.println("Q1 - Invalid day");
        }

        // Q2: Grade Evaluator
        char grade = 'B';
        switch (grade) {
            case 'A': System.out.println("Q2 - Excellent"); break;
            case 'B': System.out.println("Q2 - Good"); break;
            case 'C': System.out.println("Q2 - Average"); break;
            case 'D': System.out.println("Q2 - Below Average"); break;
            case 'F': System.out.println("Q2 - Fail"); break;
            default: System.out.println("Q2 - Invalid grade");
        }

        // Q3: Month Name
        int month = 8;
        switch (month) {
            case 1: System.out.println("Q3 - January"); break;
            case 2: System.out.println("Q3 - February"); break;
            case 3: System.out.println("Q3 - March"); break;
            case 4: System.out.println("Q3 - April"); break;
            case 5: System.out.println("Q3 - May"); break;
            case 6: System.out.println("Q3 - June"); break;
            case 7: System.out.println("Q3 - July"); break;
            case 8: System.out.println("Q3 - August"); break;
            case 9: System.out.println("Q3 - September"); break;
            case 10: System.out.println("Q3 - October"); break;
            case 11: System.out.println("Q3 - November"); break;
            case 12: System.out.println("Q3 - December"); break;
            default: System.out.println("Q3 - Invalid month");
        }

        // Q4: Traffic Signal
        String signal = "green";
        switch (signal) {
            case "red": System.out.println("Q4 - Stop"); break;
            case "yellow": System.out.println("Q4 - Wait"); break;
            case "green": System.out.println("Q4 - Go"); break;
            default: System.out.println("Q4 - Invalid signal");
        }

        // Q5: Calculator Operation
        int a = 12, b = 4;
        char operator = '/';
        switch (operator) {
            case '+': System.out.println("Q5 - " + (a + b)); break;
            case '-': System.out.println("Q5 - " + (a - b)); break;
            case '*': System.out.println("Q5 - " + (a * b)); break;
            case '/': System.out.println("Q5 - " + (b != 0 ? (a / b) : "Cannot divide by zero")); break;
            default: System.out.println("Q5 - Invalid operator");
        }

        // Q6: Browser Detection
        String browser = "Safari";
        switch (browser) {
            case "Chrome":
            case "Firefox":
            case "Safari":
                System.out.println("Q6 - Supported");
                break;
            default:
                System.out.println("Q6 - Not supported");
        }

        // Q7: Vowel or Consonant
        char ch = 'O';
        switch (Character.toLowerCase(ch)) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                System.out.println("Q7 - Vowel");
                break;
            default:
                System.out.println("Q7 - Consonant");
        }

        // Q8: Level Description
        int level = 2;
        switch (level) {
            case 1: System.out.println("Q8 - Easy"); break;
            case 2: System.out.println("Q8 - Medium"); break;
            case 3: System.out.println("Q8 - Hard"); break;
            default: System.out.println("Q8 - Unknown Level");
        }

        // Q9: Shape Sides
        String shape = "Square";
        switch (shape) {
            case "Triangle": System.out.println("Q9 - 3 sides"); break;
            case "Square": System.out.println("Q9 - 4 sides"); break;
            case "Pentagon": System.out.println("Q9 - 5 sides"); break;
            default: System.out.println("Q9 - Unknown shape");
        }

        // Q10: Currency Symbol
        String currency = "JPY";
        switch (currency) {
            case "USD": System.out.println("Q10 - $ (USD)"); break;
            case "EUR": System.out.println("Q10 - โ‚ฌ (EUR)"); break;
            case "JPY": System.out.println("Q10 - ยฅ (JPY)"); break;
            default: System.out.println("Q10 - Unknown currency");
        }

        // Q11: Season Finder
        String monthName = "Jan";
        switch (monthName) {
            case "Dec":
            case "Jan":
            case "Feb":
                System.out.println("Q11 - Winter"); break;
            case "Mar":
            case "Apr":
            case "May":
                System.out.println("Q11 - Spring"); break;
            case "Jun":
            case "Jul":
            case "Aug":
                System.out.println("Q11 - Summer"); break;
            case "Sep":
            case "Oct":
            case "Nov":
                System.out.println("Q11 - Autumn"); break;
            default:
                System.out.println("Q11 - Invalid month");
        }

        // Q12: Language Greeting
        String language = "Spanish";
        switch (language) {
            case "English": System.out.println("Q12 - Hello"); break;
            case "Spanish": System.out.println("Q12 - Hola"); break;
            case "French": System.out.println("Q12 - Bonjour"); break;
            default: System.out.println("Q12 - Language not supported");
        }

        // Q13: Menu Selection
        int option = 2;
        switch (option) {
            case 1: System.out.println("Q13 - Start"); break;
            case 2: System.out.println("Q13 - Settings"); break;
            case 3: System.out.println("Q13 - Exit"); break;
            default: System.out.println("Q13 - Invalid Option");
        }

        // Q14: Planet Order
        int planetNumber = 4;
        switch (planetNumber) {
            case 1: System.out.println("Q14 - Mercury"); break;
            case 2: System.out.println("Q14 - Venus"); break;
            case 3: System.out.println("Q14 - Earth"); break;
            case 4: System.out.println("Q14 - Mars"); break;
            case 5: System.out.println("Q14 - Jupiter"); break;
            case 6: System.out.println("Q14 - Saturn"); break;
            case 7: System.out.println("Q14 - Uranus"); break;
            case 8: System.out.println("Q14 - Neptune"); break;
            default: System.out.println("Q14 - Invalid planet number");
        }

        // Q15: File Type Detector
        String fileExt = ".pdf";
        switch (fileExt) {
            case ".jpg":
            case ".png":
            case ".gif":
                System.out.println("Q15 - Image File"); break;
            case ".mp4":
            case ".mkv":
                System.out.println("Q15 - Video File"); break;
            case ".pdf":
                System.out.println("Q15 - Document File"); break;
            default:
                System.out.println("Q15 - Unknown File Type");
        }
    }
}
import java.util.Scanner;

public class SwitchCaseChallengerUserInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Q1: Day of the Week
        System.out.print("Q1 - Enter a number (1-7) for day of the week: ");
        int day = sc.nextInt();
        switch (day) {
            case 1: System.out.println("Q1 - Monday"); break;
            case 2: System.out.println("Q1 - Tuesday"); break;
            case 3: System.out.println("Q1 - Wednesday"); break;
            case 4: System.out.println("Q1 - Thursday"); break;
            case 5: System.out.println("Q1 - Friday"); break;
            case 6: System.out.println("Q1 - Saturday"); break;
            case 7: System.out.println("Q1 - Sunday"); break;
            default: System.out.println("Q1 - Invalid day");
        }

        // Q2: Grade Evaluator
        System.out.print("Q2 - Enter a grade (A/B/C/D/F): ");
        char grade = sc.next().toUpperCase().charAt(0);
        switch (grade) {
            case 'A': System.out.println("Q2 - Excellent"); break;
            case 'B': System.out.println("Q2 - Good"); break;
            case 'C': System.out.println("Q2 - Average"); break;
            case 'D': System.out.println("Q2 - Below Average"); break;
            case 'F': System.out.println("Q2 - Fail"); break;
            default: System.out.println("Q2 - Invalid grade");
        }

        // Q3: Month Name
        System.out.print("Q3 - Enter a number (1-12) for month: ");
        int month = sc.nextInt();
        switch (month) {
            case 1: System.out.println("Q3 - January"); break;
            case 2: System.out.println("Q3 - February"); break;
            case 3: System.out.println("Q3 - March"); break;
            case 4: System.out.println("Q3 - April"); break;
            case 5: System.out.println("Q3 - May"); break;
            case 6: System.out.println("Q3 - June"); break;
            case 7: System.out.println("Q3 - July"); break;
            case 8: System.out.println("Q3 - August"); break;
            case 9: System.out.println("Q3 - September"); break;
            case 10: System.out.println("Q3 - October"); break;
            case 11: System.out.println("Q3 - November"); break;
            case 12: System.out.println("Q3 - December"); break;
            default: System.out.println("Q3 - Invalid month");
        }

        // Q4: Traffic Signal
        System.out.print("Q4 - Enter traffic signal color (red/yellow/green): ");
        String signal = sc.next().toLowerCase();
        switch (signal) {
            case "red": System.out.println("Q4 - Stop"); break;
            case "yellow": System.out.println("Q4 - Wait"); break;
            case "green": System.out.println("Q4 - Go"); break;
            default: System.out.println("Q4 - Invalid signal");
        }

        // Q5: Calculator Operation
        System.out.print("Q5 - Enter two integers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.print("Q5 - Enter an operator (+, -, *, /): ");
        char operator = sc.next().charAt(0);
        switch (operator) {
            case '+': System.out.println("Q5 - " + (a + b)); break;
            case '-': System.out.println("Q5 - " + (a - b)); break;
            case '*': System.out.println("Q5 - " + (a * b)); break;
            case '/':
                if (b != 0) System.out.println("Q5 - " + (a / b));
                else System.out.println("Q5 - Cannot divide by zero");
                break;
            default: System.out.println("Q5 - Invalid operator");
        }

        // Q6: Browser Detection
        System.out.print("Q6 - Enter a browser name (Chrome/Firefox/Safari): ");
        String browser = sc.next();
        switch (browser) {
            case "Chrome":
            case "Firefox":
            case "Safari":
                System.out.println("Q6 - Supported"); break;
            default:
                System.out.println("Q6 - Not supported");
        }

        // Q7: Vowel or Consonant
        System.out.print("Q7 - Enter an alphabet character: ");
        char ch = sc.next().toLowerCase().charAt(0);
        switch (ch) {
            case 'a': case 'e': case 'i': case 'o': case 'u':
                System.out.println("Q7 - Vowel"); break;
            default:
                System.out.println("Q7 - Consonant");
        }

        // Q8: Level Description
        System.out.print("Q8 - Enter a level (1-3): ");
        int level = sc.nextInt();
        switch (level) {
            case 1: System.out.println("Q8 - Easy"); break;
            case 2: System.out.println("Q8 - Medium"); break;
            case 3: System.out.println("Q8 - Hard"); break;
            default: System.out.println("Q8 - Unknown Level");
        }

        // Q9: Shape Sides
        System.out.print("Q9 - Enter a shape (Triangle/Square/Pentagon): ");
        String shape = sc.next();
        switch (shape) {
            case "Triangle": System.out.println("Q9 - 3 sides"); break;
            case "Square": System.out.println("Q9 - 4 sides"); break;
            case "Pentagon": System.out.println("Q9 - 5 sides"); break;
            default: System.out.println("Q9 - Unknown shape");
        }

        // Q10: Currency Symbol
        System.out.print("Q10 - Enter a currency code (USD/EUR/JPY): ");
        String currency = sc.next();
        switch (currency) {
            case "USD": System.out.println("Q10 - $ (USD)"); break;
            case "EUR": System.out.println("Q10 - โ‚ฌ (EUR)"); break;
            case "JPY": System.out.println("Q10 - ยฅ (JPY)"); break;
            default: System.out.println("Q10 - Unknown currency");
        }

        // Q11: Season Finder
        System.out.print("Q11 - Enter month short name (Jan-Dec): ");
        String monthName = sc.next();
        switch (monthName) {
            case "Dec": case "Jan": case "Feb":
                System.out.println("Q11 - Winter"); break;
            case "Mar": case "Apr": case "May":
                System.out.println("Q11 - Spring"); break;
            case "Jun": case "Jul": case "Aug":
                System.out.println("Q11 - Summer"); break;
            case "Sep": case "Oct": case "Nov":
                System.out.println("Q11 - Autumn"); break;
            default:
                System.out.println("Q11 - Invalid month");
        }

        // Q12: Language Greeting
        System.out.print("Q12 - Enter a language (English/Spanish/French): ");
        String language = sc.next();
        switch (language) {
            case "English": System.out.println("Q12 - Hello"); break;
            case "Spanish": System.out.println("Q12 - Hola"); break;
            case "French": System.out.println("Q12 - Bonjour"); break;
            default: System.out.println("Q12 - Language not supported");
        }

        // Q13: Menu Selection
        System.out.print("Q13 - Enter menu option (1-3): ");
        int option = sc.nextInt();
        switch (option) {
            case 1: System.out.println("Q13 - Start"); break;
            case 2: System.out.println("Q13 - Settings"); break;
            case 3: System.out.println("Q13 - Exit"); break;
            default: System.out.println("Q13 - Invalid Option");
        }

        // Q14: Planet Order
        System.out.print("Q14 - Enter planet number (1-8): ");
        int planetNumber = sc.nextInt();
        switch (planetNumber) {
            case 1: System.out.println("Q14 - Mercury"); break;
            case 2: System.out.println("Q14 - Venus"); break;
            case 3: System.out.println("Q14 - Earth"); break;
            case 4: System.out.println("Q14 - Mars"); break;
            case 5: System.out.println("Q14 - Jupiter"); break;
            case 6: System.out.println("Q14 - Saturn"); break;
            case 7: System.out.println("Q14 - Uranus"); break;
            case 8: System.out.println("Q14 - Neptune"); break;
            default: System.out.println("Q14 - Invalid planet number");
        }

        // Q15: File Type Detector
        System.out.print("Q15 - Enter a file extension (e.g., .jpg, .pdf): ");
        String fileExt = sc.next();
        switch (fileExt) {
            case ".jpg": case ".png": case ".gif":
                System.out.println("Q15 - Image File"); break;
            case ".mp4": case ".mkv":
                System.out.println("Q15 - Video File"); break;
            case ".pdf":
                System.out.println("Q15 - Document File"); break;
            default:
                System.out.println("Q15 - Unknown File Type");
        }

        sc.close();
    }
}

๐Ÿ” 15 Best for Loop Concept Challenges

  1. Print Numbers from 1 to 10: Write a program using a for loop that prints all numbers starting from 1 up to 10, each on a new line.
  2. Sum of First N Natural Numbers: Ask the user to enter a number N. Use a loop to calculate and print the sum of numbers from 1 to N.
  3. Print Even Numbers from 1 to 50: Use a for loop to print all even numbers between 1 and 50 (inclusive), separated by spaces.
  4. Multiplication Table Generator: Prompt the user to enter a number, then print its multiplication table from 1 to 10 using a for loop.
  5. Factorial Calculator: Ask the user to enter a number N. Use a loop to compute the factorial of N (i.e., N!) and display the result.
  6. Print Numbers in Reverse: Write a loop that prints numbers from 10 down to 1 in descending order, all on one line separated by spaces.
  7. Square of Numbers from 1 to 10: Use a loop to print each number from 1 to 10 along with its square in the format: number^2 = result.
  8. Count Multiples of 3 Between 1 and 100: Use a loop to count how many numbers from 1 to 100 are divisible by 3 and print that count.
  9. Sum of Odd Numbers up to N: Ask the user to enter a number N, then use a loop to calculate and print the sum of all odd numbers from 1 to N.
  10. Pattern Printing - Star Triangle: Use nested for loops to print a right-angled triangle of asterisks (*) with 5 rows.
  11. Pattern Printing - Number Triangle: Use nested loops to print a triangle with numbers starting from 1 and increasing consecutively across 5 rows.
  12. Skip Multiples of 4: Use a loop to print numbers from 1 to 20, but skip (do not print) numbers that are divisible by 4.
  13. Stop Loop on Specific Match: Print numbers from 1 to 100 using a loop, but stop the loop (use break) when the number 42 is reached.
  14. Sum of Digits of a Number: Ask the user to input a number. Use a loop to compute and print the sum of its individual digits.
  15. Fibonacci Series Generator: Prompt the user to enter how many terms of the Fibonacci sequence to print. Then use a loop to display the first N terms of the sequence.

๐Ÿงฎ Java for Loop Challenge Solutions

public class ForLoopChallengerAnswers {
    public static void main(String[] args) {

        // 1. Print 1 to 10
        for (int i = 1; i <= 10; i++) {
            System.out.println("Q1 - " + i);
        }

        // 2. Sum of First N Numbers
        int n = 10, sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("Q2 - Sum: " + sum);

        // 3. Even Numbers from 1 to 50
        System.out.print("Q3 - Even Numbers: ");
        for (int i = 2; i <= 50; i += 2) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 4. Multiplication Table
        int num = 7;
        for (int i = 1; i <= 10; i++) {
            System.out.println("Q4 - " + num + " x " + i + " = " + (num * i));
        }

        // 5. Factorial Calculator
        int fact = 1, x = 5;
        for (int i = 1; i <= x; i++) {
            fact *= i;
        }
        System.out.println("Q5 - Factorial: " + fact);

        // 6. Reverse Print
        System.out.print("Q6 - Reverse: ");
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 7. Square of Numbers 1-10
        for (int i = 1; i <= 10; i++) {
            System.out.println("Q7 - " + i + "^2 = " + (i * i));
        }

        // 8. Count Multiples of 3 (1 to 100)
        int count = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 3 == 0) count++;
        }
        System.out.println("Q8 - Multiples of 3: " + count);

        // 9. Sum of Odd Numbers up to N
        int oddSum = 0;
        for (int i = 1; i <= n; i += 2) {
            oddSum += i;
        }
        System.out.println("Q9 - Sum of odd numbers: " + oddSum);

        // 10. Pattern: Stars Triangle (5 rows)
        System.out.println("Q10 - Star Triangle:");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }

        // 11. Pattern: Numbers Triangle (5 rows)
        System.out.println("Q11 - Number Triangle:");
        int number = 1;
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(number++ + " ");
            }
            System.out.println();
        }

        // 12. Skip Multiples of 4
        System.out.print("Q12 - Skipping multiples of 4: ");
        for (int i = 1; i <= 20; i++) {
            if (i % 4 == 0) continue;
            System.out.print(i + " ");
        }
        System.out.println();

        // 13. Break on Match
        System.out.print("Q13 - Break at 42: ");
        for (int i = 1; i <= 100; i++) {
            if (i == 42) break;
            System.out.print(i + " ");
        }
        System.out.println();

        // 14. Sum of Digits
        int numToSum = 1234;
        int digitSum = 0;
        for (; numToSum > 0; numToSum /= 10) {
            digitSum += numToSum % 10;
        }
        System.out.println("Q14 - Digit Sum: " + digitSum);

        // 15. Fibonacci Series (first N terms)
        System.out.print("Q15 - Fibonacci Series: ");
        int terms = 10, a = 0, b = 1;
        for (int i = 1; i <= terms; i++) {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
        }
        System.out.println();
    }
}
import java.util.Scanner;

public class ForLoopChallengerUserInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // 1. Print 1 to 10
        System.out.println("Q1 - Numbers from 1 to 10:");
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }

        // 2. Sum of First N Numbers
        System.out.print("Q2 - Enter N for sum from 1 to N: ");
        int n = sc.nextInt();
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("Sum = " + sum);

        // 3. Even Numbers from 1 to 50
        System.out.print("Q3 - Even Numbers from 1 to 50: ");
        for (int i = 2; i <= 50; i += 2) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 4. Multiplication Table
        System.out.print("Q4 - Enter a number for multiplication table: ");
        int num = sc.nextInt();
        for (int i = 1; i <= 10; i++) {
            System.out.println(num + " x " + i + " = " + (num * i));
        }

        // 5. Factorial Calculator
        System.out.print("Q5 - Enter a number to calculate factorial: ");
        int x = sc.nextInt();
        int fact = 1;
        for (int i = 1; i <= x; i++) {
            fact *= i;
        }
        System.out.println("Factorial = " + fact);

        // 6. Reverse Print
        System.out.print("Q6 - Numbers from 10 to 1: ");
        for (int i = 10; i >= 1; i--) {
            System.out.print(i + " ");
        }
        System.out.println();

        // 7. Square of Numbers from 1 to 10
        System.out.println("Q7 - Squares of numbers 1 to 10:");
        for (int i = 1; i <= 10; i++) {
            System.out.println(i + "^2 = " + (i * i));
        }

        // 8. Count Multiples of 3 (1 to 100)
        int count = 0;
        for (int i = 1; i <= 100; i++) {
            if (i % 3 == 0) count++;
        }
        System.out.println("Q8 - Count of multiples of 3 from 1 to 100: " + count);

        // 9. Sum of Odd Numbers up to N
        System.out.print("Q9 - Enter N to find sum of odd numbers up to N: ");
        int oddN = sc.nextInt();
        int oddSum = 0;
        for (int i = 1; i <= oddN; i += 2) {
            oddSum += i;
        }
        System.out.println("Sum of odd numbers = " + oddSum);

        // 10. Pattern: Stars Triangle
        System.out.println("Q10 - Star Triangle (5 rows):");
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }

        // 11. Pattern: Numbers Triangle
        System.out.println("Q11 - Number Triangle (5 rows):");
        int number = 1;
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(number++ + " ");
            }
            System.out.println();
        }

        // 12. Skip Multiples of 4
        System.out.print("Q12 - Numbers from 1 to 20 (skipping multiples of 4): ");
        for (int i = 1; i <= 20; i++) {
            if (i % 4 == 0) continue;
            System.out.print(i + " ");
        }
        System.out.println();

        // 13. Break on Match
        System.out.print("Q13 - Numbers from 1 to 100 (stop at 42): ");
        for (int i = 1; i <= 100; i++) {
            if (i == 42) break;
            System.out.print(i + " ");
        }
        System.out.println();

        // 14. Sum of Digits
        System.out.print("Q14 - Enter a number to sum its digits: ");
        int numToSum = sc.nextInt();
        int digitSum = 0;
        for (; numToSum > 0; numToSum /= 10) {
            digitSum += numToSum % 10;
        }
        System.out.println("Digit sum = " + digitSum);

        // 15. Fibonacci Series
        System.out.print("Q15 - Enter N to print first N Fibonacci numbers: ");
        int terms = sc.nextInt();
        int a = 0, b = 1;
        System.out.print("Fibonacci Series: ");
        for (int i = 1; i <= terms; i++) {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
        }
        System.out.println();

        sc.close();
    }
}

๐Ÿ” 15 Best while Loop Concept Challenges

  1. Print Numbers 1 to 10: Write a program that uses a while loop to print numbers from 1 to 10.
  2. Countdown from 10 to 1: Use a while loop to print a countdown from 10 down to 1.
  3. Add Until Total Reaches 100: Keep asking the user to input numbers and keep adding them until the total is 100 or more.
  4. Reverse the Digits of a Number: Input a number and reverse its digits using a while loop.
  5. Count the Number of Digits: Write a program that counts how many digits are in a given integer using a while loop.
  6. Check if a Number is a Palindrome: Check whether a given number reads the same backward as forward (e.g., 1221).
  7. Sum the Digits of a Number: Calculate and print the sum of all digits in a number using a while loop.
  8. Multiplication Table Until Exit: Continuously print the multiplication table for user input until the user enters -1 to exit.
  9. Guess the Secret Number: Let the user guess a secret number until they guess it correctly.
  10. Print Powers of Two up to 1024: Use a while loop to print powers of 2 starting from 1 up to 1024.
  11. Generate Fibonacci Numbers Until a Limit: Print all Fibonacci numbers less than a given limit (e.g., 100) using a while loop.
  12. Check if a Number is an Armstrong Number: Determine whether a 3-digit number is an Armstrong number (e.g., 153 โ†’ 1ยณ + 5ยณ + 3ยณ = 153).
  13. Sum of Even Numbers from 1 to 100: Use a while loop to calculate the sum of all even numbers from 1 to 100.
  14. Find All Factors of a Number: Print all positive integers that divide a given number exactly using a while loop.
  15. User Login with 3 Attempts: Allow the user up to 3 attempts to enter the correct password. If incorrect after 3 tries, lock the account.

๐Ÿงฎ Java while Loop Challenge Solutions

import java.util.Scanner;

public class WhileLoopChallengerAnswers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Q1: Print 1 to 10
        System.out.println("Q1 - Printing numbers from 1 to 10:");
        int i = 1;
        while (i <= 10) {
            System.out.println(i);
            i++;
        }

        // Q2: Countdown
        System.out.println("\nQ2 - Countdown from 10 to 1:");
        int n = 10;
        while (n >= 1) {
            System.out.println(n);
            n--;
        }

        // Q3: Sum Until 100
        System.out.println("\nQ3 - Keep entering numbers to reach or exceed a sum of 100:");
        int sum = 0;
        while (sum < 100) {
            System.out.print("Enter number: ");
            int input = sc.nextInt();
            sum += input;
        }
        System.out.println("Total sum: " + sum);

        // Q4: Reverse Digits
        System.out.print("\nQ4 - Enter a number to reverse its digits: ");
        int num = sc.nextInt();
        int rev = 0;
        while (num != 0) {
            int digit = num % 10;
            rev = rev * 10 + digit;
            num /= 10;
        }
        System.out.println("Reversed number: " + rev);

        // Q5: Count Digits
        System.out.print("\nQ5 - Enter a number to count its digits: ");
        int countNum = sc.nextInt();
        int count = 0;
        while (countNum != 0) {
            countNum /= 10;
            count++;
        }
        System.out.println("Number of digits: " + count);

        // Q6: Check Palindrome
        System.out.print("\nQ6 - Enter a number to check if it's a palindrome: ");
        int original = sc.nextInt();
        int temp = original;
        int reversed = 0;
        while (temp != 0) {
            int digit = temp % 10;
            reversed = reversed * 10 + digit;
            temp /= 10;
        }
        System.out.println(original == reversed ? "Palindrome" : "Not Palindrome");

        // Q7: Sum of Digits
        System.out.print("\nQ7 - Enter a number to find sum of its digits: ");
        int digitSumNum = sc.nextInt();
        int digitSum = 0;
        while (digitSumNum != 0) {
            digitSum += digitSumNum % 10;
            digitSumNum /= 10;
        }
        System.out.println("Sum of digits: " + digitSum);

        // Q8: Table Until Exit
        System.out.println("\nQ8 - Enter numbers to print their multiplication table (-1 to exit):");
        int tableInput;
        do {
            System.out.print("Enter number: ");
            tableInput = sc.nextInt();
            int t = 1;
            while (tableInput != -1 && t <= 10) {
                System.out.println(tableInput + " x " + t + " = " + (tableInput * t));
                t++;
            }
        } while (tableInput != -1);

        // Q9: Guess the Number
        System.out.println("\nQ9 - Guess the secret number between 1 and 10:");
        int secret = 7;
        int guess;
        do {
            System.out.print("Your guess: ");
            guess = sc.nextInt();
        } while (guess != secret);
        System.out.println("Correct!");

        // Q10: Power of Two
        System.out.println("\nQ10 - Powers of 2 up to 1024:");
        int power = 1;
        while (power <= 1024) {
            System.out.println(power);
            power *= 2;
        }

        // Q11: Fibonacci Until Limit
        System.out.print("\nQ11 - Enter a limit to generate Fibonacci numbers: ");
        int limit = sc.nextInt();
        int a = 0, b = 1;
        System.out.print("Fibonacci series: ");
        while (a < limit) {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
        }
        System.out.println();

        // Q12: Check Armstrong Number
        System.out.print("\nQ12 - Enter a 3-digit number to check if it's an Armstrong number: ");
        int arm = sc.nextInt();
        int originalArm = arm;
        int result = 0;
        while (arm != 0) {
            int digit = arm % 10;
            result += digit * digit * digit;
            arm /= 10;
        }
        System.out.println(result == originalArm ? "Armstrong number" : "Not Armstrong");

        // Q13: Even Sum
        System.out.println("\nQ13 - Sum of even numbers from 1 to 100:");
        int even = 1;
        int evenSum = 0;
        while (even <= 100) {
            if (even % 2 == 0)
                evenSum += even;
            even++;
        }
        System.out.println("Sum of even numbers: " + evenSum);

        // Q14: Factor Finder
        System.out.print("\nQ14 - Enter a number to find its factors: ");
        int factNum = sc.nextInt();
        int f = 1;
        System.out.println("Factors of " + factNum + ":");
        while (f <= factNum) {
            if (factNum % f == 0)
                System.out.println(f);
            f++;
        }

        // Q15: User Login Attempts
        String correctPass = "admin123";
        int attempts = 0;
        System.out.println("\nQ15 - Login system (3 attempts):");
        while (attempts < 3) {
            System.out.print("Enter password: ");
            String input = sc.next();
            if (input.equals(correctPass)) {
                System.out.println("Access Granted");
                break;
            }
            attempts++;
        }
        if (attempts == 3) {
            System.out.println("Account Locked");
        }

        sc.close();
    }
}

๐Ÿ” 15 Best do-while Concept Challenges

  1. Print numbers from 1 to 10: Use a do-while loop to print numbers from 1 to 10. No user input is required.
  2. Sum of first N numbers: Prompt the user to enter a number N. Use a do-while loop to find and print the sum of numbers from 1 to N.
  3. Multiplication table: Ask the user to enter a number. Use a do-while loop to print its multiplication table up to 10.
  4. Reverse a number: Prompt the user to enter a number. Use a do-while loop to reverse the digits of that number (e.g., input: 1234 โ†’ output: 4321).
  5. Palindrome check: Ask the user to input a number. Use a do-while loop to check whether the number is a palindrome (reads the same forwards and backwards).
  6. Digit count: Prompt the user to enter a number. Use a do-while loop to count how many digits the number has.
  7. Even numbers from 1 to 50: Use a do-while loop to print all even numbers between 1 and 50 (inclusive). No user input required.
  8. Factorial: Ask the user to enter a number. Use a do-while loop to calculate and print its factorial (e.g., 5 โ†’ 120).
  9. Sum of digits: Prompt the user to enter a number. Use a do-while loop to compute and display the sum of its digits.
  10. Positive input prompt: Use a do-while loop to repeatedly ask the user to enter a number until they provide a positive number.
  11. Decimal to binary conversion: Ask the user to enter a decimal number. Use a do-while loop to convert and display its binary representation (as an integer).
  12. Star pattern: Prompt the user to enter the number of rows. Use nested do-while loops to print a right-angled triangle pattern of stars (*) up to that number of rows.
  13. Countdown: Use a do-while loop to print a countdown from 10 to 1. No user input is required.
  14. Fibonacci series: Ask the user how many terms of the Fibonacci series to print. Use a do-while loop to generate and display that many terms.
  15. Sum of odd numbers: Prompt the user to enter a number N. Use a do-while loop to calculate and print the sum of all odd numbers from 1 to N.

๐Ÿงฎ Java do-while Challenge Solutions

import java.util.Scanner;

public class DoWhileChallengerUserInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Q1: Print 1 to 10
        System.out.println("Q1 - Printing numbers from 1 to 10:");
        int i = 1;
        do {
            System.out.print(i + " ");
            i++;
        } while (i <= 10);
        System.out.println("\n");

        // Q2: Sum of first N numbers
        System.out.print("Q2 - Enter N to find sum from 1 to N: ");
        int n = sc.nextInt();
        int sum = 0, j = 1;
        do {
            sum += j;
            j++;
        } while (j <= n);
        System.out.println("Sum: " + sum + "\n");

        // Q3: Multiplication table
        System.out.print("Q3 - Enter a number for its multiplication table: ");
        int num = sc.nextInt(), k = 1;
        do {
            System.out.println(num + " x " + k + " = " + (num * k));
            k++;
        } while (k <= 10);
        System.out.println();

        // Q4: Reverse a number
        System.out.print("Q4 - Enter a number to reverse: ");
        int number = sc.nextInt(), reversed = 0, temp = number;
        do {
            reversed = reversed * 10 + temp % 10;
            temp /= 10;
        } while (temp != 0);
        System.out.println("Reversed: " + reversed + "\n");

        // Q5: Palindrome check
        System.out.print("Q5 - Enter a number to check palindrome: ");
        int original = sc.nextInt(), rev = 0, copy = original;
        do {
            rev = rev * 10 + copy % 10;
            copy /= 10;
        } while (copy != 0);
        System.out.println(original == rev ? "Palindrome\n" : "Not a palindrome\n");

        // Q6: Digit count
        System.out.print("Q6 - Enter a number to count digits: ");
        int digitNum = sc.nextInt(), count = 0;
        do {
            count++;
            digitNum /= 10;
        } while (digitNum != 0);
        System.out.println("Digit count: " + count + "\n");

        // Q7: Even numbers from 1 to 50
        System.out.println("Q7 - Even numbers from 1 to 50:");
        int ev = 2;
        do {
            System.out.print(ev + " ");
            ev += 2;
        } while (ev <= 50);
        System.out.println("\n");

        // Q8: Factorial
        System.out.print("Q8 - Enter a number to find factorial: ");
        int x = sc.nextInt(), fact = 1, f = 1;
        do {
            fact *= f;
            f++;
        } while (f <= x);
        System.out.println("Factorial: " + fact + "\n");

        // Q9: Sum of digits
        System.out.print("Q9 - Enter a number to sum its digits: ");
        int numToSum = sc.nextInt(), digitSum = 0;
        do {
            digitSum += numToSum % 10;
            numToSum /= 10;
        } while (numToSum != 0);
        System.out.println("Digit sum: " + digitSum + "\n");

        // Q10: Positive input prompt simulation
        int input;
        do {
            System.out.print("Q10 - Enter a positive number: ");
            input = sc.nextInt();
        } while (input <= 0);
        System.out.println("Positive input accepted: " + input + "\n");

        // Q11: Decimal (Integer) to Binary
        System.out.print("Q11 - Enter a whole number (integer): ");
        if (sc.hasNextInt()) {
            int dec = sc.nextInt();
            int binary = 0, place = 1;
            int originalDec = dec;
        
            if (dec == 0) {
                binary = 0;
            } else {
                do {
                    int rem = dec % 2;
                    binary += rem * place;
                    place *= 10;
                    dec /= 2;
                } while (dec != 0);
            }
        
            System.out.println("Binary of " + originalDec + " is: " + binary + "\n");
        } else {
            System.out.println("Invalid input! Please enter a whole number (no decimal part).\n");
            sc.next(); // clear the invalid input
        }

        // Q11: Decimal (Floating-Point) to Binary
        System.out.print("Q11 - Enter a decimal number (e.g., 5.75): ");
        if (sc.hasNextDouble()) {
            double decimalInput = sc.nextDouble();
            int intPart = (int) decimalInput;
            double fracPart = decimalInput - intPart;
        
            // Convert integer part using do-while
            String intBinary = "";
            if (intPart == 0) {
                intBinary = "0";
            } else {
                do {
                    intBinary = (intPart % 2) + intBinary;
                    intPart /= 2;
                } while (intPart > 0);
            }
        
            // Convert fractional part using do-while
            String fracBinary = "";
            int limit = 10; // max digits after point
            int fracCount = 0;
        
            if (fracPart > 0) {
                do {
                    fracPart *= 2;
                    if (fracPart >= 1) {
                        fracBinary += "1";
                        fracPart -= 1;
                    } else {
                        fracBinary += "0";
                    }
                    fracCount++;
                } while (fracPart > 0 && fracCount < limit);
            }
        
            System.out.println("Binary of " + decimalInput + " is: " + intBinary +
                    (fracBinary.isEmpty() ? "" : "." + fracBinary) + "\n");
        
        } else {
            System.out.println("Invalid input! Please enter a numeric value.\n");
            sc.next(); // clear invalid input
        }

        // Q12: Star pattern
        System.out.print("Q12 - Enter number of rows for star pattern: ");
        int rows = sc.nextInt(), row = 1;
        do {
            int star = 1;
            do {
                System.out.print("* ");
                star++;
            } while (star <= row);
            System.out.println();
            row++;
        } while (row <= rows);
        System.out.println();

        // Q13: Countdown
        System.out.println("Q13 - Countdown from 10:");
        int down = 10;
        do {
            System.out.print(down + " ");
            down--;
        } while (down >= 1);
        System.out.println("\n");

        // Q14: Fibonacci series
        System.out.print("Q14 - Enter number of Fibonacci terms: ");
        int terms = sc.nextInt(), a = 0, b = 1, fib = 1;
        System.out.print("Fibonacci series: ");
        do {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
            fib++;
        } while (fib <= terms);
        System.out.println("\n");

        // Q15: Sum of odd numbers
        System.out.print("Q15 - Enter a number to sum all odd numbers up to it: ");
        int limit = sc.nextInt(), odd = 1, oddSum = 0;
        do {
            oddSum += odd;
            odd += 2;
        } while (odd <= limit);
        System.out.println("Sum of odd numbers: " + oddSum);

        sc.close();
    }
}

๐Ÿ”ข Decimal to Binary Converter

๐Ÿง  Logic (Simple Explanation)

๐Ÿ” Integer to Binary using do-while loop

// ๐ŸŸข Q11: Decimal (Integer) to Binary using do-while
System.out.print("Q11 - Enter a whole number (integer): "); // Ask the user for an integer input
if (sc.hasNextInt()) { // Check if the input is a valid whole number (integer)
    int dec = sc.nextInt(); // Read and store the input number
    int binary = 0, place = 1; // Initialize binary result and place value (1s, 10s, 100s...)
    int originalDec = dec; // Save original number for display later

    if (dec == 0) { // Special case: if the number is 0, binary is also 0
        binary = 0;
    } else {
        do { // Start do-while loop for conversion (runs at least once)
            int rem = dec % 2; // Get remainder when dividing by 2 (either 0 or 1)
            binary += rem * place; // Add the bit in the correct place value (units, tens, etc.)
            place *= 10; // Move to the next binary digit's place (like shifting left)
            dec /= 2; // Divide number by 2 for next iteration (integer division)
        } while (dec != 0); // Repeat until the number becomes 0
    }

    // Print the original number and its binary form
    System.out.println("Binary of " + originalDec + " is: " + binary + "\n");
} else {
    // If user entered an invalid input (like a string or decimal), show message
    System.out.println("Invalid input! Please enter a whole number (no decimal part).\n");
    sc.next(); // Clear the invalid input from the scanner buffer
}

๐Ÿ“˜ Easy Explanation:

๐Ÿ” Floating-Point (Decimal) to Binary using do-while loop

// ๐ŸŸข Q11: Decimal (Floating-Point) to Binary using do-while
System.out.print("Q11 - Enter a decimal number (e.g., 5.75): "); // Prompt user for decimal input
if (sc.hasNextDouble()) { // Check if the input is a valid decimal (integers are valid too)
    double decimalInput = sc.nextDouble(); // Read the input number
    int intPart = (int) decimalInput; // Extract the integer part
    double fracPart = decimalInput - intPart; // Extract the fractional part

    // --- Convert integer part using do-while ---
    String intBinary = ""; // To store binary of the integer part
    if (intPart == 0) {
        intBinary = "0"; // If 0, set binary as "0"
    } else {
        do {
            intBinary = (intPart % 2) + intBinary; // Add remainder to binary string
            intPart /= 2; // Move to next bit
        } while (intPart > 0); // Repeat until integer part becomes 0
    }

    // --- Convert fractional part using do-while ---
    String fracBinary = ""; // To store binary of fractional part
    int limit = 10; // Limit to max 10 fractional digits
    int fracCount = 0; // Counter for fractional digits

    if (fracPart > 0) {
        do {
            fracPart *= 2; // Multiply fraction by 2
            if (fracPart >= 1) {
                fracBinary += "1"; // Add 1 and subtract
                fracPart -= 1;
            } else {
                fracBinary += "0"; // Add 0
            }
            fracCount++; // Increase counter
        } while (fracPart > 0 && fracCount < limit); // Stop if fraction becomes 0 or limit reached
    }

    // Display final binary representation
    System.out.println("Binary of " + decimalInput + " is: " + intBinary +
            (fracBinary.isEmpty() ? "" : "." + fracBinary) + "\n");

} else {
    // If invalid input entered
    System.out.println("Invalid input! Please enter a numeric value.\n");
    sc.next(); // Clear invalid token
}

๐Ÿ“˜ Easy Explanation:

โœ… Sample Output:

Integer Input: 13
Binary: 1101

Decimal Input: 5.75
Integer part: 5 โ†’ 101
Fraction part: .75 โ†’ .11
Binary: 101.11

๐Ÿ” Integer to Binary using while loop

// Q11: Decimal (Integer) to Binary
System.out.print("Q11 - Enter a whole number (integer): ");  // Ask user to type a whole number (no decimals)

if (sc.hasNextInt()) {  // Check if the user typed a valid whole number
    int dec = sc.nextInt();  // Store the number in 'dec'
    int binary = 0, place = 1;  // 'binary' will hold our answer, 'place' tracks the position (1s, 10s, 100s)
    int originalDec = dec;  // Save the original number to show in the end

    while (dec != 0) {  // Keep going until the number becomes 0
        int rem = dec % 2;  // Divide by 2, get the remainder (this is one binary digit)
        binary += rem * place;  // Put the digit in the right position (units, tens, etc.)
        place *= 10;  // Move to the next place (e.g., 1 โ†’ 10 โ†’ 100)
        dec /= 2;  // Cut the number in half (integer division)
    }

    // Show the original and the result
    System.out.println("Binary of " + originalDec + " is: " + binary + "\n");
} else {
    // If they typed something wrong (like 5.2 or letters)
    System.out.println("Invalid input! Please enter a whole number (no decimal part).\n");
    sc.next(); // Clear the bad input
}

๐Ÿ“˜ Easy Explanation:

๐Ÿ” Floating-Point (Decimal) to Binary

// Q11: Decimal (Floating-Point) to Binary
System.out.print("Q11 - Enter a decimal number (e.g., 5.75): ");  // Ask user to enter a decimal number
if (sc.hasNextDouble()) {  // Check if they entered a valid decimal
    double decimalInput = sc.nextDouble();  // Read it
    int intPart = (int) decimalInput;  // Get the whole number part (e.g., from 5.75 โ†’ 5)
    double fracPart = decimalInput - intPart;  // Get the decimal part (e.g., from 5.75 โ†’ 0.75)

    // --- Convert the integer part to binary ---
    String intBinary = "";  // Store the binary result as text
    if (intPart == 0) {
        intBinary = "0";  // If the whole part is 0, just write 0
    } else {
        while (intPart > 0) {
            intBinary = (intPart % 2) + intBinary;  // Add remainder in front each time
            intPart /= 2;
        }
    }

    // --- Convert the fractional part to binary ---
    String fracBinary = "";
    int limit = 10; // Only go 10 digits after decimal point to avoid infinite loops

    while (fracPart > 0 && fracBinary.length() < limit) {
        fracPart *= 2;  // Multiply the fraction by 2
        if (fracPart >= 1) {
            fracBinary += "1";  // If it's 1 or more, add a 1
            fracPart -= 1;      // Remove the 1
        } else {
            fracBinary += "0";  // If less than 1, just add 0
        }
    }

    // Join the two parts together and print
    System.out.println("Binary of " + decimalInput + " is: " + intBinary + 
        (fracBinary.isEmpty() ? "" : "." + fracBinary) + "\n");
} else {
    System.out.println("Invalid input! Please enter a numeric value.\n");
    sc.next(); // clear invalid input
}

๐Ÿ“˜ Easy Explanation:

โœ… Sample Output:

Integer Input: 13
Binary: 1101

Decimal Input: 5.75
Integer part: 5 โ†’ 101
Fraction part: .75 โ†’ .11
Binary: 101.11

๐Ÿงช Summary of Key Concepts:

Part What It Does
% 2 Gets binary digit (remainder) โ€” either 0 or 1
/ 2 Divides the number by 2 to move to the next binary digit (integer part)
* 2 Used to convert fractional part โ€” shift left in binary terms
do-while Loop runs at least once even if the condition is false initially โ€” great for guaranteed input processing
while Loop checks the condition first โ€” safer when input may already be invalid
place Tracks binary digit positions (1s, 10s, 100s...) โ€” only used for integer-to-binary when storing result as a number
String Used to build binary values with leading zeros or decimal points (especially for floating-point numbers)

๐Ÿค” Which is better: do-while or while?

๐Ÿงฎ Factorial Calculator Using All Loop Types in Java

The factorial of a number n is the product of all positive integers from 1 to n.

๐Ÿง  Step-by-Step Explanation

๐Ÿ” Using for Loop

import java.util.Scanner;

public class FactorialFor {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int num = sc.nextInt();
    int fact = 1;

    for (int i = 1; i <= num; i++) {
      fact *= i;
    }

    System.out.println("Factorial of " + num + " is: " + fact);
  }
}

๐Ÿ” Using while Loop

import java.util.Scanner;

public class FactorialWhile {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int num = sc.nextInt();
    int fact = 1, i = 1;

    while (i <= num) {
      fact *= i;
      i++;
    }

    System.out.println("Factorial of " + num + " is: " + fact);
  }
}

๐Ÿ” Using do-while Loop

import java.util.Scanner;

public class FactorialDoWhile {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a number: ");
    int num = sc.nextInt();
    int fact = 1, i = 1;

    do {
      fact *= i;
      i++;
    } while (i <= num);

    System.out.println("Factorial of " + num + " is: " + fact);
  }
}

โœ… Summary

๐Ÿ”ข Fibonacci Series in Java

This section demonstrates how to print the Fibonacci Series using for, while, and do-while loops in Java. It also includes detailed step-by-step explanations inside the code as comments.

โœ… 1. Using for loop

public class FibonacciFor {
  public static void main(String[] args) {
    int n = 10; // Total number of terms
    int a = 0, b = 1;

    System.out.print("Fibonacci Series using for loop: ");

    // Step 1: Print first two terms
    System.out.print(a + " " + b + " ");

    // Step 2: Loop from 2 to n-1
    for (int i = 2; i < n; i++) {
      int c = a + b;     // Next term is sum of previous two
      System.out.print(c + " ");
      a = b;             // Move b to a
      b = c;             // Move c to b
    }
  }
}

โœ… 2. Using while loop

public class FibonacciWhile {
  public static void main(String[] args) {
    int n = 10;
    int a = 0, b = 1;
    int i = 2;

    System.out.print("Fibonacci Series using while loop: ");

    // Step 1: Print the first two terms
    System.out.print(a + " " + b + " ");

    // Step 2: Continue loop while i < n
    while (i < n) {
      int c = a + b;
      System.out.print(c + " ");
      a = b;
      b = c;
      i++; // Increment counter
    }
  }
}

โœ… 3. Using do-while loop

public class FibonacciDoWhile {
  public static void main(String[] args) {
    int n = 10;
    int a = 0, b = 1;
    int i = 2;

    System.out.print("Fibonacci Series using do-while loop: ");

    // Step 1: Print the first two terms
    System.out.print(a + " " + b + " ");

    // Step 2: Use do-while to continue until n terms
    do {
      int c = a + b;
      System.out.print(c + " ");
      a = b;
      b = c;
      i++;
    } while (i < n);
  }
}

๐Ÿ“Œ Step-by-Step Logic

๐Ÿ“ˆ Fibonacci Series Until a Given Limit

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence starts from 0 and 1. Unlike the version with a fixed number of terms, here we stop when the next number would exceed a user-defined limit.

๐Ÿ” Using for Loop

// Step-by-step for-loop Fibonacci until a limit
int limit = 100;
int a = 0, b = 1;
System.out.print("Fibonacci series up to " + limit + ": ");
System.out.print(a + " " + b + " ");

for (int next = a + b; next <= limit; next = a + b) {
  System.out.print(next + " ");
  a = b;
  b = next;
}

๐Ÿ”„ Using while Loop

// Step-by-step while-loop Fibonacci until a limit
int limit = 100;
int a = 0, b = 1;
System.out.print("Fibonacci series up to " + limit + ": ");
System.out.print(a + " " + b + " ");
int next = a + b;

while (next <= limit) {
  System.out.print(next + " ");
  a = b;
  b = next;
  next = a + b;
}

๐Ÿ”‚ Using do-while Loop

// Step-by-step do-while-loop Fibonacci until a limit
int limit = 100;
int a = 0, b = 1;
System.out.print("Fibonacci series up to " + limit + ": ");
System.out.print(a + " " + b + " ");
int next = a + b;

do {
  System.out.print(next + " ");
  a = b;
  b = next;
  next = a + b;
} while (next <= limit);

This version ensures that at least one iteration happens even if the limit is small. Ideal when initial values must be printed regardless of conditions.

๐Ÿงฎ Factor Finder: Using All Loops

๐Ÿ”น What Are Factors?

A factor of a number is any number that divides it exactly without leaving a remainder.

Example: Factors of 12 are 1, 2, 3, 4, 6, and 12.

๐Ÿ” Using for Loop

int num = 12;
System.out.println("Factors of " + num + " using for loop:");

for (int i = 1; i <= num; i++) {
    if (num % i == 0) {
        System.out.print(i + " ");
    }
}

โœ… Explanation:

๐Ÿ” Using while Loop

int num = 12;
int i = 1;
System.out.println("\nFactors of " + num + " using while loop:");

while (i <= num) {
    if (num % i == 0) {
        System.out.print(i + " ");
    }
    i++;
}

โœ… Explanation:

๐Ÿ” Using do-while Loop

int num = 12;
int i = 1;
System.out.println("\nFactors of " + num + " using do-while loop:");

do {
    if (num % i == 0) {
        System.out.print(i + " ");
    }
    i++;
} while (i <= num);

โœ… Explanation:

โœ… Output Example for num = 12:

Factors of 12 using for loop:
1 2 3 4 6 12

Factors of 12 using while loop:
1 2 3 4 6 12

Factors of 12 using do-while loop:
1 2 3 4 6 12

๐Ÿ”ข Digit Counter in Java

๐Ÿ“ Objective:

Count the number of digits in an integer using for, while, and do-while loops.

๐Ÿ’ก Logic:

๐Ÿ“˜ Example:

If the number is 4567, it has 4 digits.

โœ… Using for Loop

int num = 4567;
int count = 0;

for (int temp = num; temp != 0; temp /= 10) {
    count++;
}

System.out.println("Digit Count: " + count);

๐Ÿ” Step-by-Step:

  1. Initialize temp = num.
  2. Loop: temp != 0.
  3. On each iteration, remove the last digit using temp /= 10.
  4. Increment count until temp becomes 0.

โœ… Using while Loop

int num = 4567;
int count = 0;
int temp = num;

while (temp != 0) {
    count++;
    temp /= 10;
}

System.out.println("Digit Count: " + count);

๐Ÿ” Step-by-Step:

  1. Copy num to temp.
  2. Continue while temp != 0.
  3. Each time: divide temp by 10 and increment count.

โœ… Using do-while Loop

int num = 4567;
int count = 0;
int temp = num;

do {
    count++;
    temp /= 10;
} while (temp != 0);

System.out.println("Digit Count: " + count);

๐Ÿ” Step-by-Step:

  1. This loop runs at least once, even if the number is 0.
  2. Each loop: count++, then divide temp by 10.
  3. Loop continues while temp != 0.

๐Ÿ“Œ Special Case:

โœ… Output:

Digit Count: 4

๐Ÿ”ข Digit Analysis

Below we calculate:

๐Ÿงฎ Using for loop

int number = 4623;
int original = number;
int count = 0, even = 0, odd = 0, sum = 0;

for (; number > 0; number /= 10) {
  int digit = number % 10;
  count++;
  sum += digit;
  if (digit % 2 == 0) even++;
  else odd++;
}

System.out.println("Digits: " + count);
System.out.println("Sum: " + sum);
System.out.println("Even digits: " + even);
System.out.println("Odd digits: " + odd);

๐Ÿ” Step-by-step:

๐Ÿ” Using while loop

int number = 4623;
int original = number;
int count = 0, even = 0, odd = 0, sum = 0;

while (number > 0) {
  int digit = number % 10;
  count++;
  sum += digit;
  if (digit % 2 == 0) even++;
  else odd++;
  number /= 10;
}

System.out.println("Digits: " + count);
System.out.println("Sum: " + sum);
System.out.println("Even digits: " + even);
System.out.println("Odd digits: " + odd);

๐Ÿ”‚ Using do-while loop

int number = 4623;
int original = number;
int count = 0, even = 0, odd = 0, sum = 0;

do {
  int digit = number % 10;
  count++;
  sum += digit;
  if (digit % 2 == 0) even++;
  else odd++;
  number /= 10;
} while (number > 0);

System.out.println("Digits: " + count);
System.out.println("Sum: " + sum);
System.out.println("Even digits: " + even);
System.out.println("Odd digits: " + odd);

โœ… Sample Output

Digits: 4
Sum: 15
Even digits: 3
Odd digits: 1

๐Ÿง  Which loop is best?

Loop Best When...
for You know all parts: start, end, and update
while You only need to repeat based on a condition
do-while You want the loop to run at least once

๐Ÿ’ก Armstrong Number Logic in Java

An Armstrong number is a number that is equal to the sum of the cubes of its digits. For example, 153 is an Armstrong number because:

1ยณ + 5ยณ + 3ยณ = 1 + 125 + 27 = 153

โœ… Java Code Example

public class ArmstrongCheck {
  public static void main(String[] args) {
    int number = 153;
    int originalNumber = number;
    int sum = 0;

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

    if (sum == originalNumber) {
      System.out.println(originalNumber + " is an Armstrong number.");
    } else {
      System.out.println(originalNumber + " is not an Armstrong number.");
    }
  }
}

๐Ÿ” Key Concepts

โ“ Why Use while (number > 0) Instead of while (number != 0)?

๐Ÿ“Š Comparison

Condition Works for Positive? Works for Zero? Works for Negative? Issue
while (number > 0) โœ… Yes โœ… Yes (loop doesn't run) โœ… Yes (loop doesn't run) None
while (number != 0) โœ… Yes โœ… Yes (loop doesn't run) โŒ No Infinite loop for negative input

๐Ÿ“ Final Tip

Use the while (number > 0) condition when processing digits of a number. It ensures your loop is safe, predictable, and avoids edge-case bugs from negative inputs.

๐Ÿ” Palindrome Number Check in Java

A palindrome number is a number that remains the same when its digits are reversed. For example, 121, 1331, and 454 are palindromes.

โœ… Java Code Example

public class PalindromeCheck {
  public static void main(String[] args) {
    int number = 121;
    int originalNumber = number;
    int reversed = 0;

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

    if (reversed == originalNumber) {
      System.out.println(originalNumber + " is a palindrome.");
    } else {
      System.out.println(originalNumber + " is not a palindrome.");
    }
  }
}

๐Ÿ” How It Works

โ“ Why Use while (number > 0) and Not while (number != 0)?

๐Ÿ“Š Condition Comparison

Condition Positive Input Zero Input Negative Input Potential Issue
while (number > 0) โœ… Yes โœ… Yes (loop doesn't run) โœ… Yes (loop doesn't run) None
while (number != 0) โœ… Yes โœ… Yes (loop doesn't run) โŒ No Infinite loop for negative input

๐Ÿ“ Final Tip

Use while (number > 0) to safely reverse digits when checking for palindromes. It's more robust and avoids accidental infinite loops from negative numbers.

โญ Right-angled triangle Star Pattern in Java Using All Loop Types

Let's print a right-angled triangle star pattern using for, while, and do-while loops in Java. Each loop gives the same output but works differently in structure.

โœ… 1. Using for Loop

public class StarPatternFor {
  public static void main(String[] args) {
    for (int i = 1; i <= 5; i++) {
      for (int j = 1; j <= i; j++) {
        System.out.print("* ");
      }
      System.out.println();
    }
  }
}

โœ… 2. Using while Loop

public class StarPatternWhile {
  public static void main(String[] args) {
    int i = 1;
    while (i <= 5) {
      int j = 1;
      while (j <= i) {
        System.out.print("* ");
        j++;
      }
      System.out.println();
      i++;
    }
  }
}

โœ… 3. Using do-while Loop

public class StarPatternDoWhile {
  public static void main(String[] args) {
    int i = 1;
    do {
      int j = 1;
      do {
        System.out.print("* ");
        j++;
      } while (j <= i);
      System.out.println();
      i++;
    } while (i <= 5);
  }
}

๐Ÿง  Pattern Logic

๐Ÿ”„ Loop Comparison

Loop Type Entry Check? Common Usage
for โœ… Condition checked before loop Best when number of iterations is known
while โœ… Condition checked before loop Use when you may not know iterations in advance
do-while โœ… Condition checked after loop Ensures loop runs at least once

๐Ÿ“Œ Output

* 
* * 
* * * 
* * * * 
* * * * * 

๐Ÿ“ Final Tip

Use for loop when the size of the pattern is fixed. Use while or do-while for more dynamic or user-driven patterns, especially when input is taken at runtime.

๐ŸŒŸ Star Patterns in Java (All Loops)

๐Ÿ“ Pattern 1: Right-Angled Triangle

*
* *
* * *
* * * *
* * * * *

โœ… For Loop

for (int i = 1; i <= 5; i++) {
  for (int j = 1; j <= i; j++) {
    System.out.print("* ");
  }
  System.out.println();
}

โœ… While Loop

int i = 1;
while (i <= 5) {
  int j = 1;
  while (j <= i) {
    System.out.print("* ");
    j++;
  }
  System.out.println();
  i++;
}

โœ… Do-While Loop

int i = 1;
do {
  int j = 1;
  do {
    System.out.print("* ");
    j++;
  } while (j <= i);
  System.out.println();
  i++;
} while (i <= 5);

๐Ÿ“ Pattern 2: Inverted Triangle

* * * * *
* * * *
* * *
* *
*

โœ… For Loop

for (int i = 5; i >= 1; i--) {
  for (int j = 1; j <= i; j++) {
    System.out.print("* ");
  }
  System.out.println();
}

โœ… While Loop

int i = 5;
while (i >= 1) {
  int j = 1;
  while (j <= i) {
    System.out.print("* ");
    j++;
  }
  System.out.println();
  i--;
}

โœ… Do-While Loop

int i = 5;
do {
  int j = 1;
  do {
    System.out.print("* ");
    j++;
  } while (j <= i);
  System.out.println();
  i--;
} while (i >= 1);

๐Ÿ“ Pattern 3: Pyramid

    *
   * *
  * * *
 * * * *
* * * * *

โœ… For Loop

for (int i = 1; i <= 5; i++) {
  for (int space = 1; space <= 5 - i; space++) {
    System.out.print(" ");
  }
  for (int j = 1; j <= i; j++) {
    System.out.print("* ");
  }
  System.out.println();
}

๐Ÿ“ Pattern 4: Inverted Pyramid

* * * * *
 * * * *
  * * *
   * *
    *

โœ… For Loop

for (int i = 5; i >= 1; i--) {
  for (int space = 1; space <= 5 - i; space++) {
    System.out.print(" ");
  }
  for (int j = 1; j <= i; j++) {
    System.out.print("* ");
  }
  System.out.println();
}

๐Ÿ“ Pattern 5: Diamond

    *
   * *
  * * *
 * * * *
* * * * *
 * * * *
  * * *
   * *
    *

โœ… For Loop (Full Diamond)

// Upper Half
for (int i = 1; i <= 5; i++) {
  for (int space = 1; space <= 5 - i; space++) {
    System.out.print(" ");
  }
  for (int j = 1; j <= i; j++) {
    System.out.print("* ");
  }
  System.out.println();
}
// Lower Half
for (int i = 4; i >= 1; i--) {
  for (int space = 1; space <= 5 - i; space++) {
    System.out.print(" ");
  }
  for (int j = 1; j <= i; j++) {
    System.out.print("* ");
  }
  System.out.println();
}

๐Ÿ“Œ Tip:

๐Ÿ“ Number Patterns in Java with Explanations

1๏ธโƒฃ Right-Angled Number Triangle (For Loop)

Print numbers in a right-angled triangle using nested for loops.

int n = 5;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}

2๏ธโƒฃ Inverted Number Triangle (For Loop)

Print decreasing sequences in each row.

int n = 5;
for (int i = n; i >= 1; i--) {
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}

3๏ธโƒฃ Number Pyramid (For Loop)

Create a centered pyramid and its inverted version using numbers.

๐Ÿ”ผ Number Pyramid

int n = 5;
for (int i = 1; i <= n; i++) {
    // Print leading spaces
    for (int s = 1; s <= n - i; s++) {
        System.out.print(" ");
    }
    // Print numbers with space
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}
๐Ÿ”น Output:
    1
   1 2
  1 2 3
 1 2 3 4
1 2 3 4 5

๐Ÿ”ป Inverted Number Pyramid

int n = 5;
for (int i = n; i >= 1; i--) {
    // Print leading spaces
    for (int s = 1; s <= n - i; s++) {
        System.out.print(" ");
    }
    // Print numbers with space
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}
๐Ÿ”น Output:
1 2 3 4 5
 1 2 3 4
  1 2 3
   1 2
    1

๐Ÿ’ก Notes:

4๏ธโƒฃ Diamond Number Pattern (For Loop)

Upper and lower pyramid combined to form a diamond with numbers.

int n = 5;

// Upper half
for (int i = 1; i <= n; i++) {
    for (int s = 1; s <= n - i; s++) {
        System.out.print(" ");
    }
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}

// Lower half
for (int i = n - 1; i >= 1; i--) {
    for (int s = 1; s <= n - i; s++) {
        System.out.print(" ");
    }
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
}

๐Ÿ“Œ Output for n = 5:

    1 
   1 2 
  1 2 3 
 1 2 3 4 
1 2 3 4 5 
 1 2 3 4 
  1 2 3 
   1 2 
    1

5๏ธโƒฃ Floyd's Triangle

Numbers increase sequentially row by row.

int n = 5;
int num = 1;

for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print(num + " ");
        num++;
    }
    System.out.println();
}

๐Ÿ“Œ Output for n = 5:

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

๐Ÿ“˜ Non-Primitive Data Type: String

In Java, a String is a non-primitive data type that represents a sequence of characters. It is an object of the String class and provides various useful methods for manipulation.

๐Ÿ”น String Basics

// Declaration
String name = "Aelify";

// Common operations
System.out.println(name.length());      // 6
System.out.println(name.charAt(0));     // 'A'
System.out.println(name.toUpperCase()); // "AELIFY"
System.out.println(name.substring(1));  // "elify"

๐Ÿง  Concept: Loop Through a String

Let's print each character in a string using all 3 loops.

โ–ถ๏ธ Using for loop

String str = "Java";
for (int i = 0; i < str.length(); i++) {
    System.out.println(str.charAt(i));
}

โ–ถ๏ธ Using while loop

String str = "Java";
int i = 0;
while (i < str.length()) {
    System.out.println(str.charAt(i));
    i++;
}

โ–ถ๏ธ Using do-while loop

String str = "Java";
int i = 0;
do {
    System.out.println(str.charAt(i));
    i++;
} while (i < str.length());

๐Ÿ” Step-by-Step Explanation

  1. Declare a String variable with a value, e.g., "Java".
  2. Use a loop to access each index of the string using charAt(i).
  3. Print each character on a new line.

๐Ÿ“Œ Output for all loops (str = "Java")

J
a
v
a

โœ… Recap

๐Ÿ“ฆ Java Classes โ€” Non-Primitive Data Type

In Java, a class is a blueprint for creating objects. It encapsulates data for the object and methods to manipulate that data. Let's understand how classes work with a step-by-step explanation and looping usage.

๐Ÿง’ Simple Explanation: What Is a Class in Java?

Think of a class like a blueprint or a template for something real โ€” like a Student, Car, or Animal.

๐Ÿ“ฆ In Simple Words:

Imagine you're making a toy using a mold (class). Every time you pour plastic into the mold (create an object), you get a new toy with the shape and features you designed.

๐Ÿ”„ Steps to Create and Use a Class in Java

  1. Create the class: Define the data (like name and age).
  2. Add a constructor: This helps you set values when the object is created.
  3. Add methods: These perform actions, like showing the info.
  4. Use the class in main(): Make real students using new keyword.
  5. Use loops: If you have many students, use for, while, or do-while to show all their info.

โœ… Example in Real Life:

A class is like a cookie-cutter ๐Ÿช. You design it once, and then make many cookies (objects) from it. Each cookie can have different flavors (data).

๐Ÿง  Tip:

Always start by asking: "What do I want to model?" โ€” That will become your class.

โœ… Basic Class Structure

class Student {
  String name;
  int age;

  // Constructor
  Student(String name, int age) {
    this.name = name;
    this.age = age;
  }

  // Method
  void displayInfo() {
    System.out.println("Name: " + name + ", Age: " + age);
  }
}

๐Ÿงช Example: Using Class in Main Method

class Student {
  String name;
  int age;

  Student(String name, int age) {
    this.name = name;
    this.age = age;
  }

  void displayInfo() {
    System.out.println("Name: " + name + ", Age: " + age);
  }
}

public class Main {
  public static void main(String[] args) {
    Student s1 = new Student("Aelify", 20);
    Student s2 = new Student("Bob", 22);

    s1.displayInfo();
    s2.displayInfo();
  }
}

๐Ÿ” Looping Over Class Objects (Array of Objects)

You can use loops to handle multiple class objects efficiently.

๐Ÿ“Œ Using for loop

class Student {
  String name;
  int age;

  Student(String name, int age) {
    this.name = name;
    this.age = age;
  }

  void displayInfo() {
    System.out.println("Name: " + name + ", Age: " + age);
  }
}

public class Main {
  public static void main(String[] args) {
    Student[] students = {
      new Student("Aelify", 20),
      new Student("Bob", 21),
      new Student("Charlie", 22)
    };

    for (int i = 0; i < students.length; i++) {
      students[i].displayInfo();
    }
  }
}

๐Ÿ“Œ Using while loop

class Student {
  String name;
  int age;

  Student(String name, int age) {
    this.name = name;
    this.age = age;
  }

  void displayInfo() {
    System.out.println("Name: " + name + ", Age: " + age);
  }
}

public class Main {
  public static void main(String[] args) {
    Student[] students = {
      new Student("Aelify", 20),
      new Student("Bob", 21),
      new Student("Charlie", 22)
    };

    int i = 0;
    while (i < students.length) {
      students[i].displayInfo();
      i++;
    }
  }
}

๐Ÿ“Œ Using do-while loop

class Student {
  String name;
  int age;

  Student(String name, int age) {
    this.name = name;
    this.age = age;
  }

  void displayInfo() {
    System.out.println("Name: " + name + ", Age: " + age);
  }
}

public class Main {
  public static void main(String[] args) {
    Student[] students = {
      new Student("Aelify", 20),
      new Student("Bob", 21),
      new Student("Charlie", 22)
    };

    int i = 0;
    do {
      students[i].displayInfo();
      i++;
    } while (i < students.length);
  }
}

๐Ÿ” Step-by-Step Breakdown

๐Ÿ“Œ Output Example

Name: Aelify, Age: 20
Name: Bob, Age: 21
Name: Charlie, Age: 22

โœ… Arrays in Java

Arrays are non-primitive data structures that store multiple values of the same type in a single variable. They are indexed starting from 0.

An array is like a row of boxes ๐Ÿงฑ. Each box stores a value, and we can find any value by its box number (called an index). Indexes start from 0.

๐Ÿ“ฆ Array Declaration & Initialization

public class Main {
  public static void main(String[] args) {
    int[] numbers = {10, 20, 30, 40, 50};

    for (int i = 0; i < numbers.length; i++) {
      System.out.println("Element at index " + i + ": " + numbers[i]);
    }
  }
}

๐Ÿ” Loop using while

public class Main {
  public static void main(String[] args) {
    int[] numbers = {10, 20, 30, 40, 50};

    int i = 0;
    while (i < numbers.length) {
      System.out.println("Element at index " + i + ": " + numbers[i]);
      i++;
    }
  }
}

๐Ÿ”‚ Loop using do-while

public class Main {
  public static void main(String[] args) {
    int[] numbers = {10, 20, 30, 40, 50};

    int j = 0;
    do {
      System.out.println("Element at index " + j + ": " + numbers[j]);
      j++;
    } while (j < numbers.length);
  }
}

โž• Sum of Array Elements

public class Main {
  public static void main(String[] args) {
    int[] numbers = {10, 20, 30, 40, 50};

    int sum = 0;
    for (int num : numbers) {
      sum += num;
    }

    System.out.println("Sum of elements: " + sum);
  }
}

๐Ÿง  Multi-dimensional Array (2D)

public class Main {
  public static void main(String[] args) {
    int[][] matrix = {
      {1, 2},
      {3, 4},
      {5, 6}
    };

    for (int row = 0; row < matrix.length; row++) {
      for (int col = 0; col < matrix[row].length; col++) {
        System.out.print(matrix[row][col] + " ");
      }
      System.out.println();
    }
  }
}

๐Ÿ“˜ Simple Explanation (for beginners)

Imagine an array like a row of mailboxes ๐Ÿ“ฌ. Each one holds a number and has a label: 0, 1, 2... etc.

๐ŸŽ’ Real-Life Analogy

Think of an array like a row of school bags. Each bag has a number tag (index) and holds a book (value). You can loop through the bags to find what's inside!

An array is like a train ๐Ÿš† with multiple coaches. Each coach carries a passenger (number). You can walk through the coaches one by one to check who's sitting where!

โœ… Output Example

Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Sum of elements: 150

๐Ÿง  Java Matrices (Multi-dimensional Arrays)

A matrix in Java is essentially a 2D array โ€” an array of arrays. Think of it like a table with rows and columns, where each cell holds a value.

๐Ÿ”น Declaring a 2D Array (Matrix)

int[][] matrix = new int[3][2]; // 3 rows, 2 columns

This creates a matrix like:

[0][0] [0][1]
[1][0] [1][1]
[2][0] [2][1]
public class Main {
  public static void main(String[] args) {
    // Declares a 2D array (matrix) with 3 rows and 2 columns
    int[][] matrix = new int[3][2];

    // Outer loop iterates over each row
    for (int i = 0; i < matrix.length; i++) {
      // Inner loop iterates over each column in the current row
      for (int j = 0; j < matrix[i].length; j++) {
        // Assigns the value i + j to each element in the matrix
        matrix[i][j] = i + j;
        // Prints the current element followed by a space
        System.out.print(matrix[i][j] + " ");
      }
      // Moves to the next line after printing one row
      System.out.println();
    }
  }
}

๐Ÿ”น Initializing a Matrix Directly

public class Main {
  public static void main(String[] args) {
    // Declares and initializes a 2D array with 3 rows and 2 columns
    int[][] matrix = {
      {1, 2},
      {3, 4},
      {5, 6}
    };

    // Traverses and prints each element using nested loops
    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        // Prints each element followed by a space
        System.out.print(matrix[i][j] + " ");
      }
      // Moves to the next line after each row
      System.out.println();
    }
  }
}

๐Ÿ” Accessing Elements

public class Main {
  public static void main(String[] args) {
    // Initializes a 2D array with fixed values
    int[][] matrix = {
      {1, 2},
      {3, 4},
      {5, 6}
    };

    // Accesses and prints the element in the first row, second column
    System.out.println("Element at [0][1]: " + matrix[0][1]); // prints 2
  }
}

๐Ÿ” Traversing a Matrix with Nested Loops

public class Main {
  public static void main(String[] args) {
    // Initializes a 2D array with 3 rows and 2 columns
    int[][] matrix = {
      {1, 2},
      {3, 4},
      {5, 6}
    };

    // Outer loop goes through each row
    for (int row = 0; row < matrix.length; row++) {
      // Inner loop goes through each column in the current row
      for (int col = 0; col < matrix[row].length; col++) {
        // Prints each element followed by a space
        System.out.print(matrix[row][col] + " ");
      }
      // Moves to next line after printing a full row
      System.out.println();
    }
  }
}

๐ŸŒŸ Enhanced For Loop (for-each)

public class Main {
  public static void main(String[] args) {
    // Initializes a 2D array
    int[][] matrix = {
      {1, 2},
      {3, 4},
      {5, 6}
    };

    // For-each loop to go through each row (which is a 1D array)
    for (int[] row : matrix) {
      // For-each loop to go through each element in the current row
      for (int num : row) {
        // Prints each number with a space
        System.out.print(num + " ");
      }
      // Moves to the next line after printing a row
      System.out.println();
    }
  }
}

โž• Matrix Addition

public class Main {
  public static void main(String[] args) {
    // Declares and initializes two 2x2 matrices A and B
    int[][] A = {
      {1, 2},
      {3, 4}
    };
    int[][] B = {
      {5, 6},
      {7, 8}
    };

    // Creates a result matrix to store the sum, same size as A and B
    int[][] result = new int[2][2];

    // Loops over each element to add corresponding elements of A and B
    for (int i = 0; i < A.length; i++) {
      for (int j = 0; j < A[0].length; j++) {
        result[i][j] = A[i][j] + B[i][j];
      }
    }

    // Prints the resulting matrix
    for (int[] row : result) {
      for (int value : row) {
        System.out.print(value + " ");
      }
      System.out.println();
    }
  }
}

โœ–๏ธ Matrix Multiplication

public class Main {
  public static void main(String[] args) {
    // Declares and initializes matrices A and B
    int[][] A = {
      {1, 2},
      {3, 4}
    };
    int[][] B = {
      {2, 0},
      {1, 2}
    };

    // Resultant matrix for storing multiplication results
    int[][] product = new int[2][2];

    // Triple nested loop to perform matrix multiplication
    for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 2; j++) {
        // Initialize current cell to 0
        product[i][j] = 0;
        // Perform the dot product of row of A and column of B
        for (int k = 0; k < 2; k++) {
          product[i][j] += A[i][k] * B[k][j];
        }
      }
    }

    // Prints the product matrix
    for (int[] row : product) {
      for (int value : row) {
        System.out.print(value + " ");
      }
      System.out.println();
    }
  }
}

๐Ÿ“ Transpose of a Matrix

public class Main {
  public static void main(String[] args) {
    // Original matrix with 3 rows and 2 columns
    int[][] original = {
      {1, 2},
      {3, 4},
      {5, 6}
    };

    // Transpose matrix will have 2 rows and 3 columns
    int[][] transpose = new int[2][3];

    // Loops through each element and swaps rows with columns
    for (int i = 0; i < original.length; i++) {
      for (int j = 0; j < original[0].length; j++) {
        transpose[j][i] = original[i][j];
      }
    }

    // Prints the transposed matrix
    for (int[] row : transpose) {
      for (int value : row) {
        System.out.print(value + " ");
      }
      System.out.println();
    }
  }
}

๐Ÿง  Advanced: Jagged Arrays

These are arrays where each row can have a different number of columns:

public class Main {
  public static void main(String[] args) {
    // Declares a jagged array with 3 rows and unspecified column sizes
    int[][] jagged = new int[3][];
    // First row has 2 elements
    jagged[0] = new int[]{1, 2};
    // Second row has 3 elements
    jagged[1] = new int[]{3, 4, 5};
    // Third row has 1 element
    jagged[2] = new int[]{6};

    // Loops through each row
    for (int i = 0; i < jagged.length; i++) {
      // Loops through each column in current row
      for (int j = 0; j < jagged[i].length; j++) {
        // Prints each element followed by space
        System.out.print(jagged[i][j] + " ");
      }
      // New line after each row
      System.out.println();
    }
  }
}

โœ… Recap:

โœ… With these tools, you can now build anything from a spreadsheet to a tic-tac-toe game using matrices!

๐Ÿง  Java Matrices (2D Arrays)

Matrices (2D arrays) are like tables in Java โ€” rows and columns of data. They're used in everything from spreadsheets to games like tic-tac-toe.

๐ŸŽฎ Project 1: Tic-Tac-Toe Game

import java.util.Scanner;

public class TicTacToe {
  public static void main(String[] args) {
    // Initialize the board with 3x3 empty spaces
    char[][] board = {
      {' ', ' ', ' '},
      {' ', ' ', ' '},
      {' ', ' ', ' '}
    };

    Scanner sc = new Scanner(System.in);
    char currentPlayer = 'X';

    for (int moves = 0; moves < 9; moves++) {
      // Print current board
      System.out.println("\nCurrent Board:");
      for (char[] row : board) {
        for (char cell : row) {
          System.out.print("|" + cell);
        }
        System.out.println("|");
      }

      System.out.println("Player " + currentPlayer + ", enter row and column (0-2):");
      int row = sc.nextInt();
      int col = sc.nextInt();

      // โœ… Check for invalid input range
      if (row < 0 || row > 2 || col < 0 || col > 2) {
        System.out.println("โŒ Invalid input! Row and column must be between 0 and 2. Try again.");
        moves--; // Don't count this as a valid move
        continue; // Ask again
      }

      // โœ… Check if cell is already occupied
      if (board[row][col] == ' ') {
        board[row][col] = currentPlayer;

        // โœ… Check for winning conditions
        if ((board[row][0] == currentPlayer && board[row][1] == currentPlayer && board[row][2] == currentPlayer) ||
            (board[0][col] == currentPlayer && board[1][col] == currentPlayer && board[2][col] == currentPlayer) ||
            (board[0][0] == currentPlayer && board[1][1] == currentPlayer && board[2][2] == currentPlayer) ||
            (board[0][2] == currentPlayer && board[1][1] == currentPlayer && board[2][0] == currentPlayer)) {
          System.out.println("๐ŸŽ‰ Player " + currentPlayer + " wins!");
          return;
        }

        // Switch player
        currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
      } else {
        System.out.println("โŒ Cell already taken! Try again.");
        moves--; // Don't count this move
      }
    }

    System.out.println("๐Ÿค It's a draw!");
  }
}

๐Ÿ“Š Project 2: Simple Spreadsheet

import java.util.Scanner;

public class Spreadsheet {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    // Ask user for number of rows and columns
    System.out.print("Enter number of rows: ");
    int rows = scanner.nextInt();

    System.out.print("Enter number of columns: ");
    int cols = scanner.nextInt();

    // Create a 2D array with user-defined size
    int[][] data = new int[rows][cols];

    // ๐Ÿ”น Input Spreadsheet Data
    System.out.println("\nEnter values for the spreadsheet:");
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        System.out.print("Enter value for cell [" + i + "][" + j + "]: ");
        data[i][j] = scanner.nextInt();
      }
    }

    System.out.println();

    // ๐Ÿ”น Sum of Each Row
    System.out.println("๐Ÿ“Œ Sum of Each Row:");
    for (int i = 0; i < rows; i++) {
      int rowSum = 0;
      for (int j = 0; j < cols; j++) {
        rowSum += data[i][j];
      }
      System.out.println("Sum of row " + i + ": " + rowSum);
    }

    System.out.println();

    // ๐Ÿ”น Sum of Each Column
    System.out.println("๐Ÿ“Œ Sum of Each Column:");
    for (int col = 0; col < cols; col++) {
      int colSum = 0;
      for (int row = 0; row < rows; row++) {
        colSum += data[row][col];
      }
      System.out.println("Sum of column " + col + ": " + colSum);
    }

    System.out.println();

    // ๐Ÿ”น Total Sum of All Elements
    int totalSum = 0;
    for (int i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        totalSum += data[i][j];
      }
    }
    System.out.println("๐Ÿงฎ Total sum of all elements: " + totalSum);

    System.out.println();

    // ๐Ÿ”น Display Spreadsheet
    System.out.println("๐Ÿ“‹ Spreadsheet View:");
    for (int[] row : data) {
      for (int val : row) {
        System.out.print(val + "\t");
      }
      System.out.println();
    }

    scanner.close(); // Clean up
  }
}

๐Ÿ Snake Game in Java (Console-based)

๐Ÿ This is a simple console-based Snake Game in Java designed for absolute beginners! It uses a 2D array (matrix) to simulate a game board where a snake ('S') moves using WASD keys and tries to eat food ('F') randomly placed on the grid. Each time the snake eats the food, your score increases, and new food appears elsewhere on the board. The game ends if you hit the wall or choose to quit. ๐Ÿšง

๐ŸŽฏ What You'll Learn:

๐Ÿงฉ Concept

๐Ÿง  Logic

๐Ÿ”ค Code (SnakeGame.java)

// ๐Ÿ“ฆ Importing utility classes needed for random number generation and user input
import java.util.Random;  // ๐ŸŽฒ Used to generate random positions for food on the board
import java.util.Scanner; // โŒจ๏ธ Used to read user keyboard input (W, A, S, D, Q)

public class SnakeGame {
    public static void main(String[] args) {
        // ๐ŸŽฏ Set dimensions for the game board (10 rows x 10 columns)
        int rows = 10;
        int cols = 10;

        // ๐Ÿงฑ Create a 2D array (matrix) to represent the board
        // Each cell can be: '.' (empty), 'S' (snake), or 'F' (food)
        char[][] board = new char[rows][cols];

        // ๐Ÿ Initialize snake's starting position at the center of the board
        int snakeRow = rows / 2;  // Row index for snake's position
        int snakeCol = cols / 2;  // Column index for snake's position

        // ๐ŸŽ Variables to hold the food's position
        int foodRow, foodCol;

        // ๐ŸŽฎ Game tracking variables
        int score = 0;             // Keeps track of how much food the snake eats
        boolean isRunning = true;  // Controls whether the game loop keeps running

        // โŒจ๏ธ Create a Scanner object to read keyboard input from the user
        Scanner scanner = new Scanner(System.in);

        // ๐ŸŽฒ Create a Random object to generate random food positions
        Random random = new Random();

        // ๐Ÿ” Fill the entire board with '.' to represent empty spaces
        for (int i = 0; i < rows; i++) {        // Loop through each row
            for (int j = 0; j < cols; j++) {    // Loop through each column in the current row
                board[i][j] = '.';              // Set cell to empty
            }
        }

        // ๐Ÿ Place the snake's starting position on the board
        board[snakeRow][snakeCol] = 'S';

        // ๐ŸŽ Place the food at a random position that is NOT on the snake
        do {
            foodRow = random.nextInt(rows); // Random row between 0 and rows-1
            foodCol = random.nextInt(cols); // Random column between 0 and cols-1
        } while (board[foodRow][foodCol] == 'S'); // Repeat if it lands on the snake

        // ๐Ÿงƒ Place the food symbol on the board
        board[foodRow][foodCol] = 'F';

        // ๐Ÿ•น๏ธ Main game loop โ€” runs until player quits or hits a wall
        while (isRunning) {
            // ๐Ÿ’ฌ Display the current score to the player
            System.out.println("\nScore: " + score);

            // ๐Ÿ–จ๏ธ Print column numbers at the top of the board
            System.out.print("   "); // Extra spaces to align columns with row numbers
            for (int j = 0; j < cols; j++) {
                System.out.print(j + " "); // Print column index
            }
            System.out.println(); // Move to next line

            // ๐Ÿ–จ๏ธ Print the board row by row with row numbers on the left
            for (int i = 0; i < rows; i++) {
                System.out.print(i + "  "); // Print row index with spacing
                for (int j = 0; j < cols; j++) {
                    System.out.print(board[i][j] + " "); // Print cell content
                }
                System.out.println(); // Move to next row
            }

            // โŒจ๏ธ Ask player for movement input
            System.out.print("Move (WASD to move, Q to quit): ");
            String input = scanner.nextLine().toUpperCase(); // Read and convert to uppercase

            // โœ… Prepare to check the move
            boolean validMove = true; // Tracks if input is a valid direction
            int newRow = snakeRow;    // Temporary new row position for snake
            int newCol = snakeCol;    // Temporary new column position for snake

            // ๐Ÿงญ Decide the direction based on input
            switch (input) {
                case "W": newRow--; break; // Move up
                case "A": newCol--; break; // Move left
                case "S": newRow++; break; // Move down
                case "D": newCol++; break; // Move right
                case "Q":                  // Quit the game
                    isRunning = false;     // Stop game loop
                    continue;              // Skip rest of this loop iteration
                default:
                    // โŒ Invalid input โ€” warn player and keep snake where it is
                    System.out.println("Invalid input! Use W, A, S, D to move.");
                    validMove = false; // Mark the move as invalid
                    break;
            }

            // ๐Ÿšซ If invalid move, skip updating the snake and redraw the board
            if (!validMove) {
                continue; // Go back to top of loop
            }

            // ๐Ÿšง Check if new position is outside the board (wall collision)
            if (newRow < 0 || newRow >= rows || newCol < 0 || newCol >= cols) {
                System.out.println("๐Ÿ’ฅ Game Over! You hit the wall.");
                break; // End the game loop
            }

            // ๐Ÿงฝ Clear the snake's old position (replace with '.')
            board[snakeRow][snakeCol] = '.';

            // ๐Ÿ”„ Update snake position to new coordinates
            snakeRow = newRow;
            snakeCol = newCol;

            // ๐Ÿฝ๏ธ Check if snake moved into the food's position
            if (snakeRow == foodRow && snakeCol == foodCol) {
                score++; // Increase score

                // ๐ŸŽ Place new food somewhere not on the snake
                do {
                    foodRow = random.nextInt(rows); // Random new food row
                    foodCol = random.nextInt(cols); // Random new food col
                } while (board[foodRow][foodCol] == 'S'); // Avoid snake position

                // ๐Ÿงƒ Place new food on the board
                board[foodRow][foodCol] = 'F';
            }

            // ๐Ÿ Place snake's new position on the board
            board[snakeRow][snakeCol] = 'S';
        }

        // ๐Ÿงน Close scanner to release system resources
        scanner.close();

        // ๐ŸŽ‰ Show the player's final score after game ends
        System.out.println("๐Ÿ‘‹ Game Ended. Final Score: " + score);
    }
}

๐Ÿ“Œ Output Sample

Score: 2
   0 1 2 3 4 5 6 7 8 9
0  . . . . . . . . . .
1  . . . . . . . . . .
2  . S . . . . . . . .
3  . . . . . . . F . .
4  . . . . . . . . . .
5  . . . . . . . . . .
6  . . . . . . . . . .
7  . . . . . . . . . .
8  . . . . . . . . . .
9  . . . . . . . . . .
Move (WASD to move, Q to quit):

๐Ÿง  Key Changes & Explanation:

Feature Explanation
Food (F) Randomly placed on any empty cell on the board. If snake eats it, score increases.
Score An integer that increases each time food is eaten.
Game End If snake moves out of bounds or player quits (Q).
Random Food Re-positioned after each eating, not allowed on the snake cell.

๐Ÿง  Concepts Used in This Game:

Concept Explanation
2D Arrays Used to represent the game board (char[][] board) as a grid.
Scanner Reads user input from the keyboard.
Random Picks random positions to place the food.
Loops Used to fill and print the board, and repeat the game until quitting.
Conditions Used to check user input and whether the snake hits the wall or eats the food.
Switch Clean way to handle movement options.
Functions Main logic is inside main, split with comments into logical steps.

๐Ÿงฏ Common Mistakes to Avoid

โœ… What You Learned

๐Ÿง  Exercises โ€” Practice Time!

๐Ÿ’ก Beginner

๐Ÿงช Intermediate

๐Ÿ”ฅ Challenge

โš ๏ธ Common Mistakes in Operators & Control Flow (Java)

๐Ÿ’ก Operators

๐Ÿ’ก if / else if / else

๐Ÿ’ก Switch-Case

๐Ÿ’ก for loop

๐Ÿ’ก while loop

๐Ÿ’ก do-while loop

โœ… Operators & Control Flow (Java): Recap

๐Ÿง  Answers โ€” With Explanations & Common Mistakes

๐Ÿ’ก Beginner

๐Ÿงช Intermediate

๐Ÿ”ฅ Challenge

๐Ÿงช Modulus with Smaller Dividend

๐ŸŽ‰ That's it! You've now solved all practice questions from basic checks to loops and logic!

Now you can create decisions, loops, and intelligent logic inside your Java code. This is the step where code becomes powerful!

โ€” Blog by Aelify (ML2AI.com)

๐Ÿ“š Documentation Index