0

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

2
  • What is the issue? What output are you expecting? Commented Apr 5, 2020 at 15:19
  • @DaniloIvanovic why space loop is one-time run that is my issue?? even I write k++ Commented Apr 5, 2020 at 15:25

2 Answers 2

2

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"; 
Sign up to request clarification or add additional context in comments.

6 Comments

why space loop is run one time that is my issue?? even I write k++
The space loop runs one time because i == 2. Look at the loop for(int k=1;k<i;k++). If i == 2 then the loop runs one time. How many times were you expecting it to run?
problem is that second time i=2 this is right but also k=2 but here k=1 that is the reason still i does solve this thing a
I hope my question is understood to you
i=2 this is right but also k=2 That is wrong, k = 1 not 2
|
0

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.

3 Comments

you mean again k value is reset 1 when increasing 2 and now again k value is reset 1 when increased 3 ?
@dipsvirag Yes, k is reset each time the loop runs.
now my confusion is clearly that is the my doubt thanks john

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.