X Lefora
X Lefora

Reputation: 11

C Program which checks multiple numbers from user input and prints out if they are prime or not

I am a newbie programmer and just started to teach myself C then decided to tackle some simple problems taken from the internet. Specifically with this one: Problem

And my solution is:

#include <stdio.h>
int main(){
  int n, i, test = 0;
  char s[] = "";
  do{
    scanf("%d", &n);
    if (n <= 1){
      break;
    }

    for(i = 2; i <= n/2; i++){
        if(n%i == 0){
        test = 1;
        break;
        }
    }

    if(test == 0){
        **s[] += "%d IS PRIME\n", n;**
    }
    else{
        **s[] += "%d IS NOT PRIME\n", n;**
    }

    }while(i > 1);
  printf("%s", s);
  return 0;
}

However, the current problem I have is modifying my program so that it would print out like the expected results (see output from Problem). And for this, I would need to concatenate the results each time into a string variable where it would be printed last, after the user inputs 1 or a number lesser than 1 which would terminate the program. I have decent experience with Java and I have highlighted that part in this program. Basically, what would be the most logical way to write that part as a C command?

Upvotes: 0

Views: 707

Answers (1)

lostbard
lostbard

Reputation: 5220

Move the print statement into the while loop so it is done each iteration of the loop.

test needs to be reset back to 0 in each loop iteration before doing the test for prime.

In addition the **s[] is not doing what you think it is. Remove it, and change it so that it prints the results at that point:

if(test == 0){
  printf("%d is PRIME\n", n);
}
else {
  printf("%d is NOT PRIME\n", n);
}

Upvotes: 2

Related Questions