Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, make sure your code has appropriate whitespace. This will help you realize when things aren't lined up like you think they are.</p> <pre><code>#include &lt;stdio.h&gt; int main() { int num, i; printf("Number [1-100]:? \n"); scanf("%d", &amp;num); while(num&gt;0 &amp;&amp; num &lt;101){ if (num==1||num==2) printf("Prime\n"); for(i=2; i&lt;=num/2; ++i) { if (num%i==0) { printf("Non-prime,divisible by %d\n",i); break; } else { printf("Prime\n"); break; } } printf("Number[1-100]:? \n"); scanf("%d",&amp;num); } printf("Done\n"); } </code></pre> <p>Now you should realize that your else statement happens on the first check! So when 3 is not divisible by 2, it prints "prime."</p> <p>And then it breaks out of the loop.</p> <p>And this happens for EVERY number. All your program is doing is checking to see if numbers are divisible by 2.</p> <p>If you wrote "Odd" instead of "Prime" it would at least be correct there.</p> <p>This is the kind of problem where setting a flag might be useful (there are other ways to do this, but this is one way). So you could set a flag, say <code>int isPrime = 1;</code></p> <p>Now, if you find out that the number is not prime, you simply set <code>isPrime = 0;</code>.</p> <p>Finally, at the end of the for loop (let me repeat: AFTER the for loop finishes), you need to check that variable. And you can say,</p> <pre><code>if (isPrime == 1) { printf("Prime\n"); } else { printf("Non-prime."); } </code></pre> <p>I'll let you figure out how to print the divisor :)</p> <p>(For reference, correctly using the flag would look like this -- and for clarity I removed the 'feature' in which it continuously looped)</p> <pre><code>#include &lt;stdio.h&gt; int main() { int num, i; int isPrime = 1; printf("Number [1-100]:? \n"); scanf("%d", &amp;num); for(i=2; i&lt;=num/2; ++i) { if (num%i==0) { isPrime = 0; break; } } if (isPrime == 1) { printf("Prime\n"); } else { printf("Non-prime."); } printf("Done\n"); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload