MATLAB while Loop
🔁 MATLAB while Loop
It is mainly used when the number of iterations is not known in advance.
MATLAB is developed by MathWorks.
🔹 What Is a while Loop?
A while loop:
-
Checks the condition before each iteration
-
Executes code while the condition is true
-
Stops when the condition becomes false
1️⃣ Basic while Loop Syntax
📌 end is mandatory.
2️⃣ Simple while Loop Example
Output
3️⃣ Sum of Numbers Using while Loop
Output
4️⃣ while Loop with Condition Check
Output
5️⃣ Using Logical Operators in while
Output
6️⃣ Infinite while Loop (⚠️ Careful)
📌 Stops only using Ctrl + C.
⚠️ Important Rules
-
Condition must be logical
-
Loop variable must be updated inside the loop
-
Infinite loops occur if condition never becomes false
-
Use
breakto exit loop early
🎯 Interview Questions: MATLAB while Loop
🔹 Q1. When should you use a while loop?
Answer:
When the number of iterations is not known beforehand.
🔹 Q2. What happens if the condition is false initially?
Answer:
The loop body will not execute at all.
🔹 Q3. Is end mandatory in while loop?
Answer:
Yes.
🔹 Q4. How do you stop an infinite loop?
Answer:
Using Ctrl + C or break.
🔹 Q5. Can logical operators be used in while condition?
Answer:
Yes (&&, ||, ~).
🔹 Q6. Difference between for and while loop?
Answer:for → known iterations,while → unknown iterations.
🔹 Q7. What causes infinite loops?
Answer:
When loop condition never becomes false.
✅ Summary
-
whileloop runs based on condition -
Iterations are not fixing
-
Condition checked before each iteration
-
Powerful for condition-controlled loops
