C Programming I made a program that works for this task Have
C++ Programming:
I made a program that works for this task:
Have a user input a string. Then display this string smashed up as follows: display the first character in the string, then the last, then the second, then the second to last, then the third... So if the string is “abcdef”, it will display: afbecd (input “abcdef”)\". And this is my coding for this task.
#include
#include
using namespace std;
void printLetters(string s);
int main()
{
string seq;
cout << \"Enter anything: \"< getline(cin, seq);
printLetters(seq);
cout << endl;
return 0;
}
void printLetters(string s)
{
int a =s.length();
if (a == 0)
{
return;
}
cout << s[0];
if(a>1)
cout<< s[a -1];
s.erase(0, 1);
a = s.length();
if(a>=1)
s.erase(a-1);
printLetters(s);
}
If I run this programm, I get these answers:
Example 1:
Enter anything:
1234 (input)
1423 (output)
Example 2:
Enter anything:
12345678 (input)
18273645 (output)
Example 3:
Enter anything:
what does this sentence look like? (input)
w?heakti ld okeoso lt heicsn esten (output)
QUESTIOIN: Now, What I need to do is unmasing this program. Which means that If I enter my output that I got in the program above, I should get the input that i entered in the program.
And these are the examples that i should get.
Example 1:
Enter anything:
1423 (input)
1234 (output)
Example 2:
Enter anything:
w?heakti ld okeoso lt heicsn esten (input)
what does this sentence look like? (output)
Solution
#include <iostream>
#include <string>
using namespace std;
void printLetters(string s);
string unmash(string s);
int main()
{
string seq;
cout << \"Enter anything: \"< getline(cin, seq);
printLetters(seq);
cout << endl;
string unm = unmash(seq);
cout <<\"Unmashed:\"<< unm << endl;
return 0;
}
void printLetters(string s)
{
int a=s.length();
if (a == 0)
{
return;
}
cout << s[0];
if(a>1)
cout<< s[a -1];
s.erase(0, 1);
a = s.length();
if(a>=1)
s.erase(a-1);
printLetters(s);
}
string unmash(string s){
int a = s.length();
int i=0;
string st = \"\";
//add odd indexed
while(i<a){
st += s[i];
i = i+2;
}
// check even or not.
a%2==0?i=a+1:i=a;
// add to string in reverse order.
while(i>0){
st += s[i];
i = i-2;
}
return st;
}
/*
sample output
Enter anything: 1423
1342
Unmashed:1234
*/


