To move to the right you must add instead of subtract. Still the problem persists, which is to get to the edge of the alphabet and start picking up other characters from the ASCII table other than letters of the alphabet. You have to detect when this happens to be able to calculate the correct letter by doing a rotation:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define TAM_ALFABETO 26 //tamanho do alfabeto definido aqui
int main(int argc, char** argv) {
char nome[100];
int teste, i;
printf("Informe um nome:\n");
scanf("%s", nome);
printf("Voce quer deslocar a quantas posicoes para a direita:\n");
scanf("%d", &teste);
for(i = 0; i < strlen(nome); i++) {
if (nome[i] >= 'a' && nome[i] <= 'z'){ //se é minuscula
nome[i] = (nome[i] + teste - 'a') % TAM_ALFABETO + 'a';
}
else {//se é maiúscula
nome[i] = (nome[i] + teste - 'A') % TAM_ALFABETO + 'A';
}
}
printf("%s\n", nome);
return 0;
}
Trying to detail the statement that modifies the letter:
nome[i] = (nome[i] + teste - 'a') % TAM_ALFABETO + 'a';
- Pick up the letter and sum the number of positions (the name
teste
for the number of positions was not really the best)
- Subtract
'a'
to get a number between 0
and 26
- Modulate the size of the alphabet to never pass this size
- Returns
'a'
to get a letter between 'a'
and 'z'
Let's look at the same example for the letter 'z'
and increase 3
:
-
'z'(122)
+ 3
gives '}'(125)
- Subtract
'a'(97)
that will give 28
-
28 % 26
gives 2
-
2 + 'a'
gives 'c'
So z
with increase of 3
gives c
See the code working on Ideone
Another alternative is to build a chars array with all valid letters and rotate based on that array. This somewhat simplifies the rotation logic.