The best way to implement this is for a loop in C

I need to list numbers from 1 to x in a format like

2,1,4,3,6,5,8,7 ......

I was thinking about a loop like

for(i =1; i <j+1; i=i+2)
{
    if (i < j)
        printf("%d ", i);

    printf("     %d \n", (i-1));
}

      

This seems primitve.

On my system, in some cases I had to access the numbers in ascending order (0,1,2,3,4, ...), and in some cases I need to get the number in the above order.

I was thinking about a simple change to the style of the for loop based on this case.

Can you suggest a better way to implement this loop.

thank

+3


source to share


7 replies


for(i=2; i<=j; i=i+2)
    printf("%d %d", i, i-1);

      



+6


source


int i, x;
printf("input x : ");
scanf("%d", &x);
for(i=1; i <= x; ++i){
    printf("%d ", i & 1 ? i+1 : i-1);
}
printf("\n");

      



+3


source


A loop can be written in a variety of ways. For example, as follows

#include <stdio.h>

int main(void) 
{
    int x;

    scanf( "%d", &x );

    for ( int i = 1, j = 1; i <= x; i++, j = -j )
    {
        printf( "%d ", i + j );
    }
    puts( "" );

    return 0;
}

      

If you enter 10, then the output will be

2 1 4 3 6 5 8 7 10 9

      

+2


source


Use "\ n" if you wish. And use code something like this. You will get as serious as what you asked for. But be careful with "\ n" ..

 Int a=0;
    for(i=1;i<n;i++){
          a=a+1;
          if(a%2==1){
              printf("%d \n",i+1);
          }else{
               printf("%d \n",i-1);
          }
}

      

+1


source


If you have a block of code inside a loop that needs to run once for each value in your list, it can generate one item in the list per iteration with the following code. This prevents repetition.

int i, j = 10;
for (i = 2; i <= j; i += -1 + 4 * (i%2)) {
    printf("%d, ",i);
}

      

+1


source


Simple sentence

int i, x;
scanf("%d", &x);

// Loop from 1 to the largest even number <= x
for(i = 1; i <= (x & ~1); i++) {
  printf("%d ", i - 1 + 2*(i%2));
}
if (i <= x) {
  printf("%d ", i);
}
printf("\n");

      

+1


source


You can try using an array and initialize for the loop like so:

int array[size];

int n;
for(n = 0; n < size; n++){
  array[n] = n;
}

      

Then you can enter the array like this:

Walk forward two; Print. Go back; printing;

and etc.

some code for this might look like:

int i = 0; //Which can be changed based on starting array number, etc.
while(i < size);
  printf("%d ", array[i]);
  if(i % 2 == 0){
    i--;
  } else {
    i += 3;
  }

      

0


source







All Articles