I am having trouble figuring out how to return the index of an element in an array or string. My program is an example of an expression tree in a left child-right child array. The user inputs an expression like +2x and output shoud be as follows:
+ 1 2
2 0 0
x 0 0
The 1 in the 2nd column represents the row the left child is in and the 2 in the 3rd column represents the row the right child is in. Another example would be +/43*34
+ 1 4
/ 2 3
4 0 0
3 0 0
* 5 6
3 0 0
4 0 0
this is my code so far:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char s[50];
cout << "Input the prefix expression.\n";
cin >> s;
cout << "\nThe expression tree is:";
int row = strlen(s);
int col = 2;
char a[9][4];
int i, j, c;
int index = 1;
for (j = 0; j < row; j++)
{
a[j][0] = s[j];
for(i = 1; i <= col; i++)
{
if ( s[j] == '+' || s[j] == '-' || s[j] == '*' || s[j] == '/')
{
a[0][i] = index;
}
else
{
a[j][i] = '0';
}
index++;
}
}
for (j = 0; j < row; j++)
{
cout << "\n";
for(i = 0; i <= col; i++)
{
cout << a[j][i] << setw(2);
}
}
cout << "\n\nThe postfix expression is " << endl;
cout << "The infix expression is " << endl;
system ("PAUSE");
return 0;
}
- #include <iostream>
- #include <iomanip>
- using namespace std;
- int main()
- {
- char s[50];
- cout << "Input the prefix expression.\n";
- cin >> s;
- cout << "\nThe expression tree is:";
-
- int row = strlen(s);
- int col = 2;
- char a[9][4];
- int i, j, c;
- int index = 1;
-
- for (j = 0; j < row; j++)
- {
- a[j][0] = s[j];
- for(i = 1; i <= col; i++)
- {
-
-
- if ( s[j] == '+' || s[j] == '-' || s[j] == '*' || s[j] == '/')
- {
- a[0][i] = index;
- }
- else
- {
- a[j][i] = '0';
- }
- index++;
- }
- }
- for (j = 0; j < row; j++)
- {
- cout << "\n";
- for(i = 0; i <= col; i++)
- {
- cout << a[j][i] << setw(2);
- }
- }
- cout << "\n\nThe postfix expression is " << endl;
-
- cout << "The infix expression is " << endl;
-
- system ("PAUSE");
- return 0;
- }