top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to find if a given expression is a valid arithmetic expression?

+2 votes
2,369 views

Eg:(())()) - Invalid expression, (()()) - Valid expression?

posted Oct 30, 2015 by Mohammed Hussain

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer
/*
 * C Program to Check if Expression is correctly Parenthesized  
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int top = -1;
char stack[100];

// function prototypes
void push(char);
void pop();
void find_top();

void main()
{
    int i;
    char a[100];
    printf("enter expression\n");
    scanf("%s", &a);
    for (i = 0; a[i] != '\0';i++)
    {
        if (a[i] == '(')
        {
            push(a[i]);
        }
        else if (a[i] == ')')
        {
            pop();
        }
    }
    find_top();
}

// to push elements in stack
void push(char a)
{
    stack[top] = a;
    top++;
}

// to pop elements from stack
void pop()
{
    if (top == -1)
    {
        printf("expression is invalid\n");
        exit(0);
    }   
    else
    {       
        top--;
    }
}

// to find top element of stack
void find_top()
{
    if (top == -1)
        printf("\nexpression is valid\n");
    else
        printf("\nexpression is invalid\n");
}
answer Nov 4, 2015 by Shivaranjini
Similar Questions
+7 votes
#include<stdio.h>

int &fun()
{
   static int x;
   return x;
}   

int main()
{
   fun() = 10;
   printf(" %d ", fun());

   return 0;
}

It is fine with c++ compiler while giving error with c compiler.

...