MATLAB while Loop

MATLAB Tutorial

🔁 MATLAB while Loop 

The while loop in MATLAB is used to repeat a block of code as long as a condition remains true.

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

1
2
3
4
5

3️⃣ Sum of Numbers Using while Loop


 

Output

15

4️⃣ while Loop with Condition Check


 

Output

10
8
6
4
2

5️⃣ Using Logical Operators in while


 

Output

1
2
3
4

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 break to 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

  • while loop runs based on condition

  • Iterations are not fixing

  • Condition checked before each iteration

  • Powerful for condition-controlled loops

You may also like...