- 1

Hi there👋can anybody help me to explain this code(especially this lines (10-22)thanks(:

1)#include<stdio.h> 2)int main() 3){ 4)char message[100], ch; 5)int i, key; 6)printf("Enter a message to encrypt: "); 7)gets(message); 8)printf("Enter key: "); 9)scanf("%d", &key); 10)for(i = 0; message[i] != '\0'; ++i){ 11)ch = message[i]; 12)if(ch >= 'a' && ch <= 'z'){ 13)ch = ch + key; 14)if(ch > 'z'){ 15)ch = ch - 'z' + 'a' - 1; 16)} 17)message[i] = ch; 18)} 19)else if(ch >= 'A' && ch <= 'Z'){ 20)ch = ch + key; 21)if(ch > 'Z'){ 22)ch = ch - 'Z' + 'A' - 1; 23)} 24)message[i] = ch; 25)} 26)} 27)printf("Encrypted message: %s", message); 28)return 0; 29)}

28th Sep 2021, 1:51 PM
Seyran Vardanyan
Seyran Vardanyan - avatar
4 Respostas
+ 3
gets(message); //dont use gets , use fgets or scanf.. it accepts a string of input, and a intiger key value that is used for encryption like for example if input is "abcdz" and key is 1, then encryption happens like: ch='a' and ch+key => 'a'+1= 'b' and next charecter from string is 'c' ch='b' and ch+key => 'b'+1= 'c' ch='c' and ch+key => 'c'+1= 'd' ch='d' and ch+key => 'd'+1= 'e' ch='z' and ch+key => 'z'+1 is a special symbol by code : for(i = 0; message[i] != '\0'; ++i){ ch = message[i]; if(ch >= 'a' && ch <= 'z'){ ch = ch + key; but now ch >'z' so if(ch > 'z'){ ch = ch - 'z' + 'a' - 1; => 'z'+1 - 'z'+'a'-1 => 'a' (like turning around from 'a' again) so now ch='a'; //this code works same but for capital letters else if(ch >= 'A' && ch <= 'Z'){ ch = ch + key; if(ch > 'Z'){ ch = ch - 'Z' + 'A' - 1; } message[i] = ch; } } now at end encrypted message for input "abcdz" is "bcdea" it just making a charecter farward of key position from alphabet read about ASCII values of char hope it helps.
28th Sep 2021, 2:16 PM
Jayakrishna 🇮🇳
+ 2
Prefer using code Playground to post codes.
28th Sep 2021, 2:05 PM
Arsenic
Arsenic - avatar