Fernando
Fernando

Reputation: 183

A better way to implement this for loop in C

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

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

I thought of 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 to primitve.

In my system, In certain cases I would have to access the numbers in ascending order (0,1,2,3,4,...) and in certain cases I have to acceses the number in the order mentioned above.

I thought of just changing the for loop style based on the case.

Can you suggest a better way to implement this loop.

Thanks

Upvotes: 3

Views: 158

Answers (7)

Gophyr
Gophyr

Reputation: 406

You may want to try using an array and an initializing for loop like so:

int array[size];

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

Then you can step into the array like so:

Go forward two; print. Go back one; print;

etc.

some code for that may look like this:

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;
  }

Upvotes: 0

chux
chux

Reputation: 153338

A simple offering

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");

Upvotes: 1

Trey Keown
Trey Keown

Reputation: 1355

If you have a block of code inside the loop that needs to run once for every value in your list, it's possible to 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);
}

Upvotes: 1

Prabhu Vignesh Rajagopal
Prabhu Vignesh Rajagopal

Reputation: 1068

As your wish use "\n". And use code something like this. You will get serious like what you asked. But 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);
          }
}

Upvotes: 1

BLUEPIXY
BLUEPIXY

Reputation: 40145

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");

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

The loop can be written in various ways. For example the following way

#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 to enter 10 then the output will be

2 1 4 3 6 5 8 7 10 9

Upvotes: 2

utdemir
utdemir

Reputation: 27216

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

Upvotes: 6

Related Questions