drj
drj

Reputation: 11

C++ Help can't get it work

Write a program that generates all the factors of a number entered by the user. For instance, the number 12 has the factors 2 * 2 * 3. This program has the following requirements:

  1. The user must enter a positive integer. If the user enters something else, your program should output an error message and let the user enter a new value. Use a do/while loop to make sure the user input is successful.

  2. The factors must be output in increasing order. The lowest factor your program should report is 2.

  3. Your program should output 4 factors per line, each factor in a field of 10 characters. (Hint: the number of factors output determines when to output endl!)

  4. You will need a while loop to report the factors. Here are some helpful hints:

    1. If (a % b == 0) then a is a factor of b.

    2. When you have found a factor, output the factor and then reduce the number you are working with by dividing the number by the factor… ie) b = b / a;

I have this code I can't get it to display the factors. After you enter the number it just ends with out displaying the factors.

#include<iostream>

using namespace std;

int factor(int& n)
{
  for(int k=2; k<=n; k++)
    if(n%k==0)
    {
      n = n/k;
      return k;
    }
}


int main()
{
  int n;
  int p=0;

  do
  {
    cout << "Enter a Positive Integer :";
    cin >> n;
  } while(n<=0);

  cout << "Factors are " << endl;

  while(1)
  {
    if(n==1) break;
    cout << factor(n) << " ";
    p++;
    if(p%4==0) 
      cout << endl;   // new line after every 4 factors !!

    system("pause");
    return 0;
  }
}

Upvotes: 1

Views: 1801

Answers (2)

phoxis
phoxis

Reputation: 61990

So after indentation it is clear that :

 while(1)
 {
  if(n==1) break;
  cout << factor(n) << " ";
  p++;
  if(p%4==0) 
    cout << endl;   // new line after every 4 factors !!

  system("pause");
  return 0;
 }

After just calculating and printing the first factor you return from main. So please indent the code and keep proper formatting. Also even if you have single line under if , for etc, enclose them in braces.

Upvotes: 0

Sander De Dycker
Sander De Dycker

Reputation: 16243

It's difficult to see due to your (lack of) indentation, but this part :

system("pause");
return 0;

is inside the while(1) loop. It should be outside of the while loop.

Upvotes: 5

Related Questions