3 /3 Q4) On a computer, each letter and symbol has an integer value, the numeric
ID: 3728346 • Letter: 3
Question
3 /3 Q4) On a computer, each letter and symbol has an integer value, the numerical mapping of a letter is typically done via an ascii (on a computer). An ascii table can easily be found in the textbook and on the internet. The ascii values for 'a'-'z' are 97-122. The ascii number can be calculatred by casting a char datatype to an int datatype, i.e. int i (int) c, where c is pre-defined as a char datatype. Write a program that converts the characters in a string to numbers. Humans would typically encode letters as numbers via number code (a 1, b 2, , z = 26), but this is too simple and insecure to use as an encoding scheme. Change the number code to be hashed by the function H 2 N 13, where N is the number code as explained earlier and H is the hashed equivalent of that number. Now, a -11, b =-9, c =-7, ,2 39, Print the string in the new code. Assume the entire string is lowercase. An example may be seen below. Enter the length of the string: 13 Enter the string: hello world Outputed hash-code: Hints: Modify the code from the previous problem to read a char array the procedures mentioned in Q3 and change the filename to char hash.c. The '(space) character is represented by 32 in ascii, -64 in number code, and -141 in our hashed code. The newline character is 10 in ascii, and -185 in our hashed code. Note: Even though "hello world" only has 11 letters (including the space), there is an addi- tional line feed character before and after the letters. Thus, the total size of the string is the number of letters + 2. There are no spaces after the :' symbol in the printed lines above. Name your file char hash.c. (string), review Submission Guidelines:Explanation / Answer
#include <stdio.h>
#include <string.h>
#define MAX_LIMIT 100
int getHashCode(int n){
int h = 2*n - 13;
return h;
}
void displayHashCode(char* str, int n){
int i, h;
printf("%d ", -185); // since ' ' is not automatically included in the string
for(i = 0; i < strlen(str); i++){
h = getHashCode(str[i] - 'a' + 1);
printf("%d ", h);
}
}
int main(){
int n;
char str[MAX_LIMIT];
printf("Enter the length of the string: ");
scanf("%d", &n);
getchar();
printf("Enter the string: ");
// scanf("%[^ ]%*c", str);
fgets(str, MAX_LIMIT, stdin);
printf("Outputed hash-code: ");
displayHashCode(str, n);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.