Home > Software design >  How to put commas on a series of numbers in a proper way
How to put commas on a series of numbers in a proper way

Time:11-19

Yes I have searched through the net and also here but failed to find similar cases. I have here a program which prints prime numbers between 2 given integers. But I have to print them with commas in a proper way. like 1, 2, 3, 4 without having a comma on the last integer. Here is my code.

#include<stdio.h>

void main()
{
    int x, y, i, j;
    puts("Enter first number: ");
    scanf("%d", &x);
    puts("Enter second number: ");
    scanf("%d", &y);
    for(i=x; i<=y; i  )
    {
        for(j=2; j<=i; j  )
        {if(i%j==0)
        {
            break;
        }
        }
        if(i==j)
        {
                printf("%d, ", i);
        }
    }
}

I wanted to identify the total number of prime numbers printed in order to set a condition that if it is the last one, a comma will not print but I don't know if it will work. That is the only thing I can think of for now and your help guys will be really appreciated. Thank you!

CodePudding user response:

You can use a flag, as others have suggested, but you can also use a string as a separator, setting it to empty for the first element and any desired separator after that.

#include <stdio.h>

void print_join(const char *sep, int n, int a[n])
{
    const char *s = "";
    for (int i = 0; i < n; i  )
    {
        printf("%s%d", s, i);
        s = sep;
    }
    printf("\n");
}

int main(void)
{

    int a[] = {1, 2, 3, 4, 5};
    int n = sizeof a / sizeof *a;

    print_join(", ", n, a);
    print_join(";", n, a);
    print_join("", n, a);
    print_join("--", n, a);

    return 0;
}

CodePudding user response:

As @kaylum pointed out, use a flag to "skip" printing the comma when printing the first number. Set that flag to false after the very first number you print.

#include <stdio.h>

void main() {
    int x, y, i, j;

    puts("Enter first number: ");
    scanf("%d", &x);

    puts("Enter second number: ");
    scanf("%d", &y);

    int is_first_time = 1;

    for (i = x; i <= y; i  ) {
        for (j = 2; j <= i; j  ) {
            if (i % j == 0) {
                break;
            }
        }

        if (i == j) {
            if (is_first_time) {
                printf("%d", i);
                is_first_time = 0;
            } 
            else {
                printf(", %d", i);
            }
        }
    }
}
  •  Tags:  
  • c
  • Related