app crash with mod division

NO need to read my post...i see what my (rather silly) error was...it turns out that you can't divide by ZERO!

Hi,
Still a C++ newb here, though enjoying the langauge more. I have a question that probably has an obvious answer...but I don't see it. I'm writing a PrimeFactory class but the app keeps crashing. Here are the files.


The problematic line is if(num % i == 0) in the PrimeFactory.C . When I remove that line the app doesn't crash but i'm not sure why that line would cause an issue. I'm using very small ints here...like 5


PrimeFactory.h
1
2
3
4
class PrimeFactory{
public:
bool isPrime(int num );
};



PrimeFactory.C
1
2
3
4
5
6
7
8
9
10
11
12

#include <iostream>
#include <math.h>
#include  "PrimeFactory.h"

bool PrimeFactory::isPrime(int num ){
for(int i= 0;i < sqrt(num);i++)
    if(num % i == 0)
      return false;

    return (num == 2);
    }


The Main
1
2
3
4
5
6
7
8
9
10
11
12
13
14

#include <iostream>
#include <math.h>
#include <string>
#include "PrimeFactory.h"

using namespace std;
int main() {
int num = 5;
PrimeFactory p;
bool r = p.isPrime(num);
  return 0;
}



While i'm posting questions, i have 1 more (unrelated one), can someone explain why I must put brackets arround string when I include it...as opposed to quotes when I inlcude a custom class's header file. i.e. why the different sytnax for the next two lines

#include <string>
#include "PrimeFactory.h"
Last edited on
if(num % i == 0) causes a crash when i == 0 because division by zero is undefined. (So is modulo zero.)

#include <> and #include "" tell compiler to look into different places for the files which should be included.
Last edited on
Line 7 in PrimeFactory.C should be for (int i=1;i<=sqrt(num);i++)

#include <foobar.h> tells the compiler to look for foobar.h in the include directories it was provided with (e.g. "C:\MinGW\include").
#include "foobar.h" tells the compiler to look for foobar.h in the same directory as the file the directive appears in.
Suppose main.cpp is in /home/user/c++/main.cpp and it contains the following lines:
1
2
3
4
#include <iostream>
#include "foo.h"
#include "foo/bar.h"
#include "../foo2.h" 
iostream will be searched in /usr/include, /usr/local/include, and any other directory that was provided for the compiler to search in. foo.h should be in /home/user/c++/, bar.h should be in /home/user/c++/foo/, and foo2.h should be in /home/user/.
Topic archived. No new replies allowed.