Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't modulo operator working inside printf function in C?

Tags:

c

function

cs50

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.

like image 401
Yash Gupta Avatar asked Nov 27 '25 03:11

Yash Gupta


1 Answers

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.

like image 63
ネロク・ゴ Avatar answered Nov 28 '25 16:11

ネロク・ゴ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!