Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How is the char variable able to store a string without using square brackets or curly braces and how does it iterate to the next character?

I am currently learning how recursion work by reversing a sentence and I can’t seem to understand how the char variable is able to store a string without using square brackets or curly braces and how it iterates to the next character

I am new to this and I hope my question isn’t too simple to ask

#include <stdio.h>

void swap_recursion();

int main() {

    printf("Input a sentence: ");
    swap_recursion();

    return 0;
}

void swap_recursion(){
    char sentence;

    scanf("%c", &sentence);
    if (sentence != '\n'){
        swap_recursion();
        printf("%c", sentence);

    }

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The string is stored in multiple instances of char sentence; on the stack. Each recursive call of swap_recursion() makes a new char sentence; on the stack, and stores one character from the input there. The stack keeps building up until a new line is encountered. At that point, the entire string is stored on the stack. Then each character is printed in the reverse order they were read, by unrolling the stack with each return.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading