Can someone please tell me what this method is doing, and ifyou can please comme
ID: 3618536 • Letter: C
Question
Can someone please tell me what this method is doing, and ifyou can please comment the lines, so I can understand itmore...thank you //precondition:none //postcondition: returns the numeric value for charint charToVal(element ch) { ch = toupper(ch); if (ch >= '0' && ch <= '9'){ return ch - '0'; } else if (ch >= 'A' && ch <='J') { return 10 + (ch - 'A'); // 10to 19 } return -1; }
Can someone please tell me what this method is doing, and ifyou can please comment the lines, so I can understand itmore...thank you //precondition:none //postcondition: returns the numeric value for char
int charToVal(element ch) { ch = toupper(ch); if (ch >= '0' && ch <= '9'){ return ch - '0'; } else if (ch >= 'A' && ch <='J') { return 10 + (ch - 'A'); // 10to 19 } return -1; }
Explanation / Answer
//precondition:none //postcondition: returns the numeric value for charint charToVal(element ch) { ch =toupper(ch); //this changes lower case characters to upper case
//so a becomes A, b become B...z becomes Z
if (ch >= '0' && ch <= '9'){ //if the character is a number this converts it to the digit andreturns it
return ch -'0'; //ascii value of character '1' is 49 so 49-48 is1 etc
} else if (ch >= 'A' && ch <='J') { //if the character is between A andJ it subtracts the ascii value of A, changing
return 10 + (ch - 'A'); // 10to 19 //between 10 and 19
} return-1; //if it's any other character other then 0-9 or A-J it returns acode of -1
}