Strong Foundation Notes
1. Switch Statements (Revision for Deeper Understanding)
What is a Switch Statement?
- A decision-making structure.
- It lets a program choose one block of code to run based on the value of a variable.
- It’s like choosing a path:
* If the value is X → follow case X.
* If the value is Y → follow case Y.
* If no match → follow default.
Syntax (Structure)
switch (variable) {
case value1:
// code to run if variable == value1
break;
case value2:
// code to run if variable == value2
break;
default:
// code if no case matches
}
Important Notes
1. Switch only checks ONE variable at a time.
2. Each case must end with a break (otherwise the program 'falls through' to the next case).
3. The default case is optional, but useful to handle unexpected input.
4. Data types allowed in switch: int, char, String (Java 7+), and some enums.
Example (Days of the Week)
int day = 4;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
case 4: [Link]("Thursday"); break;
case 5: [Link]("Friday"); break;
default: [Link]("Weekend");
}
Output: Thursday
2. While Loops (Introduction with Strong Foundation)
What is a Loop?
- A loop is used when we want to repeat a set of instructions.
- Instead of copying the same code many times, we use a loop.
Example (Without a loop):
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
Example (With a loop):
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
While Loop Definition
- A while loop repeats a block of code as long as the condition is TRUE.
- If the condition is false at the beginning, the loop will not run at all.
Syntax:
while (condition) {
// code to repeat
}
Example 1: Counting
int i = 1;
while (i <= 5) {
[Link]("Number: " + i);
i++;
}
Output: Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
Example 2: User Input Until Stop
import [Link];
public class WhileExample {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
int num;
[Link]("Enter a number (0 to stop): ");
num = [Link]();
while (num != 0) {
[Link]("You entered: " + num);
[Link]("Enter a number (0 to stop): ");
num = [Link]();
}
[Link]("Program ended.");
}
}
Key Points for While Loops
1. Condition is checked first → if false, loop never runs.
2. Always update the variable inside the loop, otherwise → infinite loop.
3. Best used when we don’t know how many times the loop should run (depends on condition).
3. Comparing Switch vs While (Foundation Link)
- Switch → for decision making (choosing 1 option from many).
- While → for repetition (doing the same action many times).
Together:
- Switch helps us decide what to do.
- While helps us repeat it until condition changes.
4. Activity for Students
Write a program that keeps showing a menu: 1. Say Hello 2. Say Bye 3. Exit - Use switch to decide
the action. - Use while to keep the menu running until the user chooses Exit.