The function\'s shift task is to shift a letter of the alphabet by x amount. Fun
ID: 3630950 • Letter: T
Question
The function's shift task is to shift a letter of the alphabet by x amount.Function’s prototype is
char shift(int shift_amount, char original);
However, function has a logic error.
**Find the logic error, repair it, so that the code has no logic errors.**
This is what I have so far:
#include <include>
#include <string>
using namespace std;
const string empty_string = "";
char shift(int shift_amount, char original);
string shift(int shift_amount, const string& original);
int main()
{
string original = "Of all things, never to have been born is best!";
for(int shift_amount = 0; shift_amount <= 26; shift_amount++)
{
string shifted = shift(shift_amount, original);
cout << shifted << endl;
}
system("pause");
return 0;
}
char shift(int shift_amount, char original)
{
char shifted;
static const int ALPHA_SIZE = 26;
static const int upper_base_code = static_cast('A');
static const int lower_base_code = static_cast('a');
shift_amount = shift_amount % ALPHA_SIZE;
if(shift_amount < 0)
shift_amount += ALPHA_SIZE;
int base_code;
if(isupper(original))
base_code = upper_base_code;
else
base_code = lower_base_code;
int original_code = static_cast(original);
int original_offset = original_code - base_code;
int shifted_offset = (original_offset + shift_amount) % ALPHA_SIZE;
int shifted_code = shifted_offset + base_code;
shifted = static_cast(shifted_code);
return shifted;
}
string shift(int shift_amount, const string& original)
{
string shifted = empty_string;
int length = original.length();
for(int index = 0; index < length; index++)
shifted += shift(shift_amount, original[index]);
return shifted;
}
Explanation / Answer
1) shift_amount = shift_amount % ALPHA_SIZE; 2) if(shift_amount < 0) 3) shift_amount += ALPHA_SIZE; In line (1) you are finding remainder when shift_amount is divided by ALPHA_SIZE so the value of shift_amount never became less than 0. In line (2) the condition never meet due to above. So your line (3) never be executed.Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.