0
//C++ Program to print diamond using stars
//N.B. The following code is correct and prints a diamond using stars.
//My doubt is regarding this expression : ***int Space=(2*n-1)/2;***
#include <iostream>
using namespace std;

int main()
{
    int n;

    cout << "Enter the number of rows : ";
    cin >> n;



    int Space=(2*n-1)/2;                  
  // The only problem I have is difficulty in understanding the order of precedence with this expression
 


    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=Space; j++)
        {
            cout << " ";
        }
        for(int j=1; j<=2*i-1; j++)
        {
            cout << "*";
        }
        cout << endl;
        Space--;
    }
    Space=0;
    for(int i=n; i>=1; i--)
    {
        for(int j=1; j<=Space; j++)
        {
            cout << " ";
        }
        for(int j=1; j<=2*i-1; j++)
        {
            cout << "*";
        }
        cout << endl;
        Space++;
    }
    return 0;
}

I was expecting the result of the above mentioned expression to be in fraction. For example: If n=5, I was expecting Space=9/2; but it displays the answer Space=4.

I admit the answer is correct but I am confused since * operator has a higher precedence than - operator, * operator should be operated first; Shouldn't it?

  • 2
    if `n == 5` then `int Space=(2*n-1)/2;` is the same as `int Space=((2*5)-1) / 2;` => `(10-1) / 2` => `9 / 2` => `4` – Ted Lyngmo Apr 04 '22 at 06:21

0 Answers0