CandyMonster
CandyMonster

Reputation: 1

Unable to get output for multiplication

#include<iostream.h>
int main()
{
  int n[50],p=0;
  double g=1;
  char c;
  cout<<"\n press a for addition";
  cout<<"\n press m for multiplication";
  cin>>c;
  if(c=='a')
  {
    for(int i=0;n[i]=!'=',i<50;i++)
    {
      cin>>n[i];
      p+=n[i];
    }
    cout<<p;
  }
  else if(c=='m')
  {
    for(int j=0;n[j]=!'=',j<50;j++)
    {
      cin>>n[j];
      g*=n[j];
    }
    cout<<g;
  }
  else cout<<"wrong input";
}

I have wrote this code, it works perfectly fine when addition part is used but when multiplication is done it isn't giving the final product. Whenever I click '=' it doesn't give any final product during multiplication but while addition the same logic works fine.

Upvotes: 0

Views: 54

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

You have multiple problems:

  • The array n isn't initialized so its contents will be indeterminate, and using indeterminate values lead to undefined behavior.

  • Fortunately (for you) the loop "condition" expression n[j]=!'=',j<50 doesn't do what you probably think it does... The part n[j]=!'=' is actually equal to n[j] = !'='. That is you assign the result of !'=' to n[j].

  • And about the loop "condition", the result of n[j]=!'=',j<50 is the result of j<50 only, because that's how the comma operator works.

  • With cin>>n[j] you can't read arbitrary characters, as n[j] is an int and you only read int values. The only way to get a '=' from the input is if the user inputs the value 61 which happens to be the ASCII encoded value for '='.

  • Your loop "condition" also have another flaw, because you increase j before you check n[j], so in the condition n[j] will always be an element of the array that you haven't read into.

  • And building on the previous point, because the value of j will be wrong in the "condition" you will go out of bounds of the array which also leads to undefined behavior.

Upvotes: 3

Related Questions