I kind of just did your assignment for you :cheesy: I was interested in trying it out. Basically this uses the ASCII values for the characters to shift them and that helps make it nice and neat.
#include "stdafx.h"
#include <iostream>
using namespace std;
void ShiftLetters(char *buffer, int places);
int main(int argc, char* argv[])
{
int PlacesToMove = 0;
int temp = 0;
char OurLetters[5] = {'A','B','C','D','E'};
cout << "Letters before shift: ";
//Need to do the following because OurLetters is not null-terminated
for (temp = 0; temp < 5; temp++)
{
cout << OurLetters[temp];
}
cout << "\n\n" << "How many places right should the letters be shifted? ";
cin >> PlacesToMove;
if (PlacesToMove != 0)
{
ShiftLetters(OurLetters, PlacesToMove);
cout << "Letters after shift: ";
for (temp = 0; temp < 5; temp++)
{
cout << OurLetters[temp];
}
cout << "\n";
}
return 0;
}
void ShiftLetters(char *buffer, int places)
{
places = places % 5;
for (int i = 0; i < 5; i++)
{
buffer[i] = buffer[i] - places;
if (buffer[i] < 65)
{
buffer[i] = buffer[i] + 5;
}
}
}
The biggest thing you're probably interested in is this:
void ShiftLetters(char *buffer, int places)
{
places = places % 5;
for (int i = 0; i < 5; i++)
{
buffer[i] = buffer[i] - places;
if (buffer[i] < 65)
{
buffer[i] = buffer[i] + 5;
}
}
}
So I'll go over that. At the beginning it just places modulus 5 because there are really only 5 different shifts you can execute: right 1, 2, 3, 4, or 5 (or 6 if you count 0), so its easier to modulus the places by 5 to make the shift one of those values.
Then it goes through each letter and subtracts the places from it to receive the new ASCII value. If its less than 65 (less than 'A'), it adds 5 to put it back into the correct value.
Thats basically it.
==========================================================
To critique your code, and tell you some things you can improve on:
cout<<"Before shifting:"<<chrs[5]<<endl;
That won't work because:chrs has only 5 elements. Remember, in C++ (and most other programming languages) the indexes start at 0!
chrs is not null-terminated so you cant just do "chrs" either. You have to loop it like I did above.
void shift(char chrs[5],int places)
An array of chars is already the same as a char * in a sense. So instead of calling for chrs[5], call for a char*. THen you can make changes directly to the character array.