Learn Python, Microsoft 365 and Google Workspace
Connect with me: Youtube | LinkedIn | WhatsApp Channel | Web | Facebook | Twitter
To access the updated handouts, please click on the following link: https://yasirbhutta.github.io/matlab/docs/flow-control.html
Syntax:
for variable = expression
statements
end
The loop counter variable is incremented by 1 after each iteration of the loop. The loop continues to iterate until the loop counter variable is greater than the value of expression.
Question: Write a MATLAB program to print the string “Hello, world!” 10 times, using a for loop.
for i = 1:10
disp('Hello, world!');
end
Question: Write a MATLAB program to print the numbers from 1 to 5, using a for loop.
for i = 1:5
disp(i);
end
Question: Write a MATLAB program to print the numbers from 1 to 10, using a for loop.
% Print the numbers from 1 to 10 to the console.
for i = 1:10
fprintf('The number is %d\n', i);
end
Question: Write a MATLAB program to calculate the sum of the first N natural numbers using a for loop.
N = 10;
sum = 0;
for i = 1:N
sum = sum + i;
end
disp(sum);
Question: Write a MATLAB program to calculates the sum of the numbers from 1 to 100 using a for loop.
sum = 0;
for i = 1:100
sum = sum + i;
end
disp(sum);
Question: Write a MATLAB program to display the even numbers from 2 to 10, inclusive, using a for loop.
for i = 2:2:10
disp(i);
end
Question: Write a MATLAB program to calculate the sum of the even numbers from 0 to 20 using a for loop.
sum = 0;
for k = 0:2:20,
sum = sum + k;
end;
fprintf('sum %d', sum);
Question: Write a MATLAB program to calculate the sum of the elements in an array using a for loop.
sum = 0;
for arr1 = [1 5 7 6],
sum = sum + arr1;
end;
fprintf('sum = %d',sum)
Question: Write a MATLAB program to display Elements of an Array Using a for Loop.
A = [10, 20, 30, 40, 50];
for i = 1:length(A)
disp(A(i));
end
for k=1:inf
disp(k)
end
The inf
keyword in MATLAB represents infinity, so the for loop will iterate forever. This means that the program will keep printing the numbers from 1 to infinity to the console until it is stopped.
Question: Write a MATLAB program to display the multiplication table from 1 to 5, inclusive, using a nested for loop.
for i = 1:5
for j = 1:5
fprintf('%d x %d = %d\n', i, j, i * j);
end
end
See also:
The syntax for a while loop is as follows:
while expression
statements
end
The expression
is a logical expression that evaluates to true
or false
. If the expression evaluates to true, the statements in the loop body are executed. The loop then repeats, and the expression is evaluated again. This process continues until the expression evaluates to false, at which point the loop terminates.
Question: Write a MATLAB program to print the string “Hello, world!” 10 times, using a while loop?
i = 1;
while i <= 10
disp('Hello, world!');
i = i + 1;
end
Question: Write a MATLAB program to print the numbers from 1 to 10, using a while loop?
% Initialize a variable
i = 1;
% While the variable i is less than or equal to 10, print the value of i to the console
while i <= 10
fprintf('The value of i is: %d\n', i);
% Increment the variable i
i = i + 1;
end
Question: Write a MATLAB program to calculates the sum of the numbers from 1 to 100 using a while loop.
i = 1;
sum = 0;
while i <= 100
sum = sum + i;
i = i + 1;
end
disp(sum);
Question: Write a MATLAB program to calculate the sum of the even numbers from 2 to 20 using a while loop.
sum = 0; % Initialize a variable to store the sum
number = 2; % Start with the first even number
while number <= 20
sum = sum + number; % Add the current number to the sum
number = number + 2; % Increment to the next even number
end
fprintf('The sum of even numbers from 2 to 20 is: %d', sum);
Question : Write a program that prints the sum of the squares of all the numbers from 1 to 4, using a while loop.
i = 1;
while i < 5
square = i ^ 2;
fprintf('Square of %d is %d \n', i, square);
i = i + 1;
end
Question: Write a MATLAB program to prompt the user to enter lines of text until the user enters a blank line. The program should then display the message “You entered a blank line.”.
inputStr = 'Start';
while ~isempty(inputStr)
inputStr = input('Enter a line of text:', 's');
end
disp('You entered a blank line.')
Question: Write a MATLAB program to add all the numbers entered by the user until the user enters zero. The program should display the sum of the numbers.
% Initialize the sum
sum = 0;
% Prompt the user to enter a number
number = input('Enter a number: ');
% While the number entered is not zero, add the number to the sum and prompt the user to enter another number
while number ~= 0
sum = sum + number;
number = input('Enter another number: ');
end
% Display the sum of the numbers
fprintf('The sum of the numbers is: %d', sum);
This program works by initializing a variable sum to 0. Then, it prompts the user to enter a number. While the number entered is not zero, the program adds the number to the sum and prompts the user to enter another number. Finally, the program displays the sum of the numbers to the console.
The general syntax of the if statement is as follows:
if condition
statements
end
The condition
can be any logical expression. If the condition is evaluated to true
, the block of statements
is executed. Otherwise, the block of statements
is skipped.
Here is a simple example of an if statement in MATLAB:
x = 10;
if x > 5
disp('x is greater than 5.')
end
This code will print the message “x is greater than 5.” to the console.
You can also use elseif statements to check for multiple conditions. The general syntax of the elseif statement is as follows:
elseif condition
statements
end
If the condition
for the if statement is evaluated to false
, the MATLAB interpreter will check the condition
for the first elseif statement. If the condition for the elseif statement is evaluated to true
, the corresponding block of statements
is executed. Otherwise, the MATLAB interpreter will check the condition
for the next elseif statement, and so on.
Here is an example of an if statement with an elseif statement:
x = 10;
if x > 5
disp('x is greater than 5.')
elseif x < 5
disp('x is less than 5.')
end
This code will print the message “x is greater than 5.” to the console.
You can also use an else statement to check for all other conditions. The general syntax of the else statement is as follows:
else
statements
end
If all of the conditions for the if and elseif statements are evaluated to false
, the block of statements
in the else statement is executed.
Here is an example of an if statement with an elseif statement and an else statement:
x = 10;
if x > 5
disp('x is greater than 5.')
elseif x == 5
disp('x is equal to 5.')
else
disp('x is less than 5.')
end
This code will print the message “x is greater than 5.” to the console.
Question: Write a MATLAB program that takes a value for x as input and calculates y based on the following conditions:
% Input value for x
x = input('Enter a value for x: ');
% Check the condition and calculate y accordingly
if x < 5
y = 2 * x + 1;
else
y = 2 * x;
end
% Display the result
fprintf('For x = %d, y = %d \n', x, y);
Example #5: User Input Validation - Validate positive number using while loop
In this example, a while loop is used to repeatedly ask the user for a positive number until a valid input is provided.
userInput = 1; % Initialize the user input with an invalid value
while userInput >= 0
userInput = input('Enter a positive number: ');
if userInput <= 0
disp('Invalid input. Please enter a positive number.');
end
end
disp(['You entered a valid positive number: ' num2str(userInput)]);
Example:
This example shows how to use a while loop to search for a specific element in an array.
array = [1, 3, 5, 7, 9];
elementToFind = 7;
index = 1;
while index <= length(array) && array(index) ~= elementToFind
index = index + 1;
end
if index > length(array)
disp('Element not found.')
else
fprintf('Element found at index %d.', index);
end
line-by-line explanation of the above MATLAB code example:
array = [1, 3, 5, 7, 9];
This line creates an array named array containing the elements 1, 3, 5, 7, and 9. This array is used to search for a specific element.
elementToFind = 7;
This line creates a variable called elementToFind
and assigns it the value 7. This is the element that the code will search for in the array
.
index = 1;
This line initializes a variable index to 1. This variable will be used to keep track of the current index while searching for elementToFind.
while index <= length(array) && array(index) ~= elementToFind
index = index + 1;
end
This is the start of a while loop. It continues to execute as long as two conditions are met:
index
is less than or equal to the length of the array
.array
(given by array(index)
) is not equal to elementToFind.Inside the loop, the index
is incremented by 1 in each iteration. This loop effectively searches for elementToFind
in the array
.
if index > length(array)
disp('Element not found.')
else
fprintf('Element found at index %d.', index);
end
This is an if statement. If the index
variable is greater than the length of the array
, then the code displays the message “Element not found.” Otherwise, the code displays the message “Element found at index %d.”, where %d is the index of the elementToFind
.
To summarize, this code searches for elementToFind in the array using a while loop and reports whether the element was found or not. The result is displayed in the console.
Output:
Element found at index 4.
or
switch switch_expression
case case_expression_1
statements_1
case case_expression_2
statements_2
...
otherwise
statements_otherwise
end
Question:Write a MATLAB program that prompts the user to enter a color code (R, G, or B) and then prints the corresponding color name (Red, Green, or Blue) to the console. If the user enters an invalid color code, the program should print “Invalid color code.”
% Create a variable to store the selected color.
selectedColor = input('Enter a color code (R, G, B): ', 's');
% Write a switch statement with cases for each color that you want to support.
switch selectedColor
case 'R'
fprintf('The selected color is Red.\n');
case 'G'
fprintf('The selected color is Green.\n');
case 'B'
fprintf('The selected color is Blue.\n');
otherwise
fprintf('Invalid color code.\n');
end
Questions: Write a MATLAB program that prompts the user to enter a day of the week (Monday, Tuesday, Wednesday, Thursday, or Friday) and then prints a different message to the console depending on the day of the week that the user enters.
% Prompt the user to enter the day of the week as a number (1-7)
day = input('Enter day of the week (1-7): ');
% Switch statement to display a different message based on the entered day
% Each case represents a different day of the week
switch day
case 1 % Monday
disp("Have a great week!");
case 2 % Tuesday
disp("Don't forget to water the plants!");
case 3 % Wednesday
disp("Have a good day!");
case 4 % Thursday
disp("Almost there!");
case 5 % Friday
disp("Have a good weekend!"); % Fixed the incomplete message
otherwise % Catch any days not explicitly listed (e.g., weekends)
disp("Have a great day!");
end
Answer: Here are some tips for using while loops effectively:
- Use a while loop when you need to execute a block of code repeatedly as long as a condition is true.
- Make sure to update the condition variable in the loop body.
- Test your loops carefully to make sure that they are working as expected.
Answer: Some common mistakes that people make when writing while loops in MATLAB include:
- Infinite loops: This occurs when the condition for the while loop is always true, which causes the loop to execute forever.
- Unreachable code: This occurs when the code inside the while loop is never executed because the condition for the loop is never met.
Answer: A for loop is used to execute a block of code a fixed number of times. A while loop is used to execute a block of code repeatedly as long as a condition is true.
Answer: Infinite loops can be dangerous because they can cause MATLAB programs to crash or become unresponsive.
Answer:
The main difference between fprintf
and disp
is that fprintf
allows you to control the format of the output, while disp
simply prints the output to the command window in a default format.
fprintf
uses a format string to specify the format of the output. The format string can contain characters such as %d
for integers, %f
for floating-point numbers, and %s
for strings. You can also use the format string to control the number of decimal places, the alignment of the output, and other formatting options.
disp
, on the other hand, does not use a format string. It simply prints the output to the command window in a default format. The default format is to print one variable per line, with the variable value.
Here is an example of how to use fprintf
to control the format of the output:
fprintf('The value of pi is %.2f.\n', pi);
This code will print the following output to the command window:
The value of pi is 3.14.
The %.2f
format string tells fprintf
to print the value of pi
with two digits to the right of the decimal point.
Here is an example of how to use disp
to print the value of a variable:
disp(pi);
This code will print the following output to the command window:
3.14159
disp
simply prints the variable value.
In general, you should use fprintf
when you need to control the format of the output. You should use disp
when you simply need to print the value of a variable to the command window.
Here is a table that summarizes the key differences between fprintf
and disp
:
Feature | fprintf | disp |
---|---|---|
Controls the format of the output | Yes | No |
Uses a format string | Yes | No |
Default format | None | Prints the variable value |
Use cases | When you need to control the format of the output | When you simply need to print the value of a variable to the command window |
Example output:
Enter a number: 5
Multiplication table for 5
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
for k=1:inf
disp(k)
end
Answer: The problem with the following MATLAB program is that it uses an infinite for loop. Infinite for loops will run forever, which can cause the program to crash or to consume all of the available memory.
N = 10;
sum = 0;
for i = 1:N
sum = sum + i;
end
disp(sum);
Output:
The square of 7 is 49
The square of 6 is 36
The square of 10 is 100
Output:
*
**
***
****
*****
“Even number” if the number is even. “Odd number” if the number is odd.
“Weekday” if the day of the week is Monday through Friday. “Weekend” if the day of the week is Saturday or Sunday.
Write a MATLAB program that prompts the user to enter a day of the week and then prints a different message to the console depending on the day of the week that the user enters. The messages should be “Have a great week!”, “Don’t forget to water the plants!”, “Have a good day!”, “Almost there!”, “Have a good weekend!”, and “Invalid day of the week.”.
Write a MATLAB program that prompts the user to enter a number between 1 and 100 and then prints whether the number is even or odd to the console.
Write a MATLAB program that prompts the user to enter two numbers and then prints the larger number to the console.
i = 1;
while i < 5
square = i ^ 2;
fprintf('Square of %d is %d \n', i, square);
i = i + 1;
end
True/False
For loop:
What is the default increment value for a MATLAB for loop?
Which of the following is the correct syntax for a for loop in MATLAB?
What is the purpose of the increment expression in a for loop?
In MATLAB, what is the primary purpose of a for loop?
What is the structure of a for loop in MATLAB?
How is the loop variable updated in a for loop?
What is the output of the following for loop?
for i = 1:5
disp(i);
end
What is the expected output of the following MATLAB code?
for i = 2:2:10
disp(i);
end
What is the expected output of the following MATLAB code?
sum = 0;
for i = 1:5
sum = sum + i;
end
disp(sum);
What is the expected output of the following MATLAB code?
for i = 1:4
if i == 3
continue;
end
disp(i);
end
What is the expected output of the following MATLAB code?
for i = 1:5
if i == 3
break;
end
disp(i);
end
while loop:
What is the purpose of a while loop?
What is the output of the following MATLAB code?
i = 1;
while i <= 5
fprintf('%d\n', i);
i = i + 1;
end
What happens if a MATLAB while loop has a condition that is always true?
What is the purpose of the end statement in a while loop in MATLAB?
Which of the following best describes the flow of control in a while loop?
What happens if the condition in a while loop is never met?
How many times a while loop execute if the condition is initially false?
if and switch:
Which of the following is the correct syntax for an if statement in MATLAB?
In a switch statement, what happens if none of the case conditions match the expression?
In MATLAB, what is the keyword used to specify the default case in a switch statement?
In a MATLAB if statement, what happens if the condition is false and there is no else block?
In a for loop, what does the continue statement do in MATLAB?
Which keyword is used to end an if statement in MATLAB?
In MATLAB, the switch statement is primarily used for:
In a switch statement in MATLAB, what happens if none of the cases match, and there is no otherwise block?
What is the difference between an if statement and a switch statement?
break and continue:
In a MATLAB loop, what does the continue statement do?
What is the purpose of the break statement in a loop?
What does the following MATLAB code do?
for i = 1:10
if i == 5
break;
end
disp(i);
end
What does the following MATLAB code do?
for i = 1:10
if i == 5
continue;
end
disp(i);
end
Which of the following will exit the loop early?
[^1] while loop to repeat when condition is true - MATLAB while