Can you print an array in reverse order without the need of a Loop/Array?

Revision en1, by TryOmar, 2022-08-10 14:32:02

Well, the simple answer is yes. Let me simplify it for you at first.. How can you print from 1 to n without using a loop?

By repeating this line 1000 times, Your program works just as efficiently as if you made an iterative loop from 1 to 1000.

 cout << x++ << endl;
  if(x==n)return 0;

For example, this code can print you numbers from 1 to 10.. You can develop it up to 1000

    int n,x=1;
    cin >> n; n++;
    cout << x++ << endl; // 1
    if(x==n)return 0;
    cout << x++ << endl; // 2
    if(x==n)return 0;
    cout << x++ << endl; // 3
    if(x==n)return 0;
    cout << x++ << endl; // 4
    if(x==n)return 0;
    cout << x++ << endl; // 5
    if(x==n)return 0;
    cout << x++ << endl; // 6
    if(x==n)return 0;
    cout << x++ << endl; // 7
    if(x==n)return 0;
    cout << x++ << endl; // 8
    if(x==n)return 0;
    cout << x++ << endl; // 9
    if(x==n)return 0;
    cout << x++ << endl; // 10
    if(x==n)return 0;

Well here comes the big question.. How do we print an array in reverse without using a loop? Well simply by reading the variables in ascending order and printing them in descending

Here is a small example on 5 variables:

	int x1; cin >> x1;
	if (n == 1) goto line1;
	int x2; cin >> x2;
	if (n == 2) goto line2;
	int x3; cin >> x3;
	if (n == 3) goto line3;
	int x4; cin >> x4;
	if (n == 4) goto line4;
	int x5; cin >> x5;
	if (n == 5) goto line5;

line5: cout << x5 << ' ';
line4: cout << x4 << ' ';
line3: cout << x3 << ' ';
line2: cout << x2 << ' ';
line1: cout << x1 << ' ';

Input: 1 2 3 4 5 Output: 5 4 3 2 1

You can do the same thing up to 1000 elements or more..believe it or not, I solved some problems related to Arrays/Loops in this way.. And It Worked (Accepted✅)

Tags array, loop, reverse, c++

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en5 English TryOmar 2022-08-10 15:22:23 4
en4 English TryOmar 2022-08-10 15:16:29 20
en3 English TryOmar 2022-08-10 14:44:35 69
en2 English TryOmar 2022-08-10 14:40:39 31 Tiny change: 'n~~~~~\n\n\n\nWell h' -> 'n~~~~~\n\nInput : 6\nOutput : 1 2 3 4 5 6\n\nWell h'
en1 English TryOmar 2022-08-10 14:32:02 1902 Initial revision (published)