Not long started c++, and I thought I had a handle on it, but I ordered this book called c++ without fear, and since I have started reading it I am becoming more and more confused. I am on the chapter using functions and the examples in the book firstly should mirror the examples on the internet, but they dont, and now unless I am reading this coded wrong, it has me confused. I will put comments in could please someone explain, as I think the code is wrong:
Code:
#include <iostream>
#include <math.h>
using namespace std;
int prime(int n);
int main()
{
int i; int being declared here as i
while (1)
{
cout << "Enter a number (0 to exit) and press ENTER: ";
cin >> i; User input now defined as i
if (i == 0)
break;
if (prime(i))
cout << i << " is prime" << endl;
else
cout << i << " is not prime" << endl;
}
cout << endl;
system("PAUSE");
return 0;
}
int prime(int n)
{
int i; Int i now declared a 2nd time
double sqrt_n = sqrt(static_cast<double>(n));
for (i = 2; i <= sqrt_n); i++) Int i now defined a 2nd time as 2
{
if (n % i == 0)
return false;
}
return true;
}
Now as I has been declared and defined in main, how can you redeclare and define it in the function as a different variable, surely they would need to be 2 separate declarations and definitions, for example, use int n in the main, and int i in the function
Am I wrong in what I am saying? I have put my comments in green