I'm working in a program for university and they use a problem like the typical Cesar Cipher. It's more like a functional program and needs to be the most basic possible.
The program will receive a number from the user from 65
to 90
and for example when the user inserts 65
will show 68
. Will add 3
numbers but when the user gives 90
will give 67
. 90+3 ---->90,65,66,67
. It's a cycle from 65
to 90
.
#include <stdio.h>
int cesar_encrypted(int x)
{
return (x+3);
}
void test_cesar_encrypted(void)
{
int x;
scanf("%d", &x);
int z = cesar_encrypted(x);
printf("%s\n", z);
}
int main(){
test_cesar_basic();
}
I did this sample code, but we can only go further and if you give 90
he will give 93
and I want 67
.
Can anyone help me to wrap it around 90?
You can use the modulo operator, it gives the remainder of a division:
int cesar_encrypted(int x)
{
return (x - 65 + 3)%(91 - 65) + 65;
}
Implementing the suggestions of Sulthan (see comment), it would look like this:
int cesar_encrypted(int x)
{
const int n_chars = 'Z' - 'A' + 1;
const int shift = 3;
return (x - 'A' + shift)%n_chars + 'A';
}