My issue
My code
#include <bits/stdc++.h>
using namespace std;
int main() {
string word = "Programming";
cout << word[ 0 ] <<endl;
cout << word[ "r" ];
return 0;
}
Learning course: Learn C++
Problem Link: CodeChef: Practical coding for everyone
The problem wants to output o and r (on different lines) from word. Your first output line will result in P which is not o or r. Your second output line is trying to access a character in word at location r, which doesn’t exist. Remember that word[i] exists if 0 \le i \lt n (where n is the number of characters in word and i is an integer). If it helps, create an index to element mapping chart as shown below:
Index: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
Character: P | r | o | g | r | a | m | m | i | n | g
Now, find r and o in the chart above. What indices do you see corresponding to them (note there maybe more than one answer, but any works)? Let’s call the index of o as i and the index of r as j (where 0 \le i, j \le 10).
Once you have the values for i and j, in your code:
#include <bits/stdc++.h>
using namespace std;
int main() {
string word = "Programming";
// Instead of using "i" and "j" in the code, replace them with the VALUES you found for them earlier.
cout << word[i] <<endl;
cout << word[j];
return 0;
}