Search code examples
c++if-statementnested-loops

Why does the program give me a different result when I use if statement


Why does the program give me a different result when I use if statement.

If I use else if statement It prints a 5. However. If I change else if to a if statement it prints a completely different picture. Could anyone tell me why is that?

#include<iostream>
using namespace std;

 // Print 5.
 int main() {
 int n=5;
 for(int row=1;row<=2*n-1;row++)    
  {
  for(int col=1;col<=n;col++)
   {
   if(row==1||row==n||row==2*n-1)
    cout<<"*";
   else if (col==1&&row<n||col==n&&row>n)
    cout<<"*";
   else
    cout<<" ";
  } 
 cout<<endl;
 }
 return 0;
}

I always thought if and else if are the same.


Solution

  • 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