I have a simple C program
int main()
{
int n, maxn = 21;
float SN, x;
printf("input x:");
scanf("%f", &x);
printf("input maxn:");
scanf("%d", &maxn);
for(n=0;n<=maxn;n++){
SN = SN + pow(x,n);
n = n + 1;
}
printf("%f", SN);
getch();
return 0;
}
I need to make it versatile so the user can enter any expression to replace pow(x, n) with whatever the user inputs from keyboard. How do I put an expression into the program?
Alt + F4 is a keyboard shortcut that completely closes the application you're currently using on your computer. Alt + F4 differs slightly from Ctrl + F4, which closes the current tab or window of the program you're currently using.
If you have the English (India) keyboard selected, then use the keys combination 'CTRL + ALT + 4' to get the Indian Rupee Symbol (₹). Otherwise follow the steps below: Type 'Control Panel' in search input at bottom-left corner of your screen. Select/Click 'Control Panel Desktop app' from the search results.
C and C++ don't offer you this feature already implemented because there is a clear cut between the compile time (when expressions are analyzed syntactically) and run time (when they're evaluated).
Implementing a parser and compiler/evaluator for expression is a good exercise but it's not trivial and would probably require a lot more experience than you have at this moment (given the question you asked).
The easiest to understand approach to this problem is in my opinion a recursive descent parser but for just the four operations, numbers and variables I'd guess it would require a hundred or so lines of code.
yacc and bison are tools that were designed to generate automatically parsing/evaluation code from a definition of a grammar. I personally prefer to hand-write parsers because of the finer control you get (especially on error handling or when the syntactic and semantic level interact, but that's me and I'm also a bad case of NIH syndrome).
Higher level languages like Python or Javascript instead offer you this feature already implemented as eval
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With