I need to write a program that reads from the input a sentence terminated by a new line. The program should write an encryption of the sentence in a way that the letter 'a' is swapped with 'z', 'b' with 'y' and so on. I am not supposed to use arrays, that is why I can't find a solution for this problem.
This is my code:
#include<stdio.h>
int main() {
char alphabet, temp;
while( scanf("%c", &alphabet) != '\n') {
for(char i ='a', j='z'; i <= 'z', j>='a'; i++, j--) {
if(alphabet == i) {
temp = j;
}
}
printf("%c", temp);
}
return 0;
}
When I input: abc as an output I get zyxxxxxxxxxxxxxxxxxxxxxxxxx(an infinite number of x).
So to sum up: Input:abc. Output: zyxxxxx(infinite number of x).
Compile your code with warnings enabled (e.g.
Wall
flag)! This:should give:
You need to use the logical AND operator
&&
and not a comma between the two comparissons.Moreover, use
getchar()
instead, like this:Output:
If you have to use
scanf()
, then try reading intoalphabet
, check the return value of scanf, and compare to newline, like this: