-8

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.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Shawn99
  • 15
  • 4
  • 2
    in `else if` the `if` is evaluated only when the enclosing `if` condition is false... It changes the things to use one form or the other... `if (c1) {} else if (c2) {}` is equivalent to `if(c1) {} if (!c1 && c2) {}`. – Jean-Baptiste Yunès Dec 16 '16 at 06:21

2 Answers2

0

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
Ahmar
  • 740
  • 6
  • 26
0

An else if block will execute only if the immediately previous "if" block is not executed. For example:

int a = 9;
if (a==9)         //true and executed
     cout<<"is 9";
else if(a<5)      //not executed since the if(a==9) block executed
     cout<<"is less than 5";

will output:

is 9

Whereas:

int a = 9;
if (a==9)         //true and executed
     cout<<"is 9";
if (a<5)           //true and executed regardless of the previous if block
     cout<<"is less than 5";

will output:

is 9
is less than 5
officialaimm
  • 378
  • 4
  • 16