Originally Posted by
GvsuStudent
I obviously understand indentation is something i need to work on, but i don't fully understand how this correlates to the portion of the code i'm having issues with. in general the code works as it should.
What you're looking at is a logic error, which typically has something to do with the flow of control through the code, which is something that is visually represented by indentation. By not having proper indentation, you obscure this flow of control, making it difficult to reason about your code.
Here's your code with proper indentation, plus a function prototype:
Code:
#include <stdio.h>
int prime(int num);
int main(void)
{
int num, secondTest;
int i, x;
printf("PRIME NUMBER CHECKER\n");
printf("Enter Value: ");
scanf("%d", &num);
x = prime(num);
if (x == 0) {
for (i = 1; i < num; i++) {
if (num % i == 0) {
printf("\n%d = %d X %d", num, i, num / i);
}
}
printf("\n%d:NOT A PRIME Number", num);
}
else if (x == 1) {
printf("\n\n%d = %d X %d", num, 1, num);
printf("\n%d: PRIME Number", num);
}
do {
printf("\nWould you like to enter another value? (1=Yes , 0=No) > ");
scanf("%d", &secondTest);
switch (secondTest) {
case 1:
printf("\nEnter Value: ");
scanf("%d", &num);
x = prime(num);
if (x == 0) {
for (i = 1; i < num; i++) {
if (num % i == 0) {
printf("\n%d = %d X %d", num, i, num / i);
}
}
printf("\n%d:NOT A PRIME Number", num);
}
else if (x == 1) {
printf("%d = %d X %d", num, 1, num);
printf("%d: PRIME Number", num);
}
break;
}
}
while (secondTest != 0);
return 0;
}
int prime(int num) {
int i, flag = 0;
for (i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
return 1;
else
return 0;
}
Note also that I explicitly stated the num parameter of prime to be an int, and removed unnecessary blank lines. Generally, you should use a blank line to group portions of code, and some people have a convention of two blank lines to separate top level constructs.
Rather than the garbled mess you had here, hidden due to poor indentation among other code:
Code:
x=prime(num);
if(x==0){
for(i=1; i<num; i++){
if(num%i==0){
printf("\n%d = %d X %d",num,i,num/i);
}
}
printf("\n%d:NOT A PRIME Number",num);
}
It is now easy to see that the relevant part that is being output is controlled by a for loop that runs until i reaches num. Consequently, you repeat the other half of the factors, since you loop past the square root of x, so you start finding the factors of x that you already found by computing num / i. That you don't need to loop past the square root of x suggests a simple fix:
Code:
for (i = 1; i * i <= num; i++) {
if (num % i == 0) {
printf("\n%d = %d X %d", num, i, num / i);
}
}
printf("\n%d:NOT A PRIME Number", num);
You have to apply this fix later as well, which suggests that you should restructure your code rather than repeat yourself. (DRY principle: Don't Repeat Yourself)