BRoke
BRoke

Reputation: 1

Why I am getting this output from this loop?

#include <iostream>
using namespace std;

I am very new to cpp and programming and I am trying to find the factors of a number, max, why is my code output coming out the way it is?

int max;
cout << "Enter a number you'd like to see the divisors of: " << endl;
cin >> max;

//I am trying to find all divisors for the number max
//I know this isn't the most efficienct way but I thought that it would work.
//Instead of 50, 25, 20, 10, 5 ,1 for output it looks like 50, 25, 25, 25 25, 5 

for (int t=1; t <= max; t++) {
  if (max % t == 0) {
    int m = max/t; 
  }
} 
cout << m << endl;

Upvotes: 0

Views: 79

Answers (3)

Ashok Bhaskar
Ashok Bhaskar

Reputation: 361

Is this your entire program? The variable

int m

is out of scope at the line

cout << m << endl;

which leads me to believe you have another variable named "m" declared earlier in the program that is being shadowed by the newly declared int also named "m" inside the if-block. If this is the case, then the previously declared variable "m" outside the if-block would get printed to cout.

Upvotes: 0

Ron
Ron

Reputation: 15501

Your output is misplaced. Move the cout << m << endl; statement into your if statement block:

if (max % t == 0) { // start of a block
    int m = max / t;
    std::cout << m << '\n';
} // end of a block

Make sure you properly mark the block of statements using braces {}. Now for a given input of 50 the output is:

50 25 10 5 2 1

Live example on Coliru

Upvotes: 3

Kfirka
Kfirka

Reputation: 74

using namespace std;

As BO41 said, you should never use the namespace, here are some reasons: Why is "using namespace std" considered bad practice?

Instead of using the namespace, you should write only what you are using, for example:

using std::cout;
using std::endl;

Now back to the question:

for(int t=1; t <= max; t++){
    if(max % t == 0)
        int m = max/t; 
} cout << m << endl;

Note that you are defining m inside the if and using it outside of it. also, if it wasn't for that, you would print only the last divisor you find. You should do something more like:

for(int t = 0; t <= max; t++){
    if(max % t == 0){
        int m = max/t
        cout << m << endl;
    }
}

here you will print every divisor of max. Personally, i would always open a block for if statements, even if there is only one line in the block, for me it's much more organized and may prevent errors.

Upvotes: 2

Related Questions