Reputation: 3
I m working with a pattern program but facing one issue my condition is false then the condition is run?
Pattern Programme:
#include<iostream>
using namespace std;
int main()
{
int i,j,k,n;
std::cout << "Enter Number:" ;
cin>>n;
for(int i=1;i<=n;i++) //row
{
//first time condition false 1(k value)<1(i value) not execute first time this is ok
//second time condition false 2(k value)<2(i value) why this condition run when condition is false????
for(int k=1;k<i;k++) //space
{
cout << " ";
}
for(int j=i;j<=n;j++) //column
{
std::cout << "*" ;
}
cout << "\n";
}
}
execute of program:
ex: user enter 3
first time excite condition properly :
now i=1 and k=1
for(int i=1;1<=3;i++) //row
{
for(int k=1;1<1;k++) //space //1<1 false ok.
{
cout << " ";
}
Issue with second-time condition:
now i=2 and k=2
for(int i=1;2<=3;i++) //row
{
for(int k=1;2<2;k++) //space //2<2 false Not Ok problem is here why these condition is run
{
cout << " ";
}
Link Programme:https://onlinegdb.com/Hk9DHuwvL
Upvotes: 0
Views: 69
Reputation: 88017
Here's your loop
for (int k=1;k<i;k++)
{
cout << " ";
}
This loop starts at 1
and goes up to but not including i
. So it runs i - 1
times. If i == 1
then it runs zero times, if i == 2
then it runs one time, if i == 3
then it runs two times, if i == 4
then it runs three times, etc. etc.
You seem to think the the number of times it has run before makes a difference to how many times it runs next, but that is not true. The loop starts again each time it is run.
Upvotes: 0
Reputation: 36441
when i=2 and k=2
, your explanation is wrong, the right one is:
When i=2
, inner code of i
loop is:
for(int k=1;k<2;k++) //space, loops one time
{
cout << " ";
}
for(int j=2;j<=3;j++) //column, loops two times
{
std::cout << "*" ;
}
cout << "\n";
Upvotes: 2