Emre Unsal
Emre Unsal

Reputation: 159

adding repetition to calling a function

Ok I'm trying to make a code that replaces characters in the string entered with the next ones in the alphabet and and print it 26 times (all letters rotated)
I took help from a rot13 code modified it a little it does EVERYTHING I want except printing it 26 times. I tried to add a counter with both for and while but I really looked stupid and didn't work of course.

here's the code

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("Please Enter The Secret Code\n");
    int code;
    while((code = getchar())) {
        code = chariot(code);
        putchar(code);
    } 
    return 0;
}

int chariot(int code)
{
    if('a' <= code && code <= 'z'){
        return Chariot(code,'a');
    } else if ('A' <= code && code <= 'Z') {
       return Chariot(code, 'A');
    } else {
        return code;
    }
}

int Chariot(int code, int newcode){
    code = (((code-newcode)+1)%26)+newcode;
    return code;
}

Upvotes: 0

Views: 105

Answers (2)

Armali
Armali

Reputation: 19395

If you insist on processing the input character by character, you can use this on a sufficiently high VT100 compatible terminal:

    while (code = getchar())
    {
        int i;
        for (i = 0; i < 26; ++i)
            if (putchar(code = chariot(code)) != '\n') printf("\b\v");
        if (code != '\n') printf(" \e[26A");
    }

But of course, this is ridiculous. The sane solution is what o_weisman suggested:

read the entire string first, and only then run Chariot function on all its characters in a loop 26 times printing the result after each call.

Upvotes: 0

Previn
Previn

Reputation: 34

What you need to do is run this last bit:

int Chariot(int code, int new code)
{
    code = (((code-newcode)+1)%26)+newcode;
    return code;
}

Through a 'for' loop.

The way it should look would be like this:

int Chariot(int code, int new code)
{

    for (int i = 0; i < 26; i++)
    {
        code = (((code-newcode)+1)%26)+newcode;
    }
    return code;
}

What this is doing is running that same bit of code 26 times, which is what your desired result will be. Do some more research on loops as they'll help you out tremendously in your life.

Upvotes: 1

Related Questions