Yamaha32088 - 1 year ago 64

C Question

This might seem like a very simple solution to some people but I have been trying to figure it out for a while now and its bugging me.

`int sum = (p[i] - 'A') + (s2[i % keyLen] - 'A');`

char c = 'A' + sum%26;

I am having trouble coming up with the solution math has never been a strong point of mine. the value of

`char c`

`p[i]=72 or 'H'`

`s2[i]=5`

This operation works wonderfully but I am trying to understand what is going on so I have tried to do it with a normal calculator and keep coming up with the wrong answer. If someone could walk me through exactly the order of operations and what the values would be I would appreciate it. Here is the complete source code that I have so far that works:

`#include <stdio.h>`

#include <cs50.h>

#include <string.h>

#include <ctype.h>

#include <stdlib.h>

int main(int argc, char *argv[])

{

char s2[25];

strcpy(s2, argv[1]);

int keyLen = strlen(s2);

printf("Please enter a string of text to be encrypted!\n");

string p = GetString();

for (int i = 0, n = strlen(p); i < n; i++)

{

if (isupper(p[i])){

int sum = (p[i] - 'A') + (s2[i % keyLen] - 'A');

char c = 'A' + sum%26;

printf("%c", c);

}

}

printf("\n");

printf("%d\n", keyLen);

}

The way I am doing this operation is:

`int sum = (p[i] - 'A') + (s2[i % keyLen] - 'A');`

//int sum = (72-65) + (72 % 5) - 65) sum= -56

char c = 'A' + sum%26;

//char c = 65 + -56 %26 char c = -8

I obviously know my math is off but I thought I was doing it right when I run the operation through the debugger

`sum = 14`

`char c = 79 or 'O'`

Answer Source

```
int sum = (p[i] - 'A') + (s2[i % keyLen] - 'A');
//int sum = (72-65) + (72 % 5) - 65) sum= -56
```

Your misunderstanding is here.

**What the code is doing**

```
(s2[i % keyLen] - 'A')
```

means

```
(char_from_s2 - 'A')
```

where `char_from_s2`

is the character in `s2`

at index `i % keyLen`

, i.e. the character at position `i`

wrapped around to fit in the length of the string.

**What your calculation shows**

Your calculation is doing something different:

```
(char_from_p % keyLen) - 'A'
```

You're taking the character from `p`

instead of from `s2`

, and applying the `%`

operator to the character value instead of the index.