I am trying to create a prime factorization c++ program, and halted immediately by this "else" error. I would really appreciate some assistance with my coding. I am new to c++, so I am just getting used to the rules. Here is what I have so far:

#include <iostream>

using namespace std;

 

int main() {
	int number=0;		// the input number
	int i=2;       
	int j=0;
	
	// get the user input
	cout<<"Please Enter a Number :";
	cin >>number;   

	// reprompt loop if incorrect (input < 2)
    while (number < 2) {                                               
      cout<<"Enter a Number Greater than 2:";
	  cin>>number;
	}
	// input is composite
	if (number % i == 0) {
		cout<< number <<"is a COMPOSITE number" << endl;
		for (i=2; i<=number; i++) {
			if (number % i == 0) {
 				cout << i << " Has Been Found as A Prime Number of " << number << endl;
			}
		}
	else {
		cout<< number <<"is a PRIME number" << endl;
	}
	}
 return 0;

}

Recommended Answers

All 4 Replies

You would need a boolean value to store the state of the primality of the number. A simpler approach is to use a function, which hopefully you have learned. This is what I usually use for a primality check:

bool isPrime(int x)//checks if x is a prime number
{
    for (int i=2; i*i<x; i++)//loop from 2 to SQRT(X)
    {
        if (x%i==0)
            return false;//its definately NOT prime
    }
    //the fact that we even made it here means that it is prime!
    return true;
}

Is the error during compilation, or during execution?
What is the error message?

Taking a quick look at the code--and maybe I am mistaken--but the closing brace on line 28 seems to match the opening brace for the for loop on line 24. Or is that for the if statement on line 22?

As a first step, double-check to see all your closing braces are where they should be.

Is the error during compilation, or during execution?
What is the error message?

Taking a quick look at the code--and maybe I am mistaken--but the closing brace on line 28 seems to match the opening brace for the for loop on line 24. Or is that for the if statement on line 22?

As a first step, double-check to see all your closing braces are where they should be.

The error is before execution, and the bracket on line 28 is indeed for the for loop (line 24). I checked all the brackets.

1. Better indentation.
2. Start again.
3. Can you define a prime number?
4. (optional) Use a function.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.