Reputation: 1168
I have written this code to print out all prime numbers between 1 and the input value:
#include <stdio.h>
#include <conio.h>
int main()
{
//Declaration of variables:
int N, i, j, isPrime, n;
// Ask user for input the upper limit for the generation of primes (N)
printf("Enter the value of N\n");
scanf("%d",&N);
if (N==1){
printf("There are no prime numbers before 1. Please recompile. \n" ); //print out an error if
// 1 is inputted as the upper limit for the generation of primes.
}
/* For every number between 2 to N, check whether it is prime number or not */
else
printf("The primes between 1 and %d are: ", N);
for(i = 2; i <= N; i++){
isPrime = 0;
/* Check whether i is prime or not */
for(j = 2; j <= i/2; j++){
/* Check If any number between 2 to i/2 divides I completely If it divides, the numebr cannot be a prime. */
if(i % j == 0){
isPrime = 1;
break;
}
}
// print out the primes if the conditions are met
if(isPrime == 0 && N != 1)
printf("%d, ", i);
}
return 0;
}
It works great, but I get a comma after each value, including the last one. I would like to remove the comma from being displayed just from the last one.
Thank you very much in advance.
Best.
Upvotes: 1
Views: 1205
Reputation: 17605
As it is somewhat difficult to determine which iteration of the loop is the last one, one could put the comma before the output instead of after the output and omit the first comma as follows, where the comments are deleted for brevity.
int isFistIteraion = 0;
for(i = 2; i <= N; i++)
{
isPrime = 0;
for(j = 2; j <= i/2; j++){
if(i % j == 0){
isPrime = 1;
break;
}
}
if(IsPrime == 0 && N != 1){
if (0 == isFirstIteration){
isFirstIteraion = 1;
printf("%d", i);
} else {
printf(", %d", i);
}
}
}
Upvotes: 3