-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncoder.c
More file actions
97 lines (90 loc) · 3.01 KB
/
Encoder.c
File metadata and controls
97 lines (90 loc) · 3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//This is the code for Morse code encoder.
//It takes a string as input and returns the Morse code equivalent of the string.
#include <stdio.h>
#include <string.h>
char *morse_code[] = { ".-", // A
"-...", // B
"-.-.", // C
"-..", // D
".", // E
"..-.", // F
"--.", // G
"....", // H
"..", // I
".---", // J
"-.-", // K
".-..", // L
"--", // M
"-.", // N
"---", // O
".--.", // P
"--.-", // Q
".-.", // R
"...", // S
"-", // T
"..-", // U
"...-", // V
".--", // W
"-..-", // X
"-.--", // Y
"--..", // Z
".----",//1
"..---",//2
"...--",//3
"....-",//4
".....",//5
"-....",//6
"--...",//7
"---..",//8
"----.",//9
"-----",//0
};
char words[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int main() {
char str[100];
printf("Press 1 for Encoding and press 2 for Decoding: ");
int choice;
scanf("%d", &choice);
// choice for encoding;
if (choice == 1) {
printf("Enter the string to be encoded: ");
scanf(" %[^\n]", str); // use scanf with space to consume newline character
int i = 0;
while (str[i] != '\0') {
for (int j = 0; j < 26; j++) {
if (str[i] == words[j] || str[i] == words[j] + 32) { // check for both uppercase and lowercase
printf("%s ", morse_code[j]);
break;
}
}
i++;
}
printf("\n");
}
// choice for decoding;
else if (choice == 2) {
printf("Enter the string to be decoded: ");
scanf(" %[^\n]", str); // use scanf with space to consume newline character
char temp[3]; // to store morse code
int i = 0, j = 0;
while (str[i] != '\0') {
while (str[i] != ' ' && str[i] != '\0') {
temp[j++] = str[i++];
}
temp[j] = '\0';
for (int k = 0; k < 26; k++) {
if (strcmp(temp, morse_code[k]) == 0) {
printf("%c", words[k]);
break;
}
}
i++; // to skip the space
j = 0; // reset j
}
printf("\n");
}
else {
printf("Invalid choice\n");
}
return 0;
}