-3

I need to print upword and downword number at a same time but with single variable and single loop.

For eg.

If I give input 5 then output should be
5 & 1
4 & 2
3 & 3
2 & 4
1 & 5

But the main condition is single loop and single variable

Thanks.

shruti
  • 780
  • 9
  • 25

5 Answers5

4

You can use structures to have single variable have multiple data.

#include <stdio.h>

int main(void) {
    struct data {
        int n, i;
    } d;
    if (scanf("%d", &d.n) != 1) return 1;
    for (d.i = 1; d.i <= d.n; d.i++) {
        printf("%d & %d\n", d.n - d.i + 1, d.i);
    }
    return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • IMHO, the question has a wording problem. As possible as giving a "one variable, multiple data" solution, one could declare and set a _constant_: `const int n1 = n + 1; while( n > 0 ){ printf("%d & %d\n", n, n1 - n); n--; }` and get the same result... – user3078414 Apr 28 '16 at 15:50
0
int main(n,v) char ** v; {
  n = atoi(v[1]) | (atoi(v[1]) << 16);

  while (n&0xFFFF)
  {
      printf ("%d & %d \n", n&0xFFFF, ((n&0xFFFF0000)>>16)-(n&0xFFFF)+1);
      n = (n&0xFFFF0000) | ((n&0xFFFF)-1);
  }
}

compile with gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) run it like this.
a.exe 7

7&1

6&2

5&3

4&4

3&5

2&6

1&7

cleblanc
  • 3,678
  • 1
  • 13
  • 16
0

You can use a variable and use different position of the number to get your values.

#include <stdio.h>

int main()
{
    int i;

    printf("Enter Start number: ");
    if (scanf("%d", &i) > 0)
    {
        if (i<100)
        {
            i = (i*100)+1;

            while (i/100>0)
            {
                printf("%d & %d\n", i/100, i%100);

                i = (i-100) + 1;
            }
        }
    }

    return 0;
}
LPs
  • 16,045
  • 8
  • 30
  • 61
0
#include <stdio.h>
#include <stdlib.h>

int main(void){
    int *p = calloc(1, sizeof(int[2]));

    puts("input n : ");
    scanf("%d", p);

    while(*p){
        printf("%d & %d\n", (*p)--, ++p[1]);
    }
    free(p);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • Smart solution but on the edge, I thing. Could be an array considered as a single variable by OP? – LPs Apr 28 '16 at 15:58
  • Clearly, `p` is one variable. For example, by using a variable of int64_t you can use a variable two areas of int32_t. At the same should be considered to be the same. – BLUEPIXY Apr 28 '16 at 15:59
  • Yes, crystal. As I already done with [this answer](http://stackoverflow.com/a/33038274/3436922) What I meant is if OP can accept an array as single variable. In that case the answer is very simple also without malloc too. – LPs Apr 28 '16 at 16:52
  • Well, in fact the pointer is not an array. but just use like an array. – BLUEPIXY Apr 28 '16 at 17:00
-1
for(i = 1; i <= 5; ++i)
{
  printf("%d & %d\n", i, 6 - i);
}
vacuumhead
  • 479
  • 1
  • 6
  • 16