Search code examples
cfunctionc-stringsinverse

How to pass output from one function to another in C?


my program has two separate functions it excludes non-prime positions and then reserve the output from this. Except the issue I'm having is that at present it is not working how I want it to in the sense that the first function excludes the non prime places and then the second function uses the original input and reserves that instead of the output from function one. I'm new to C so please go easy on me.

#include <stdio.h>
#include <string.h>

void reverse(char[], long, long);
int main()
{
    char str[50];
    int i, j, k, cnt = 0;
    long size;

    printf("Enter: ");
    scanf("%s", str);

    size = strlen(str);
    reverse(str, 0, size - 1);
    printf(str);
    return 0;
}

void reverse(char str[], long index, long size)
{
    char temp;
    temp = str[index];
    str[index] = str[size - index];
    str[size - index] = temp;
    if (index == size / 2)
    {
        return;
    }
    reverse(str, index + 1, size);
}

Sorry for being so vague, a sample output from an input of 1234567 would be 2357 then this output reversed into 7532.


Solution

  • Here is what your code does (as it is written right now):

    1. Input a string from console
    2. Print out every character that is in a "prime position" (2, 3, 5, 7, etc) without modifying the string
    3. Reverse the original, unmodified string
    4. print out the reversed string

    It sounds to me that what you are looking for is the following:
    When you "exclude characters from a string" you create a new string that you populate with the characters from the input string that are in non-prime positions. Than you use that modified string as a parameter into the reverse() function.

    I have no doubt that if you understand the above paragraph you'd have no problem fixing your code.

    Here are the steps to achieve what you need:

    1. input string into str (as you currently do)
    2. introduce a new string str2 of the same size 50 as the original string
    3. in your loop copy every character from str into str2 that is not in a "prime position"
    4. call reverse() providing it the str2 as a parameter, not the (current) str