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
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 to share
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 to share