6.9: while Loops vs. for Loops

Fundamentals of MATLAB Programming · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    6.9: while Loops vs. for Loops

    A common beginner question is: How do I know whether to use a while loop or a for loop?

    Question

    Recommended Loop

    Do I know exactly how many times the loop should run?

    Use a for loop.

    Am I looping through all elements of an array?

    Usually use a for loop.

    Am I asking the user for input until the input is valid?

    Usually use a while loop.

    Am I repeating until some condition changes?

    Use a while loop.

    Am I searching until I find something?

    Either can work; a for loop with break is common.

    Note

    Use for when you know the number of repetitions. Use while when you know the condition for stopping.


    This page titled 6.9: while Loops vs. for Loops was last modified on Tue, 30 Jun 2026 02:11:42 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.