Write recursive function that gets an array of chars and a '.' at the end, and print if in reverse . Write in C

0 votes
asked Mar 30 by Kobi

Hi,

 I hope it was clear - here an example:

for " abcd."

the function will print - ".dcba"

I need that the function will get a pointer like that - " void printCharsOpposit(char* str) "

I can do it without the pointer:

#include <stdio.h>

void reverseSentence();

int main()

{

    printf("Enter a sentence: ");

    reverseSentence();

    return 0;

}

void reverseSentence()

{

    char c;

    scanf("%c", &c);

    if( c != '.')

    {

        reverseSentence();

        printf("%c",c);

    }

}

Thank you!

2 Answers

0 votes
answered Apr 2 by (540 points)

First to mention, char arrays are stored in memory with additional (termination) character '\0' added at the end of array, so we can first call recursions until that char is found, and then printing each chars while going back from recursions, so here is my solution.
 

// Parameter 'str' is an address to current character in array
// When calling this function from main, str is an address to first character in array

void printCharsOpposit(char* str) {

  if (*str != '\0') {

    printCharsOpposit(str + 1);

    printf("%c", *str);

  }

}
And test for function:
int main() {

  char str[] = "abcd.";

  printCharsOpposit(str);

}

0 votes
answered Aug 10 by (300 points)
#include <stdio.h>
     
    int main()
    {
       int n,c,d,a[100],b[100];
     
       printf("Enter the number of elements in array\n");
       scanf("%d",&n);
     
       printf("Enter array elements\n");
     
       for(c=0;c<n;c++)
          scanf("%d",&a[c]);
       for(c=n-1,d=0;c>=0;c--,d++)
          b[d] = a[c];
       for(c=0;c<n;c++)
          a[c]=b[c];
     
       printf("Reverse array is\n");
     
       for(c=0;c<n;c++)
          printf("%d\n",a[c]);
       return 0;
    }
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...