Tiana Chargin
Tiana Chargin

Reputation: 51

Not getting correct output Function not working

I'm trying to write a code that will take a number that the user inputted and create an inverted triangle like: 8 6 4 2 0 on the first line, 6 4 2 0 on the second line, 4 2 0 on the third line, 2 0 on the fourth line, 0 on the last line. My nested for loops worked in a previous code that was in the main not in a function, but I decided I wanted to create a function that when called would run through the loops. However, something in my code isn't right since now I don't get an inverted triangle. I just get 0 and I think that's because my return is 0. I'm not sure if I'm writing my function incorrectly or if it's something else.
Please help. Thank you

#include <iostream>

using namespace std;

int row(int num)
{
    int number;
    int decreasedNumber;
    
    for(int i = number; i >= 0; i -= 2)
    {
        decreasedNumber = i;
        
        for(int j = decreasedNumber; decreasedNumber >= 0; decreasedNumber -=2)
        {
            cout << decreasedNumber << " ";
        }
        cout << endl;
    }
    return 0;
}

int main()
{
    int number;
    
    //Prompting the user to enter a number and collect that input
    cout << "Enter a number: " << endl;
    cin >> number;
    
    cout << row(number);
   
    return 0;
}

Upvotes: 0

Views: 51

Answers (2)

cigien
cigien

Reputation: 60208

You are accepting num as a parameter to row, but never using it. Also, you are using number, but never initializing it. Instead, it seems you want number to be the parameter to the function, instead of a local variable.

Here's a demo.

Also, the variable j is never used in the loop, so you should just remove it.

Also, please don't use using namespace std;, it's a bad habit that you should avoid.

Upvotes: 4

MikeCAT
MikeCAT

Reputation: 75062

You are using number as the initial value of i.

number is uninitialized and its value is indeterminate.

Instead of number, you should use the argument num as the initial value of i.

Upvotes: 1

Related Questions