Using stacks, write a program in C++ to check if an expression is correctly parenthesized. In other words, you are checking that every left parenthesis has a matching right parenthesis. Only check for parentheses and no other characters, i.e., if (2+3)*5 is given as input, the output should be “The expression is correctly parenthesized”. Given an input 5(3+8, the output should be “The expression is not correctly parenthesized”.
Write a recursive method called powerof3() that, given an integer n, returns 3n (3 to the nth power). Please remember that 30 = 1, 31 = 3, 32 = (3*3) = 9, 33 = 3*3*3 = 27, etc.
Write a recursive method called capitalize() that will capitalize the letters in a sentence. For example, capitalizing (“Old McDonald had a Farm”) would give you: OLD MCDONALD HAD A FARM. You cannot use the toupper function to do the capitalization for you.
Expert Answer
Balanced Expression Code:
#include<bits/stdc++.h>
using namespace std;
bool areParanthesisBalanced(char expr[])
{
stack<char> s;
char a, b, c;
for (int i=0; i<strlen(expr); i++)
{
if (expr[i]=='(‘||expr[i]=='[‘||expr[i]=='{‘)
{
s.push(expr[i]);
}
else
{
switch (expr[i])
{
case ‘)’:
a = s.top();
s.pop();
if (a=='{‘||a=='[‘)
cout<<“Not Balancedn”;
break;
case ‘}’:
b = s.top();
s.pop();
if (b=='(‘||b=='[‘)
cout<<“Not Balancedn”;
break;
case ‘]’:
c=s.top();
s.pop();
if (c=='(‘||c=='{‘)
cout<<“Not Balancedn”;
break;
}
}
}
if (s.empty())
return true;
else
return false;
}
int main()
{
char expr[]=”5(3+8″;
if(areParanthesisBalanced(expr))
cout<<“Exp Balanced”;
else
cout<<“Exp Not Balanced”;
return 0;
}
Output Screenshot:
Power Code:
#include<iostream>
#include<conio.h>
using namespace std;
void powerData(int base,int power);
int main()
{
int base,power;
cout<<“Enter base and power: “;
cin>>base>>power;
powerData(base,power);
}
void powerData(int b,int p){
int i;
int powValue=1;
for(i=p;i>0;i–)
{
powValue=powValue*b;
}
cout<<“power is: “<<powValue;
}
Output Screenshot:
Capitalize Data Code :
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
void capitalize_data(char* objStr);
int main()
{
char objStr[20];
cout<<“Enter the String Value : “;
cin>>objStr;
capitalize_data(objStr);
}
void capitalize_data(char* objStr){
int objI;
for(objI=0;objI<=strlen(objStr);objI++)
{
if(objStr[objI]>=97 && objStr[objI]<=122)
{
objStr[objI]=objStr[objI]-32;
}
}
cout<<“nThe String in Uppercase = “<<objStr;
}
Output Screenshot: