Home > Back-end >  printf values inside single bracket
printf values inside single bracket

Time:10-12

I was just practicing with beginner code printing odds and evens and I could never figure out how to print them inside a simple for loop such that the values stay inside 1 single bracket { } like this:

The·even·number·in·range·are·{2,·4,·6,·8,·10}.

And not like this:

The even number in range are {2} The even number in range are {4}

Edit: oops forgot to place code fragment.

for(i=1; i<=n; i  ){
    r=i%2;
    if(r==0){
      printf("The even number in range are {%d} ",i);
    }

CodePudding user response:

#include <stdio.h>

int main(void) {
    int n=21;
    printf("The even number in range are {");
    for(int i=1; i<=n; i  ){
        (i%2)? 0:printf("%d ", i);
    }
    printf("}\n");
    return 0;
}

Output

Success #stdin #stdout 0s 5436KB
The even number in range are {2 4 6 8 10 12 14 16 18 20 }
  •  Tags:  
  • c
  • Related