Rishab
Rishab

Reputation: 1957

Recursive function that takes an array and displays the elements in reverse order

I just want to print the array in reverse order using a recursive function. Below is my code. This code prints all the characters in reverse but the very first element is always missing since the last return is always array(1)(1 being the index of array..... I don't actually know the memory address) and not array(0).

Code:

#include<iostream>
using namespace std;

void array(char *s){
    if(*s=='\0') return;
    array(++s);
    printf("%c",*s);
}
int main(){
    char s[20];
    gets(s);
    cout<<"\n";
    array(s);
    return 0;
}

Upvotes: 1

Views: 216

Answers (5)

Aiman Al-Eryani
Aiman Al-Eryani

Reputation: 709

Just use array(s+1); instead of array(++s); to preserve the first value.

N.B: It should be noted that you better use sizeof() when doing pointer arithmetic like that.

Upvotes: 0

True Tech
True Tech

Reputation: 3

your code was fine, but why aren't you getting answer is, '\0' this works fine when the user types enter button ,to give another input but , while user was giving input he doesn't type enter at beginning, so your code doesn't work for that one letter. now to manage this program you can do like this, store that first character in another variable and display it at last.

Upvotes: 0

ameyCU
ameyCU

Reputation: 16607

You can write like this -

void array(char *s,int i)
{
    if(s[i]=='\0') return;
    array(s,i+1);          // i declared in main as int i=0 and call as array(s,i) in main
    printf("%c",s[i]);
 }

Upvotes: 1

Tamir Vered
Tamir Vered

Reputation: 10287

Change the method:

void array(char *s){
    if(*s=='\0') return;
    array(++s);
    printf("%c",*s);
}

To:

void array(char *s){
    if(*s=='\0') return;
    array(s + sizeof(char));
    printf("%c",*s);
}

Because ++s or s++ changes the pointer variable which affects the printf and makes you always print the next character.

Upvotes: 2

Kenney
Kenney

Reputation: 9093

Change

 array(++s)

to

 array(s+1)

so you keep the proper value of s for the printf statement.

#include <iostream>
#include <stdio.h>
using namespace std;

void array(char *s){
    if(*s=='\0') return;
    array(s+1);
    printf("%c",*s);
}
int main(){
    char s[20];
    gets(s);
    cout<<"\n";
    array(s);
    return 0;
}

Upvotes: 1

Related Questions