7.2: Flowcharts
- Page ID
- 84477
By Carey A. Smith
A flowchart is a graphical representation of code logic. It is especially helpful to understand the logic of code with for loops and if-else logic.
An example is given here. More information can be found at:
https://en.wikipedia.org/wiki/Flowchart [en.Wikipedia.org]
Try to code this up
Solution
The corresponding code is:
for n = 1:12
if(mod(n,2) == 0)
disp([num2str(n),' is even'])
else
disp([num2str(n),' is odd'])
end
end
.
flowchart for primes
This flowchart and code show an algorithm to determine which numbers between 1 and 48 are prime numbers.
We already know that 2, 3, and 5 are prime, so the for loop starts at k = 6.
For each value it tests, it displays a message stating whether or not it is a prime number. It stores the prime numbers it finds in a vector called prime_list.
Try coding this logic.
Note that the for-loop automatically does the "k = k+1" shown at the bottom of the flowchart; do not code that line.
(There are more sophisticated and efficient prime-number algorithms; this one is an illustration of moderately complex logic.)
Solution
%% "for loop" example with “if-then-elseif” logic:
% Find the prime numbers between 1 to 48:
prime_list = [2,3,5] % Initial set of primes
for k = 6:48
if( mod(k,2) == 0) % Tests if k is divisible by 2
disp([num2str(k),' is not prime. It is divisible by 2'])
elseif (mod(k,3) == 0) % Tests if k is divisible by 3
disp([num2str(k),' is not prime. It is divisible by 3'])
elseif( mod(k,5) == 0) % Tests if k is divisible by 5
disp([num2str(k),' is not prime. It is divisible by 5'])
else
disp([num2str(k),' is prime.'])
% Add k to the list of primes:
prime_list = [prime_list, k];
end % end if
end % for k = 6:48
% Display the primes found
prime_list
This code is the attached file for_loop_primes.m
.
Homework:
1. Watch the following video from Robert Talbert
Then code the second example in the video about the temperature and rain. The corresponding flowchart is this:
Figure \(\PageIndex{i}\): Flowchart for Temperature, Rain, Wearing a Coat.
Put parentheses around the conditional expressions, even though the video did not do this. Examples:
if (temp < 50)
elseif (raining == 1)
.