3

When I remove "%97" then code works and prints what it expected. Like if input is "a" then it prints "f" whereas it doesn't works when that modulo 97 is present and prints whitespace.

What is reason behind this problem? How to solve it?

    int main(void)
    {
        char *s = get_string();
        for(int i = 0; i<strlen(s); i++)
        printf("this is %c", (s[i]+5%97));
    }

Edit : Guys after adding brackets i.e. changing my last line to "(s[i]+5)%97" program isn't working as expected. Upon entering "a" output should be "f" but it's whitespace.

Upon entering "A" I am getting "F"!! What's happening? This program is meant to convert "a" to "a+5" but it's converting "A" to "A+5". Please explain.

Yash Gupta
  • 35
  • 6
  • What you have is `s[i]+(5%97)`. You want `(s[i]+5)%97`, I assume. – Dietrich Epp May 23 '17 at 12:08
  • I guess you should try using parenthesis around like this `printf("this is %c", ((s[i]+5)%97));` – Darkpingouin May 23 '17 at 12:08
  • Read up about operator precedence – Ed Heal May 23 '17 at 12:08
  • Of course, you'll end up with, e.g., `\0` for `Z`, which is not going to print out anything useful. – Dietrich Epp May 23 '17 at 12:08
  • 1
    Why did you not split up that compound expression into separate simpler statements, with some extra temp vars, outside the printf() and step through with your debugger? I have to ask, since it seem an obvious step? – ThingyWotsit May 23 '17 at 12:53
  • What does the magic number 97 represent? – Andrew Henle May 23 '17 at 12:54
  • Thingy yeah I have done that but compiler was showing "error : expected indentifier" Andrew it represents starting of "a" in ASCII. Actually I used it because of this logic - (97+5)%97 = 5 hence a will become 5th character of alphabet but I forgot that 5 isn't ASCII code for any character. Stupid mistake. :( Anyways modulo was essential because after getting to z we have to start from a again. – Yash Gupta May 23 '17 at 13:53

1 Answers1

7

I think you want to write:

(s[i] + 5) % 97

The expression you wrote:

s[i] + 5 % 97

is the same as:

s[i] + (5 % 97)

That is, the operator % has a higher precedence than +.

You are adding 5 % 97 which is 5 to s[i] in your code.

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • Neroku thanks for response. I have changed code to "(s[i] + 5) % 97" still on input "a" it's printing "this is (whitespace)". Whereas on input "A" it's printing "F" Isn't opposite is happening? Because ASCII for A is 65 whereas ASCII for a is 97. I wanted this program to convert "a" to "a+5" i.e. "f" – Yash Gupta May 23 '17 at 12:21
  • The value of 'A' in ascii code is 65, then (65 + 5) % 97 = 70, which is the value of 'F'. For 'a' (value 97), then (97 + 5) % 97 = 5. The value of 5 does not correspond to 'f'. – JFMR May 23 '17 at 12:27
  • @ChandramauliGupta then just remove the modulo operation – JFMR May 23 '17 at 12:28
  • Oh yeah thanks Neroku I got my answer. What a stupid mistake. – Yash Gupta May 23 '17 at 12:30