Converting a do-while loop into a while loop - c++

My code is this I just want to convert my do-while loop into a for loop or a while loop how do I do that. The point of the program is to reverse the input word. like if you put in abc it would output as cba.
int main()
{
while (i < --length - 1);
cout << word << endl;
return 0;
}

The traditional way to convert a while loop into a for loop takes this form:
// While loop
int i = 0;
while( i < n ) {
// Amazing things happen here
i++;
}
// Equivalent for loop
for( int i = 0; i < n; i++ ) {
// Amazing things still happen here
}
Therefore, applied to your code it would look something like:
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
for( int i = 0, length = word.length(); i < --length - 1; i++ ) {
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
Note that since the do-while loop executes the body of the loop before testing, I had to put one copy of the loop body out front. To avoid having to update two different copies of the code, you may want to extract the loop body into a function, which is then called in front of the loop and in the loop body.
And for a while loop version:
int i = 0, length = word.length();
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
while( ++i < --length ) {
char ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}

An alternative is this, which doesn't bother doing anything with strings of size 0 or 1:
int length = word.length();
if (length > 1)
{
int i = 0;
char ch;
while (i < length)
{
ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
i++;
length--;
}
}
For version:
int length = word.length();
if (length > 1)
{
char ch;
for(int i = 0; i < length; i++, length--)
{
ch = word[i];
word[i] = word[length - 1];
word[length - 1] = ch;
}
}

Related

I am attempting to add a whitespace to the middle of char array. Unsure of how to move it properly

I am checking an array for a sentence end and then making sure there is a space after sentence end. I am attempting to move all the array 1 to the right to make room for the whitespace. userPara[] is just a user entered char array. I CANNOT use strings but can use string class
void add_whitespace(char userPara[])
{
int len = strlen(userPara);
int newlen = len + 1;
char temp1;
char temp2;
char whitespace = ' ';
for (int i = 0; i < newlen; i++) {
if (userPara[i-1] == '.' || userPara[i-1] == '?' || userPara[i-1] ==
'!' && userPara[i] != ' ') {
temp1 = userPara[i];
userPara[i] = whitespace;
for (int j = i; j < newlen; j++) {
temp2 = userPara[j+1];
userPara[j+1] = temp1;
temp1 = userPara[j+2];
userPara[j+2] = temp2;
cout << userPara << endl; //This is for testing
}
}
}
}
it seems to be just moving the the first [j+1] element to the right until that element is out of the string
Since in your inner for you shift to right two elements of userPara, you should increment the counter by 2 (j+=2 not j++).
One example for you purpose could be the following:
for (int i = 0; i < n; i++) {
if(userPara [i] == '.')
{
temp1 = userPara [i];
userPara [i] = ' ';
for (int j = i+1; j < n; j+=2)
{
temp2 = userPara [j];
userPara [j] = temp1;
temp1 = userPara [j+1];
userPara [j+1] = temp2;
}
break;
}
}
As discussed in the comments please note that this approach may have issues regarding this blindly increasing of the array.

continue not working? [c++]

Hi guys I've run into a problem,for some reason a blank string is being printed or you could also say nothing is being printed when I try to print out the string,this only occurs when I include a capital letter in the string such as acB if I type acb it sorts and prints them with no problems,I added a continue statement in to the for loop because I thought this would skip the rest of the code and go to the next iteration if that block of code got executed but to no avail anyway here is my code.
void order(char *str,int size){
bool sorted = false;
while(!sorted){
sorted = true;
for(int i = 0; i < size-1; i++){
if(str[i] >= 'A' && str[i] <= 'Z'){
if((str[i+1])-32 < str[i]){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
if(str[i+1] < str[i]){
char temp = str[i];
str[i] = str[i+1];
str[i+1] = temp;
sorted = false;
}
}
}
}
int main()
{
char str[] = "aCb";
int size = sizeof(str) / sizeof(char);
order(str,size-1);
cout << str << endl;
}
void order(char *str,int size){
bool sorted = false;
while(!sorted){
sorted = true;
for(int i = 0; i < size - 1; i++){
if(str[i+1] >= 'A' && str[i+1] <= 'Z' && str[i] > 'Z'){
if(str[i+1] < str[i] - 32){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
else{
if(str[i] >= 'A' && str[i] <= 'Z' && str[i + 1] >= 'Z'){
if(str[i+1] -32 < str[i]){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
if(str[i+1] < str[i]){
char temp2 = str[i];
str[i] = str[i+1];
str[i+1] = temp2;
sorted = false;
continue;
}
}
}
}
}
int main()
{
char str[] = "aCB";
int size = sizeof(str) / sizeof(char);
order(str,size-1);
cout << str << endl;
}
First IF: Checks if the first letter is lowercase and the second letter is uppercase.
Second IF: Checks if the first letter is uppercase and the second letter is lowercase.
Third IF: then both letters are uppercase or lowercase.

Keep getting undeclared identifier I error caesar

I'm working on pset2 from the cs50 course, but I don't understand why I keep getting this error that I didn't declare I, because I think I did.. First I ask for a number to use as a key for the encrypting, than I ask for plain text, which should be encrypted by the number given, and printed out later.
Here's my code:
int main(int argc, string argv[])
{
// get key from command line argument, return 1 if wrong
if (argc < 2)
{
printf("No value entered!\n");
return 1;
}
//store key in integer
int k = atoi(argv[1]);
if (k < 0)
{
printf("No right variable detected\n");
return 1;
}
else
{
printf("Plain text: \n");
string s = get_string();
// iterate over strings in argv
for (int i = 0; n = strlen(s); i < n; i++);
{
if (isalpha(s[i]))
{
// for capitalized letters
if (isupper(s[i]))
{
int a = s[i] - 65;
int b = (a + k) % 26;
int c = b + 65;
printf("%c", c);
}
//for lowercase
else
{
int d = s[i] - 97;
int e = (d + k) % 26;
int f = e + 97;
printf("%c", f);
}
}
else
{
//for non alphabetical characters
printf("%c", s[i]);
}
}
}
// print new line
printf("\n");
return 0;
}
You have a ; at the end of for loop
for (int i = 0; n = strlen(s); i < n; i++);
^
Change it to
for (int i = 0, n = strlen(s); i < n; i++)
Moreover, as you can see init must be placed before the first semicolon ,(comma) separated.
Side notes
You should avoid to use "magic numbers" in code. In your case you can simply use
You should use variable names that can make your code more readable
You can do your ashing with a single variable, not 6
if (isalpha(s[i]))
{
int ashed;
// for capitalized letters
if (isupper(s[i]))
{
ashed = s[i] - 'A';
ashed = (ashed + k) % 26;
ashed += 'A';
}
//for lowercase
else
{
ashed = s[i] - 'a';
ashed = (ashed + k) % 26;
ashed += 'a';
}
printf("%c", ashed);
}
For loop is wrong, it accepts 3 parameters, you set it 4.
Also, notice semicolon after your for loop.
This line:
for (int i = 0; n = strlen(s); i < n; i++);
should be:
for (int i = 0, n = strlen(s); i < n; i++)
Notice comma and no semi-colon at the end

Converting "12345678" into "1-234-5678", my code produces nothing

It's not showing any errors but for some reason my cout's wont show up. Am I missing something? I'm trying to convert a series of numbers to a typical phone number format.
int numberCount = 0;
string phoneNumberUnform = "12345678";
for (size_t i = 0; i < phoneNumberUnform.length(); i++)
{
numberCount++;
}
if (numberCount = 8)
{
string phoneNumber[10];
phoneNumber[0] = phoneNumberUnform[0];
phoneNumber[1] = "-";
for (int i = 2; i = 5; i++)
{
phoneNumber[i] = phoneNumberUnform[i-1];
}
phoneNumber[6] = "-";
for (int i = 7; i = 10; i++)
{
phoneNumber[i] = phoneNumberUnform[i-1];
}
cout << phoneNumberUnform;
cout << phoneNumber;
return 0;
}
Use the std::string's insert member function:
#include <iostream>
#include <string>
int main() {
std::string s = "123456789";
s.insert(1, "-");
s.insert(5, "-");
std::cout << s;
return 0;
}
For the manual approach, resize the original string to accommodate the additional two characters:
std::string s = "123456789";
std::string temp = s;
int strlen = temp.length();
s.resize(s.length() + 2);
s[1] = '-';
for (int i = 2; i < 5; i++)
{
s[i] = temp[i - 1];
}
s[5] = '-';
for (int i = 6; i < strlen + 2; i++)
{
s[i] = temp[i - 2];
}
In the second loop use the temp[i - 2] index instead of the temp[i - 1] one because by then we have already inserted the two - characters into our original string.

c++ encryption with rotation

I'm having some issues in creating a function that encrypts a word using a rotation number the user inputs. Here is what I have so far:
string encryptWord(string word, int num)
{
string newWord;
newWord = word;
for(int i = 0; i < word.length(); i++)
{
newWord[i] = tolower(word[i]);
if((word[i] >= 'a') && (word[i] <= 'z'))
{
newWord[i] = word[i] + (num % 26);
if(newWord[i] > 'z')
newWord[i] = newWord[i] - 26;
}
}
return newWord;
}
now in my main when I test it out with
cout << encryptWord("xyz", 6);
the output I get is: de
Similarly, for decryption I have
string decryptRotWord(string word, int num)
{
string newWord;
num = num % 26;
int index;
for(int i = 0; i < word[i]; i++)
{
newWord[i] = tolower(word[i]);
if(word[i] >= 'a' && word[i] <= 'z')
{
index = word[i] - num;
if(index < 'a')
index = index + 26;
newWord[i] = index;
}
}
return newWord;
}
however, for this one, it does not output anything when I test with
cout << decryptRotWord("vdds", 2);
In your decrypt function, I think you have a mistake on the loop end condition:
for(int i = 0; i < word[i]; i++)
As in the encrypt function, you should iterate over length
for(int i = 0; i < word.length(); i++)
When your for loop arrives to the letter 'z', it does 'z' + 6. But that goes beyond the max length of a char (127). You get an undefined behavior from that.
You should implement a way of starting to count from 'a' whenever you check the encryption goes beyond 'z'.
For the decryption, same as mentioned before, you want to test :
i < word.length()