While Loop Concept in MATLAB | MATLAB Tutorials

while loop in C programming repeatedly executes a target statement as long as a given condition is true.

Syntax of While Loop:

The syntax of a while loop in C programming language is:

while (conditions)
{ statements
}

 

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.

When the condition becomes false, the program control passes to the line immediately following the loop.

Program Using while loop in MATLAB
% Generate Guessing Game In MatlaB.
%generate a Random integer between 1 and 100.
clc
clear all
count=0;
a=randi([1,100]);
%Ask the user to guess the number.
fprintf('I''m thinking of a whole number between 1 and 100\n');
guess=input('Guess a number:');
while guess~=a
count=count+1;
if guess < a
% fprintf use to print the anything.
fprintf('The Guess was too low\n');
guess=input('Guess again > ');
else
fprintf('The Guess was too High\n');
guess=input('Guess again > ');
end
end
fprintf('Congratulations!You gueesed the corrected number in %g shots.\n ',count+1);
pause();

Copy above code in Editor window to create .M file and run program.

You may also like...

Leave a Reply