-1

I want to make a code to Print the inputs in reverse order.

If I put integer input

6

20

14

5

I want to read the data not using array just method

like 5 14 20 6, not 5 41 02 6.

what should I do next? Please help me.

#include <stdio.h>

int main(void)
{
    int reverResult;
    int num;
    int i;
    int recurnum=0;
    printf("Test PrintReverse\n");
    printf("Number Please\n");

    scanf("%d",&recurnum);
    printf("%d is the number of recursion\n", recurnum);

    for(i=1 ; i<=recurnum ; i++)
    {
        scanf("%d\n",&num);
        printf("%d\n", num);

    }
}
Community
  • 1
  • 1
Dongzibi
  • 3
  • 2

2 Answers2

2

Here you have to store the input data in some form of another to print it in reverse order. If not array, some other form of data structure is needed.

[Assuming the easiest approach needed] What you want here is to use an array of ints to hold the input value.

The algorithm goes like this

  1. Read and store inputs in an array.
  2. Keep on incrementing the index with each valid (successful) input.
  3. Once done, start printing from the highest index to lower.

and you'll have your reverse print. :-)

Notes:

  1. Please remember, array index starts from 0.
  2. Always initialize your local variables.
  3. Try to use explicit return statement. Good practice.

[ P.S. - No, I won't write the code here. Please try it yourself first and if you face any issue, come back. We'll be here to help. :-) ]

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

You can do this without any arrays, using recursion. The recursive stack will be the storage, and will give you the reversal that comes with popping from a stack. I'll sketch it in pseudo-code:

def recursive_read()
    x = read_value()           // attempt to read a value into x
    if x != EOF_INDICATOR      // read attempt was NOT end-of-file
        recursive_read()       // recursively attempt the next read
        print x                // print the current x when control returns here
    endif
    return      // got EOF, or finished reading/printing. Either way, we're done here!
enddef
pjs
  • 18,696
  • 4
  • 27
  • 56