well...As far as I know, we could use any variable or names in the argument list or parameter providing that the data type and the function name are the same, right? However, this code won't work if I replace factor_num with n in the argument_list of the function definition?
This program doesn't work.Code:#include <iostream> int triangle(int); int main() { using namespace std; // Declare a variable as fact_num that represent factorial number int fact_num; // Promt user for input cout << "Please enter a number: "; cin >> fact_num; cout << "Your factorial number is: " << triangle(fact_num) << endl; system("pause"); return 0; } // The function body. That's the function definition int triangle(int n){ int n; int sum = 0; for(n = 1; n <= fact_num; n++) sum += n; return sum; }
But this one with different names for the argument_list in the main() or in the function definition works really well. I am just wondering why. That really baffles me.
Besides, how come the author has to set [b]while (1) {()} before the function call?Code:#include <iostream> #include <cmath> using namespace std; int prime(int n); int main(){ int i; while(1){ cout << "Enter a number (0 to exit)"; cout << "and press ENTER:"; cin >> i; if(i == 0) break; if(prime(i)) // This is what I am talking about, see // the (i) variable in the argument_list cout << i << " is prime" << endl; else cout << i << " is not prime" << endl; } return 0; } int prime(int n){ // See this. the varialbe in the argument_list int i; // is now n, not i. for(i = 2; i <= sqrt(static_cast<double>(n)); i++){ if(n % i == 0) return false; } return true; }



LinkBack URL
About LinkBacks


