mercredi 18 août 2021

Trouble with nested while loops in c++ [closed]

I am having a problem with a program I'm trying to write. The user should enter an odd number and then the program should display the number line by line in decreasing order. Eg., if 5 is entered the output should be:

1 2 3 4 5

1 2 3 4

1 2 3

1 2

1

1 2

1 2 3

1 2 3 4

1 2 3 4 5

The problem is that it only displays the first line of numbers... This is what I've tried so far:

#include <iostream>

using namespace std;

int main()
{
    int number = 0;
    int test = 0;
    int i = 0;
    int k = 0;
    int j = 0;

    cout << "Enter an odd number: ";
    cin >> number;

    test = number%2;
    i = 1;
    k = number;
    j = k + 4;

    if (test == 0)
    {
        cout << "You have entered an invalid number! Please try again." << endl;
        exit(-1);
    }

    if (i <= number && i != 0)
    {
        while (j > 0)
        {
            while (k > 0)
            {
                cout << i << "\t";
                k = k - 1;
                i = i + 1;
                j = j - 1;
            }
            j = j - 1;
        }
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire