Hi ,
I doing my assignment and got struck with my programming. The following source code take in data(1,2,3,4,5) and then display it. My program display the following result which
is not my expected result.
----------------------------------
First data = 1
Second data = 2
Third data = 3
Fourth data = 4
Fifth data = 5
----------------------------------
Then i use the if function to store the data to the desire position. it works but will not work if i change the position of the source code from main{}. That means it is not flexible.
For example ,shift "push(3)" from it's current position to after the "printf("First data = %d\n", d);" , i will not be able to get the desirable result again
i want the output to be like this :
First data = 3
Second data = 2
Third data = 4
Fourth data = 5
Fifth data = 1
Can anyone give me some clue how to solve this. ( Note : source code from the main{}
cannot be altered.)
Code:#include <stdio.h> int buffer[1024]; int inp = 0; int outp = 0; push(int v) { if (inp < 1024) { if(v==1) { buffer[4] = v; inp++; } else if(v==2) { buffer[1] = v; inp++; } else if(v==3) { buffer[0] = v; inp++; } else if(v==4) { buffer[2] = v; inp++; } else if(v==5) { buffer[3] = v; inp++; } } } int pop() { int data = 0; if(outp < inp) { data = buffer[outp]; outp+=1; } return data; } main() { int d; push(1); push(2); d = pop(); push(3); printf("First data = %d\n", d); d = pop(); printf("Second data = %d\n", d); push(4); d = pop(); printf("Third data = %d\n", d); push(5); d = pop(); printf("Fourth data = %d\n", d); d = pop(); printf("Fifth data = %d\n", d); }