Verifying if a nr is prime. Program not running fully

Hi! I am new to C++ and I am trying to learn on my own, so I tried to make a program that verifies if a number is prime or not. It shows no errors and when I run it, it will ask for number input, but then nothing happens. Any suggestions on how to fix this will be much appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;
int main()
{
unsigned int a, n, i=0;
cout << "Input a natural number: ";
cin >> a;
for (n = 2; n < a; ++n)
{
	if (a % n == 0)
	{ i++; }
}
if (i == 0)
{ cout << "This number is prime"<<endl; }
else
{ cout << "This number is not prime"<<endl; }
}
Works for me. What number are you entering?
Seems fine here.
$ g++ bar.cpp
$ ./a.out 
Input a natural number: 13
This number is prime
$ ./a.out 
Input a natural number: 42
This number is not prime


Perhaps you're running the code from your IDE, and the console window vanishes before you see anything.
https://www.cplusplus.com/articles/iw6AC542/
It works for you? I entered several numbers, one of them was 13. I am using visual studio 2019 for the first time, maybe I'm doing something wrong. Thanks for letting me know that the program works though. Cheers:)
Thanks for the link, salem c, I have no idea what that even means so I am going to look into it now! Thanks a lot!
Add this function before main.
1
2
3
4
5
6
7
void wait_key()
{
  std::cout << "** hit any key to continue ** ";
  std::cin.clear();
  std::cin.ignore(255, '\n');
  std::cin.get();
}

At the end of main call waitKey();
Last edited on
Topic archived. No new replies allowed.