What to do to remove a comma after the last term?

#include <stdio.h>

int main()
{
  int n1, n2, temp, n, d, p;
  printf("Enter two numbers(The limits of your prime numbers): ");
  scanf("%d %d", &n1, &n2);
  if (n1>n2)
  {
      temp=n1;
      n1=n2;
      n2=temp;
  }
  printf("The prime numbers between %d and %d are: ", n1, n2);
  for(n=n1;(n<=n2)||(n<2000);++n)
  {
      p=1;
      for(d=2; d<=n/2; ++d)
      {
        if(n%d==0)
        {
          p=0;
          break;
        }
      }
      if(p==1)
      {
        if (n==1)
        {continue;}
        printf("%d",n);
        //I don't know what to put here so that the last term won't have a comma
        printf(", ");

      }
  }
  return 0;
}

I am trying to print prime numbers between two intervals (inclusive), but the last members always have a comma. I need a way to prevent the comma from printing after the deadline. Commas are followed by a space before the next term.

For example (current situation):

Input:1 10 Output:2, 3, 5, 7,

What it should be:2, 3, 5, 7

I forgot to mention that when "n" exceeds 2000, it should stop printing.

+4
source share
5 answers

, . , , , . ", " , .

edit: , : if (firstRun) { firstRun = 0; } else { fputs(", ", stdout); }

+2

, , . .

+2

 (n<=n2)?printf(","):(n<2000?printf(","):printf("\n"))
0

- :

char *separator = "";

for (...) {
    ...
    printf("%s%d", separator, n);
    separator = ",";
}
0

printf ( "\ b\b" );//2 \b\b

0; :

 if(p==1)
  {
    if (n==1)
    {continue;}
    printf("%d",n);
    //I don't know what to put here so that the last term won't have a comma
    printf(", ");

  }
   }
 printf("\b\b  "); //here insert code 
 return 0;

-1

Source: https://habr.com/ru/post/1608547/


All Articles