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! ๐ก
These perform basic math operations.
| Operator | Description | Example |
|---|---|---|
| + | Addition | a + b |
| - | Subtraction | a - b |
| * | Multiplication | a * b |
| / | Division | a / b |
| % | Remainder (Modulus) | a % b |
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 |
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 |
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)
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)
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)
// 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
// 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 ==, !=, >, <, >=, <=
// 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
// 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
// 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 >
// 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!
// 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
// 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
// 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)
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
}
}
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
}
}
!.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
}
}
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.
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").
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.
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.
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.
| 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) |
if, else if, and else Concept Challengesif, else if, and else Challenge Solutionspublic 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();
}
}
Switch-Case Concept Challengespublic 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();
}
}
for Loop Concept Challengesfor loop that prints all
numbers starting from 1 up to 10, each on a new line.N. Use a loop
to
calculate and print the sum of numbers from 1 to N.for loop to print all even numbers
between
1 and 50 (inclusive), separated by spaces.for loop.N. Use a loop to compute
the
factorial of N (i.e., N!) and display the result.number^2 = result.N, then use a loop
to
calculate and print the sum of all odd numbers from 1 to N.for loops to print a right-angled
triangle of asterisks (*) with 5 rows.break) when the number 42 is reached.
N terms of the sequence.for Loop Challenge Solutionspublic 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();
}
}
while Loop Concept Challengeswhile loop to print numbers
from 1 to 10.while loop to print a countdown from 10 down to
1.
while loop.
while loop.while loop.
-1 to exit.while loop to print powers of 2 starting
from 1 up to 1024.while loop.while loop to calculate the sum of
all
even numbers from 1 to 100.while loop.while Loop Challenge Solutionsimport 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();
}
}
do-while Concept Challengesdo-while loop to print numbers from 1 to 10.
No
user input is required.N. Use a
do-while loop to find and print the sum of numbers from 1 to N.
do-while loop to
print
its multiplication table up to 10.do-while loop to
reverse the digits of that number (e.g., input: 1234 โ output: 4321).do-while loop to check
whether the number is a palindrome (reads the same forwards and backwards).do-while loop to count
how
many digits the number has.do-while loop to print all even numbers
between 1
and 50 (inclusive). No user input required.do-while loop to calculate
and
print its factorial (e.g., 5 โ 120).do-while loop to
compute
and display the sum of its digits.do-while loop to repeatedly ask the user to enter
a
number until they provide a positive number.do-while loop to convert and display its binary representation (as an integer).
do-while
loops to print a right-angled triangle pattern of stars (*) up to that number of rows.do-while loop to print a countdown from 10 to 1. No user
input is
required.do-while loop to generate and display that many terms.
N. Use a
do-while loop to calculate and print the sum of all odd numbers from 1 to N.
do-while Challenge Solutionsimport 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();
}
}
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
}
do-while loop.place helps put binary digits in the right place: units, tens, hundreds.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
}
do-while and divide repeatedly by 2 (same as above).1 and subtract 1.0.do-while) up to 10 times or until the fraction becomes 0.. in the middle.Integer Input: 13
Binary: 1101
Decimal Input: 5.75
Integer part: 5 โ 101
Fraction part: .75 โ .11
Binary: 101.11
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
}
place to multiply the bits into correct position: 1s, 10s, 100s, etc.// 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
}
intPart = 5, fracPart = 0.75Integer Input: 13
Binary: 1101
Decimal Input: 5.75
Integer part: 5 โ 101
Fraction part: .75 โ .11
Binary: 101.11
| 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) |
do-while or while?do-while when you want the loop to run at least once no matter what.
Example:
converting a number that could be zero.while when the condition must be true before running even the first time.
It's
slightly safer in input-sensitive scenarios.do-while is a better fit when
converting
0 or small numbers (guarantees 1 run).The factorial of a number n is the product of all positive integers from
1 to n.
fact = 1.fact by each value.fact after the loop ends.for Loopimport 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);
}
}
while Loopimport 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);
}
}
do-while Loopimport 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);
}
}
for is best for fixed iterations; while and do-while are useful for
variable conditions.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.
for looppublic 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
}
}
}
while looppublic 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
}
}
}
do-while looppublic 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);
}
}
a = 0, b = 10 1c = a + bca = b, b = cn terms are printedThe 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.
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;
}
limit.a and b accordingly in each iteration.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;
}
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.
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.
for Loopint 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:
num % i == 0i as a factorwhile Loopint 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:
i = 1i <= numido-while Loopint 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:
i = 1do-while to ensure the loop runs at least oncei until i > numFactors 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
Count the number of digits in an integer using for, while, and do-while
loops.
If the number is 4567, it has 4 digits.
for Loopint num = 4567;
int count = 0;
for (int temp = num; temp != 0; temp /= 10) {
count++;
}
System.out.println("Digit Count: " + count);
temp = num.temp != 0.temp /= 10.count until temp becomes 0.while Loopint num = 4567;
int count = 0;
int temp = num;
while (temp != 0) {
count++;
temp /= 10;
}
System.out.println("Digit Count: " + count);
num to temp.temp != 0.temp by 10 and increment count.do-while Loopint num = 4567;
int count = 0;
int temp = num;
do {
count++;
temp /= 10;
} while (temp != 0);
System.out.println("Digit Count: " + count);
temp by 10.temp != 0.num = 0, all loops must still return 1 digit.if (num == 0), return 1 directly or handle it in
do-while.
Digit Count: 4
Below we calculate:
for loopint 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);
% 10 extracts the last digit/= 10 removes the last digitif (digit % 2 == 0) checks for evenwhile loopint 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);
do-while loopint 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);
Digits: 4
Sum: 15
Even digits: 3
Odd digits: 1
| 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 |
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
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.");
}
}
}
number % 10: Extracts the last digit.digit * digit * digit: Cubes the digit.number /= 10: Removes the last digit (integer division).while (number > 0) Instead of while (number != 0)?!= 0: If number is negative, it never becomes 0 โ leads to
infinite
loop.| 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 |
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.
A palindrome number is a number that remains the same when its digits are reversed. For example,
121, 1331, and 454 are palindromes.
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.");
}
}
}
number % 10: Extracts the last digit.reversed = reversed * 10 + digit: Builds the reversed number.number /= 10: Removes the last digit.while (number > 0) and Not while (number != 0)?number != 0 can cause infinite loop for negative
input.
number > 0 safely skips
negatives.| 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 |
Use while (number > 0) to safely reverse digits when checking for palindromes. It's more robust
and
avoids accidental infinite loops from negative numbers.
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.
for Looppublic 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();
}
}
}
while Looppublic 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++;
}
}
}
do-while Looppublic 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);
}
}
i has i stars.| 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 |
*
* *
* * *
* * * *
* * * * *
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.
*
* *
* * *
* * * *
* * * * *
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
int i = 1;
while (i <= 5) {
int j = 1;
while (j <= i) {
System.out.print("* ");
j++;
}
System.out.println();
i++;
}
int i = 1;
do {
int j = 1;
do {
System.out.print("* ");
j++;
} while (j <= i);
System.out.println();
i++;
} while (i <= 5);
* * * * *
* * * *
* * *
* *
*
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
int i = 5;
while (i >= 1) {
int j = 1;
while (j <= i) {
System.out.print("* ");
j++;
}
System.out.println();
i--;
}
int i = 5;
do {
int j = 1;
do {
System.out.print("* ");
j++;
} while (j <= i);
System.out.println();
i--;
} while (i >= 1);
*
* *
* * *
* * * *
* * * * *
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();
}
* * * * *
* * * *
* * *
* *
*
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();
}
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
// 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();
}
n).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();
}
i) runs from 1 to n โ number of rows.j) runs from 1 to i โ print increasing numbers per row.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();
}
n to 1.Create a centered pyramid and its inverted version using numbers.
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();
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
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();
}
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
System.out.print(j + " "); adds a number and a space for proper width.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();
}
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
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();
}
num starts at 1 and increases with each printed number.i contains exactly i numbers.n = 5:1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
StringIn 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.
// 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"
Let's print each character in a string using all 3 loops.
for loopString str = "Java";
for (int i = 0; i < str.length(); i++) {
System.out.println(str.charAt(i));
}
while loopString str = "Java";
int i = 0;
while (i < str.length()) {
System.out.println(str.charAt(i));
i++;
}
do-while loopString str = "Java";
int i = 0;
do {
System.out.println(str.charAt(i));
i++;
} while (i < str.length());
String variable with a value, e.g., "Java".charAt(i).J
a
v
a
String is an object that represents character sequences.for, while, or do-while to iterate over each character.
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.
Think of a class like a blueprint or a template for something real โ like a Student, Car, or Animal.
class tells Java what things (data) an object should have, and what it can do (methods).
constructor is like a door that lets you create objects with specific values.method is like a behavior โ it tells the object what to do (like speak or display info).
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.
name and age).main(): Make real students using new keyword.
for, while, or
do-while to show all their info.
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).
Always start by asking: "What do I want to model?" โ That will become your class.
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);
}
}
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();
}
}
You can use loops to handle multiple class objects efficiently.
for loopclass 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();
}
}
}
while loopclass 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++;
}
}
}
do-while loopclass 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);
}
}
new keyword to instantiate the class.Name: Aelify, Age: 20
Name: Bob, Age: 21
Name: Charlie, Age: 22
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.
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]);
}
}
}
whilepublic 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++;
}
}
}
do-whilepublic 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);
}
}
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);
}
}
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();
}
}
}
Imagine an array like a row of mailboxes ๐ฌ. Each one holds a number and has a label: 0, 1, 2... etc.
int[] numbers;{10, 20, 30, 40, 50}numbers[0] to see what's inside the first boxfor or while
loop
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!
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
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.
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();
}
}
}
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();
}
}
}
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
}
}
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();
}
}
}
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();
}
}
}
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();
}
}
}
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();
}
}
}
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();
}
}
}
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();
}
}
}
matrix[i][j]โ With these tools, you can now build anything from a spreadsheet to a tic-tac-toe game using matrices!
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.
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!");
}
}
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
}
}
๐ 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. ๐ง
ScannerRandom10x10 2D array to represent the game board.'.' (empty space).'S'.'F'.Scanner to read player input: W (up), A (left), S
(down), D (right), Q (quit).'.'.'S'.// ๐ฆ 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);
}
}
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):
| 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. |
| 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. |
import java.util.Random; or import java.util.Scanner;,
your program won't compile. Java won't recognize Random or Scanner without these
imports.
Scanner object with scanner.close() at the end of the program to
free
system resources.
Scanner for System.in can cause unexpected behavior or skipped
inputs.
Reuse the same instance throughout the program.
random.nextInt() without an argument will throw an error.
Always specify the bound, e.g., random.nextInt(rows) to stay within the board range.
rows,
cols, snakeRow, and snakeCol.
Random (for random numbers) and
Scanner (for user input)
Randomif.for loop.&&.switch to print weekday names from number (1-7).while loop to print first 5 even numbers.= (assignment) with == (equality)== for comparing strings instead of .equals()5/2 gives 2)! without proper parentheses (e.g., !a == b)a && b || c without understanding operator precedence& and && or | and ||a = b = c without realizing assignment returns a valueint + double)if (condition); with an unintended semicolon{ } for multiple statements in an if blockelse without a preceding ifif / else if laddersif (a = 5) instead of ==)if statements without clear indentationif (x != 0 && y/x > 1))if where a switch would be cleanerelse to handle unanticipated casesbreak in switch cases, causing fall-throughcase labelsdefault case in switch statementfloat) in switch expressionscase values, causing compile errors== for string matching in switch instead of Java 7+ string switch
// โ Incorrect way: using '==' for string comparison
String fruit = "apple";
if (fruit == "apple") {
System.out.println("Fruit is apple");
}
// โ
Better: using switch with String (Java 7+)
switch (fruit) {
case "apple":
System.out.println("Fruit is apple");
break;
case "banana":
System.out.println("Fruit is banana");
break;
default:
System.out.println("Unknown fruit");
}
break that is never reachedswitch statements without braces or claritycase blocks (e.g., duplicate constants)switch supports only specific types (e.g., int, char,
String)
i <= n instead of <)i inside i)for loops (e.g., i-- instead of
i++)
while (infinite loop)while instead of do-while when at least one execution is requiredwhile to repeat foreverdo-while without understanding it runs at least oncedo incorrectly (do; { ... })while(condition);break and continue poorly inside do-while+, -, *, /, %)
for
calculations==, !=, >, <,
>=, <=) to compare values
&&, ||, !) combine or invert conditionsif, else if, else to handle conditional branchingswitch is useful for multi-way branching with fixed valuesfor loops are ideal when the number of iterations is knownwhile loops are used when the condition must be true before entering the loopdo-while loops run the block at least once before checking the conditioncondition ? trueValue : falseValue) offers a concise alternative to simple
if-elsepublic class PositiveNegativeZero {
public static void main(String[] args) {
int number = -5; // Change this to test different numbers
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
}
}
โ Explanation:
if (number > 0) โ Runs when the number is greater than zero.else if (number < 0) โ Runs when the number is less than zero.else โ Runs when the number is exactly zero.โ Common Mistakes:
= instead of == for equality (causes assignment, not comparison).
if statements instead of else if, which may cause multiple
outputs.
for loop
public class PrintOneToTen {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
โ Explanation:
i = 1.i <= 10 ensures it runs until i reaches 10.i++ increases i by 1 each time.โ Common Mistakes:
i < 10 instead of i <= 10, which prints only 1-9.i inside the loop (e.g., i = 1;), causing an infinite loop.i++, which also causes an infinite loop.public class DivisibleByTwoAndThree {
public static void main(String[] args) {
int number = 12; // Change this to test
if (number % 2 == 0 && number % 3 == 0) {
System.out.println("Divisible by both 2 and 3");
} else {
System.out.println("Not divisible by both");
}
}
}
โ Explanation:
% (modulus) finds the remainder.number % 2 == 0 โ divisible by 2.number % 3 == 0 โ divisible by 3.&& means both conditions must be true.โ Common Mistakes:
|| instead of && โ checks if divisible by 2 or 3,
not both.
number % 2 = 0 โ assignment instead of comparison, causing a compilation error.
switch to print weekday names from number (1-7)
public class WeekdaySwitch {
public static void main(String[] args) {
int day = 3; // Change to test different days (1-7)
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Invalid day");
}
}
}
โ
Explanation: The switch statement checks the value of day
against
each case.
When a match is found, the corresponding block runs. break stops the execution from
continuing into
the next case.
The default case runs when none of the cases match.
โ Common Mistakes:
break, which causes the program to execute all following cases
("fall-through").
default case โ this means invalid inputs won't be handled.default.while loop to print first 5 even numbers
public class FirstFiveEvens {
public static void main(String[] args) {
int count = 0; // How many even numbers printed
int number = 2; // Start from the first even number
while (count < 5) {
System.out.println(number);
number += 2; // Jump to the next even number
count++; // Keep track of how many printed
}
}
}
โ
Explanation: The while loop runs as long as count < 5.
Each
time it prints the current
even number, increases it by 2, and increments count to eventually stop the loop.
โ Common Mistakes:
count or number โ causes an infinite loop.number at 0 if you want numbers from 2 โ leads to wrong sequence.<= 5 instead of < 5 with count โ prints 6 numbers
instead
of 5.public class EvenOddTernary {
public static void main(String[] args) {
int num = 7; // Change this to test
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
}
}
โ
Explanation: The ternary operator ?: is a shorthand for
if-else.
Here, (num % 2 == 0) checks if the number is divisible by 2. If true, it assigns
"Even" to result,
otherwise "Odd".
โ Common Mistakes:
= instead of == in the condition โ causes unintended assignment.
; inside the ternary โ breaks the expression.public class SimpleCalculator {
public static void main(String[] args) {
int a = 10, b = 5;
char op = '*';
switch (op) {
case '+': System.out.println(a + b); break;
case '-': System.out.println(a - b); break;
case '*': System.out.println(a * b); break;
case '/':
if (b != 0) {
System.out.println(a / b);
} else {
System.out.println("Cannot divide by zero");
}
break;
default: System.out.println("Invalid operator");
}
}
}
โ
Explanation: The switch checks the value of op and performs
the
corresponding arithmetic operation.
For division, we check b != 0 to prevent division by zero.
โ Common Mistakes:
break โ leads to executing multiple cases unintentionally."+" (String) instead of '+' (char) for op.public class ReverseNumber {
public static void main(String[] args) {
int num = 1234;
int reversed = 0;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
System.out.println("Reversed: " + reversed);
}
}
โ
Explanation: We extract the last digit with num % 10, multiply the
reversed
number by 10 to shift digits,
then add the extracted digit. We remove the last digit from num using integer division.
โ Common Mistakes:
num /= 10 โ causes an infinite loop.% and / โ leads to incorrect results.public class TrianglePattern {
public static void main(String[] args) {
int rows = 5;
// Triangle pattern
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
public class SquarePattern {
public static void main(String[] args) {
int size = 5;
// Square pattern
for (int i = 1; i <= size; i++) {
for (int j = 1; j <= size; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}
โ Explanation:
size times, so each row has the
same
number of stars.System.out.print keeps printing on the same line, while
System.out.println() moves
to the next line after each row.
โ Common Mistakes:
print and println โ breaks the pattern layout.< instead of <= in loops โ causes missing stars or rows.import java.util.Scanner;
public class CalculatorUserInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter first number: ");
if (!sc.hasNextDouble()) {
System.out.println("Invalid number! Please restart the program.");
return;
}
double a = sc.nextDouble();
System.out.print("Enter operator (+, -, *, /): ");
String opInput = sc.next();
if (opInput.length() != 1 || "+-*/".indexOf(opInput.charAt(0)) == -1) {
System.out.println("Invalid operator! Please restart the program.");
return;
}
char op = opInput.charAt(0);
System.out.print("Enter second number: ");
if (!sc.hasNextDouble()) {
System.out.println("Invalid number! Please restart the program.");
return;
}
double b = sc.nextDouble();
switch (op) {
case '+': System.out.println("Result: " + (a + b)); break;
case '-': System.out.println("Result: " + (a - b)); break;
case '*': System.out.println("Result: " + (a * b)); break;
case '/':
if (b != 0) {
System.out.println("Result: " + (a / b));
} else {
System.out.println("Cannot divide by zero");
}
break;
}
} finally {
sc.close();
}
}
}
โ
Explanation: This version checks for invalid numbers using
hasNextDouble() and
validates the operator string before performing the calculation.
โ Common Mistakes:
hasNextDouble() before reading numbers โ causes program crash if letters
are
entered.++ โ this code prevents that.finally or close() โ leads to resource leaks.import java.util.Scanner;
public class ComplexCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean running = true;
while (running) {
try {
System.out.print("Enter first number: ");
if (!sc.hasNextDouble()) {
System.out.println("Invalid number! Please try again.");
sc.next(); // clear wrong input
continue;
}
double a = sc.nextDouble();
System.out.print("Enter operator (+, -, *, /, %): ");
String opInput = sc.next();
if (opInput.length() != 1 || "+-*/%".indexOf(opInput.charAt(0)) == -1) {
System.out.println("Invalid operator! Please try again.");
continue;
}
char op = opInput.charAt(0);
System.out.print("Enter second number: ");
if (!sc.hasNextDouble()) {
System.out.println("Invalid number! Please try again.");
sc.next(); // clear wrong input
continue;
}
double b = sc.nextDouble();
switch (op) {
case '+': System.out.println("Result: " + (a + b)); break;
case '-': System.out.println("Result: " + (a - b)); break;
case '*': System.out.println("Result: " + (a * b)); break;
case '/':
if (b != 0) {
System.out.println("Result: " + (a / b));
} else {
System.out.println("Cannot divide by zero");
}
break;
case '%':
if (b != 0) {
System.out.println("Result: " + (a % b));
} else {
System.out.println("Cannot perform modulo by zero");
}
break;
}
System.out.print("Do you want to calculate again? (yes/no): ");
String choice = sc.next();
if (!choice.equalsIgnoreCase("yes")) {
running = false;
}
} catch (Exception e) {
System.out.println("Unexpected error: " + e.getMessage());
sc.next(); // clear bad input
}
}
sc.close();
System.out.println("Calculator closed.");
}
}
โ
Explanation: This version uses hasNextDouble() and operator validation to
prevent crashes. It runs in a loop and keeps asking until the user chooses to exit.
โ Common Mistakes:
sc.next() โ without this, the loop keeps reading the
same bad
input forever.== for strings instead of equalsIgnoreCase() โ this breaks string
comparison.public class ModulusDemo {
public static void main(String[] args) {
System.out.println(2 % 3); // integer modulus
System.out.println(2 % 3.0); // double modulus
double result = 5.5 % 2.2; // raw double result
System.out.println(Math.round(result * 100.0) / 100.0); // rounded to 2 decimals
}
}
2
2.0
1.1
โ
Explanation: The modulus operator (%) returns the remainder after
division.
2 % 3 โ Since 2 is smaller than 3, the quotient is 0 and the remainder is 2 (integer).
2 % 3.0 โ One operand is a double, so Java promotes the result to
double, giving 2.0.
5.5 % 2.2 โ The quotient is 2 (truncated), raw result is
1.0999999999999996 due to
floating-point precision.
Using rounding: Math.round(result * 100.0) / 100.0 โ 1.1.
remainder = dividend - (divisor ร truncatedQuotient)
โ Common Mistakes:
double, the result is also
double.
๐ 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