Abhinav K
Abhinav K

Reputation: 87

why does it go into an infinite loop?

I am a beginner. This is a program to print a right angled triangle.The height and base should same. for example if input n = 3 then we should get the output as.

*
* *
* * *

I wrote the following code for this:

#include<iostream>
using namespace std;

int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        while(i>=1){
            cout<<"*";
            cout<<" ";
            i--;
            cout<<i;
        }
        cout<<"\n";
    }

}

but it goes on forever. anything wrong?

Upvotes: 2

Views: 147

Answers (4)

Chandra Shekhar
Chandra Shekhar

Reputation: 617

The main issue in the program is that variable i is being shared by both inner and the outer loop. The inner while loop is trying to modify the value of i to 0 the the value of i is incremented by 1 by outer for-loop , again the control come back to while loop and makes the value of i to 0. This repeats in subsequent steps leading to the infinite loop.

To avoid this ambiguity it is recommended to use another variable j for the inner while loop.

Please have a look at the modified code that solved this issue below :

#include<iostream>
using namespace std;

    int main(){
        int n;
        cin>>n;
        int j;
        for(int i=1;i<=n;i++){
            j=i;
            while(j>=1){
                cout<<"*";
                cout<<" ";
                j--;
                cout<<j;
            }
            cout<<"\n";
        }
    
    }

Upvotes: 0

Meowster
Meowster

Reputation: 657

This happens because your while loop reverts i to 0 and then your for loop starts from 0 each time.

A solution is to use other variable for inner loop:

#include<iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    for (int i = 0; i < n; i++){
        for (int j = 0; j <= i; j++) {
            cout << "* ";
        }
        cout << '\n';
    }
}

Upvotes: 1

Rohith V
Rohith V

Reputation: 1123

The problem is that, after you exit the while loop, the value of i changes back to 1 and the for loop again start from i = 1 which results in the infinite loop

You can store the value of i to another varible like j and use this j to do the while loop Here is the code :

#include<iostream>
using namespace std;

int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        int j=i;
        while(j>=1){
            cout<<"*";
            cout<<" ";
            j--;
            cout<<j;
        }
        cout<<"\n";
    }

}

Output :

* 0
* 1* 0
* 2* 1* 0

Upvotes: 1

Akshay Bande
Akshay Bande

Reputation: 2587

You are decrementing i in while loop and incrementing in for loop. Use separate variable j.

using namespace std;

int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        int j = i;
        while(j>=1){
            cout<<"*";
            cout<<" ";
            j--;
            cout<<j;
        }
        cout<<"\n";
    }

}

Upvotes: 3

Related Questions