[Solved] Why does the program give me a different result when I use if statement [duplicate]


In an if else-if statement you put multiple conditions to evaluate the result.

The following is how the statements will work in your case:

if(row==1||row==n||row==2*n-1)
cout<<"*"; //if true then put * or if false then move down
else if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the first is false and the 2nd one is true then put * or if false then move down
else
cout<<" "; // if both of the above statements are not true put whitespace

I hope it helps.

Update: (from the OP’s comment)

if(row==1||row==n||row==2*n-1)
cout<<"*"; // if the above is true then show *
else
cout<<" "; // else show whitespace

if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the above is true show *
else
cout<<" "; // else show whitespace

In this code the first and second statements work independently and there is nothing related in them. If the first one is true or false it doesn’t matter to the second one and vice versa.

Furthermore, you can omit the else statement if you don’t need it.

if (col==1&&row<n||col==n&&row>n)
cout<<"*"; // if the above is true show *
// here else will not show whitespace because it is omitted

2

solved Why does the program give me a different result when I use if statement [duplicate]