I recently found a C puzzle to write a program to read a set of integers x0, x1, x2, ……. till a -1 is entered as input..
After reading the -1, the program should print the difference between each adjacent numbers.
Ie, x1-x0, x2-x1, x3-x2,…..
eg:
Input:
1 2 4 7 11 -1
Output
1 2 3 4
The output is the result of (2-1), (4-2), (7-4), (11-7)
The problem is that the program shouldn’t be using an array. Even the dynamically allocated arrays won’t do.
I tried a lot and this is my what I’ve come with
#include<stdio.h>
int a, b;
int fn()
{
int r=b-a;
a=b;
scanf("%d", &b);
if(b!=-1)
{
printf("%d ", fn());
}
return r;
}
int main()
{
scanf("%d%d", &a, &b);
printf("%d ", fn() );
return 0;
}
The above program uses a recursive function but in this method, since it is like a stack, the value that was calculated last is being printed first instead of the value that was calculated first being printed first.
ie, output for the same input as above is:
4 3 2 1
instead of
1 2 3 4
Is there a way to save the values taken from this call stack (please correct me if I’m not using the right terms) and push them again to stack so that while retrieving the first calculated value will now be the first to be popped?
Eg:
I got the values 4, 3, 2 & 1 with fn() because it was like this on stack before 4 was popped:
4 3 2 1
Suppose I pop all elements from the stack and push them to another stack in the order in which they were popped. Then the new stack would be
1 2 3 4
(ie, 4 got popped and pushed first (& hence ended up in bottom), then 3 got popped & pushed and so on.)
If this could be done, we could just pop elements from the new stack and display them in the order in which they are popped.
Note: The stack that I'm referring to is the call stack & not an explicitly created stack (which would probably need array).
Or maybe there’s a simpler way?
EDIT: I need the inputting and outputting phases to be separate and not interleaved. No output should be displayed before the end of input is signaled with the -1.
EDIT: The program can't use files to store the input to be read back later.