How to print all prime numbers between 1 and 100 using a for loop?

for f = (1:100)
f
isprime(f)
j = all(f)
end
fprintf('%j',j)
This is what I have, I either get j as logical or if I change it to "fprintf('%f', f)" I get f = 100.
I need to print the prime numbers.
What am I doing wrong?

 Accepted Answer

num = 1:100 ; % numbers till 100
idx = isprime(num) ; % get logical indices of prime numebrs
num(idx) % print the prime numbers
ans = 1×25
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

7 Comments

Ok, so that does work, but I forgot to mention that I need to print the prime numbers, How do I do that?
Hey num(idx) will print the prime numbers on screen. Did you run the code?
Yes I ran it, but I was trying to get it without the '[ ]' for non-prime numbers. Is there a way to do that?
That worked, Thank You for your help.
The square brackets here are completely superfluous:
primenum = [num(idx)]
Get rid of them, they do absolutely nothing.
Yes @Stephen..
primenum = num(idx) ;
is enough.

Sign in to comment.

More Answers (0)

Tags

Asked:

on 28 Oct 2020

Commented:

on 28 Oct 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!