# Beginners C++ Programming Question?

This topic is 3903 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Ive been teaching myself C++ for about a month now and have come along a example that I have a few questions about. If you guys could give me some good information that would be awesome! Thanks Everyone Here is the code of my example. My questions will be below the code. #include <iostream> #include <math.h> 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)) cout << i << " is prime" << endl; else cout << i << " is not prime" << endl; } return o; } int prime(int n) { for (int i=2; i <= sqrt((double) n); i++) { if (n % i == 0) return false; } return true; } 1. Ive been told that "#include <fstream.h>" no longer has the .h in it. So does this mean that "math.h" or any other with this .h should be without .h too? 2. Why in "while(1)" is 1 entered here? Is there a reason for this or does this mean nothing? 3. The user input "i" from the keyboard in the main function and then it is called to the prime function with "if (prime(i));". Is "i" now "n" in the prime function? This author makes this confusing by using "i" for another variable. Why the hell didnt the author just use "n" and something other then "i" to make it understandable for a beginner like me! He doesnt even explain why he did that! 4. In the prime function there is a "if" statement but no "else" to go with it. How is it supposed to know about "return true;"? Everything before this in the book used "if" and "else" together. Once again the author has no explanation for this action! 5. Im a little confusing about the "return false;" and "return true;" why would it not be like this? int prime(int n) { int true = 1; int false = 0; for (int i=2; i <= sqrt((double) n); i++) { if (n % i == 0) return false; else return true; }

##### Share on other sites
Quote:
 Original post by guzumba1. Ive been told that "#include " no longer has the .h in it. So does this mean that "math.h" or any other with this .h should be without .h too?

fstream is a C++ header, so the correct way to include it is #include <fstream>. math.h is a C header, so the correct way to include it is #include <cmath>.

Quote:
 Original post by guzumba2. Why in "while(1)" is 1 entered here? Is there a reason for this or does this mean nothing?

Here, the author is using the fact that 1 can evaluate to the boolean true, so the loop becomes while(true). So, it will loop infinitely, or until broken out of from within.

Quote:
 Original post by guzumba3. The user input "i" from the keyboard in the main function and then it is called to the prime function with "if (prime(i));". Is "i" now "n" in the prime function? This author makes this confusing by using "i" for another variable. Why the hell didnt the author just use "n" and something other then "i" to make it understandable for a beginner like me! He doesnt even explain why he did that!

n is a copy of i. It is a new int which will have the same value as i when i is passed to the function. The original variable i does not exist in the scope of the new function, so the author is free to reuse it as a variable name.

Quote:
 Original post by guzumba4. In the prime function there is a "if" statement but no "else" to go with it. How is it supposed to know about "return true;"? Everything before this in the book used "if" and "else" together. Once again the author has no explanation for this action!

There is no need for an if to always have an else follow it. As it is written here, if the statement is true, the if block will be entered, and the function will return false. If the is statement is false, then nothing will happen, and the for loop will continue.

Quote:
 Original post by guzumba5. Im a little confusing about the "return false;" and "return true;"why would it not be like this?int prime(int n) {int true = 1;int false = 0; for (int i=2; i <= sqrt((double) n); i++) {if (n % i == 0)return false;else return true;}

You don't necessarily want to return from the prime function if (n % i == 0), because there may be some other value of i by which n is divisible. That's why you don't want to return true until every value of i has been tested.

##### Share on other sites
1. If you're programming in C++ you should use the ones without .h, <math.h> has a c++ equivalent in <cmath>.

2. When the while-loop are testing if it should run the code block or skip it, it evaluates what's between the parentheses. If it evaluates to true it runs the block and skips it if false. The 1 always evaluate to true so that piece of code runs forever, or rather until the break is reached anyway.

3. As the function are set up now you're calling prime() by value, you send a copy of the value i contains to prime which is stored in prime()'s local variable n. So they're the same in the sense that they contain the same value but they're different in the sense that changing n inside prime() doesn't change the value of main()'s i. The author may have intended to show by this that the value of prime()'s i and main()'s i are separate, they're local to their respective function.

4. It's a little confusing if you don't know the details ;) . Formatting and some explanation:
int prime(int n){   for (int i=2; i <= sqrt((double) n); i++)   {      if (n % i == 0)         return false;   }   return true;}

For each time the for-loop runs it checks if the remainder of the division between n and i (the %, modulo) are 0. If it is it's not a prime and returns early (early as in it returns before the for-loop has finished, there's no need to test if more than one number gives the remainder of 0), returning the value false since it has found that the number isn't prime. If it doesn't find a division with the remainder of 0 before i<=sqrt(n) and it exits the for-loop, it returns true since there were no division with the remainder of 0.

5. true and false are reserved keywords in c++, associated to the type bool. The conversion between int and bool is done automatically but I'd rather use: bool prime(int n); .. and later, further down .. bool prime(int n) {
If you're not testing the return value for anything but true or false (like in this case) bool is more logical. (bool can only hold the 'values' true or false.)

##### Share on other sites
Quote:
 1. Ive been told that "#include " no longer has the .h in it. So does this mean that "math.h" or any other with this .h should be without .h too?

Not quite. This is only true for the standard library. "math.h" should be "cmath". You will get used to it :)

Quote:
 2. Why in "while(1)" is 1 entered here? Is there a reason for this or does this mean nothing?

This creates an infinity loop.

In C++, a "0" = false, while a non-zero value represents "true". In the above expression, the expression while(1) results to true, so the loop always executes.

while(1) is similar to while(true) in this way - they both are infinity loops.

Quote:
 3. The user input "i" from the keyboard in the main function and then it is called to the prime function with "if (prime(i));". Is "i" now "n" in the prime function?

Kind of. You have the basic idea, however it is not that "i" is now "a". Instead, "a" simply contains the same value as "i". This is an example of Pass by Value, where you pass a value and a copy of that value is stored in the routines parameter.

Quote:
 This author makes this confusing by using "i" for another variable. Why the hell didnt the author just use "n" and something other then "i" to make it understandable for a beginner like me! He doesnt even explain why he did that!

To be honest, there are other problems with the code besides the above. The author should have put more emphasis on readability - the variables should have more defined names rather then "n" and "i". Perhaps "num"? or even "number"?

Quote:
 4. In the prime function there is a "if" statement but no "else" to go with it. How is it supposed to know about "return true;"?

if does not require else.

Also, the routines' logic is different then what you have written. Here is the same code, with structure and comments:
int prime(int n) {   // begin code block: for loop   for (int i=2; i <= sqrt((double) n); i++) {      // check if number is not prime. If not, return false.      // Note that for a one line expression (like this) we dont      // need to use braces { }      if (n % i == 0)         return false;   } // end code block: for loop   // If we get here, the for loop has completed, return success/true   return true;}

^This example displays how important it is to structure your code, and how it improves readability.

Quote:
 5. Im a little confusing about the "return false;" and "return true;"why would it not be like this?*code snip*

true and false are keywords, similar to int and void. Because of this, a) One is not required to define a variable with their name, and b) It would be illegal syntax if this was possible. That is:
int true;  //errorint false; //error

##### Share on other sites
Quote:
 Original post by guzumbaIve been teaching myself C++ for about a month now and have come along a example that I have a few questions about. If you guys could give me some good information that would be awesome! Thanks EveryoneHere is the code of my example. My questions will be below the code.

Since you have been teaching yourself C++, you should have no difficulty teaching yourself to use the boards properly, particularly with respect to posting code. Here's where to get started. Also, you should recognize that you are a beginner and have beginner questions; so why not post in the "For Beginners" forum which appears at the top of the forum listing?

Quote:
 1. Ive been told that "#include " no longer has the .h in it. So does this mean that "math.h" or any other with this .h should be without .h too?

Headers that were part of the C library have the .h dropped and also a 'c' added at the beginning: thus, <cmath>, <cstring> (contains functions for manipulating "string data", NOT a real string data type; that comes from the new C++ header <string>), <cctype> (notice two c's now). Headers that were part of the original C++ library only have the .h dropped. This includes all the stream libraries, thus <fstream>, <iostream> etc.

Quote:
 2. Why in "while(1)" is 1 entered here? Is there a reason for this or does this mean nothing?

There has to be something to check on each while loop. A while loop runs for as long as the condition is met, i.e. as long as the expression evaluates as true. A number evaluates as true as long as it is not zero. 1 is not zero, so it evaluates as true every time. The loop continues until it is broken out of.

Quote:
 3. The user input "i" from the keyboard in the main function and then it is called to the prime function with "if (prime(i));". Is "i" now "n" in the prime function? This author makes this confusing by using "i" for another variable. Why the hell didnt the author just use "n" and something other then "i" to make it understandable for a beginner like me! He doesnt even explain why he did that!

Experienced programmers tend not to think very much about variable names. In many cases, they don't think enough about them.

However, there is indeed no need - nor generally any reason - for variable names to "match up" in the way you seem to be expecting. A function in code has basically the behaviour of a function in mathematics: it is a mapping from the input values (parameters) to an output (return) value. It doesn't care about where its input comes from or where its output is going to. As such, the caller can use whatever name it likes - or, indeed, no name at all - for the data it provides when it calls the function:

void foo(int i) {  // do something}// somewhere elsefoo(i);foo(x); // doesn't matter that this doesn't match up.// The function receives a copy of 'x', and internally refers to it as 'i'.foo(42); // same thing. 42 is simply a value that is passed to the function.// It doesn't need a name down here; the function will call it 'i' no matter what.

Quote:
 4. In the prime function there is a "if" statement but no "else" to go with it. How is it supposed to know about "return true;"? Everything before this in the book used "if" and "else" together. Once again the author has no explanation for this action!

Suppose I tell you "if you are hungry, then go to the store and buy something." You are not hungry, so you don't go anywhere. Then I say "Please deliver this package for me."

Q. How do you know that I want you to deliver the package?
A. Because you haven't left for the store.

Quote:
 5. Im a little confusing about the "return false;" and "return true;"why would it not be like this?

You mean to say that you're confused about it. Although I would agree that beginners' questions can be confusing at times.

Anyway, the reason it's like that is because the keywords 'false' and 'true' are built into the language. There is a real boolean data type, called 'bool', which the author should be using instead of returning an int. He should also be writing 'while(true)' instead of 'while(1)', because it is obviously clearer and will compile to the same thing.

##### Share on other sites
Please use the [ code][/ code] tags next time

1. Some of the c++ headers don't have the .h extension. math.h is still a standard c header and is perfectly fine to use. #include simply copies a header into your source file. You can look in the 'include' directory of your compiler install to see all of the headers available.

2. 'while(argument)' continues to loop as long as the 'argument' equals true. 1 means true so this loop will never finish, which is known as an infinite loop.

3. You can use the same variable name, but that might cause more confusion:
main(){  int n;  prime(n);}int prime(int n){}

This is perfectly valid code, but n in main() and n in prime() are NOT the same variable, they just have the same name. when prime() is called the value of n in main() is copied to n in prime(). If you have a function that is called by many other functions it can be impractical to use the same variable name throughout. Do a search for 'variable scope' it should explain this.

4. It is perfectly fine to have an if with no else. The function stops when it gets to a return and doesn't go any farther, so 'return true;' is never excuted if 'n % i == 0'

5. 'true' and 'false' are keywords, and the compiler does that for you, which makes code easier to read.

##### Share on other sites
Quote:
 Original post by ZahlmanSince you have been teaching yourself C++, you should have no difficulty teaching yourself to use the boards properly, particularly with respect to posting code. Here's where to get started. Also, you should recognize that you are a beginner and have beginner questions; so why not post in the "For Beginners" forum which appears at the top of the forum listing?

Maybe you need to read the description under that forum and what it says under this forum. You probable would not be saying this.

General Programming
"The place for discussing programming issues not related to games."

For Beginners
"If you're new to game development, plan on spending some time here before visiting the other forums."

I believe it says for "game development". I am not asking questions about game development. I just wanted to let you know since you are such a master of GameDev.Net

1. 1
2. 2
3. 3
Rutin
21
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 10
• 12
• ### Forum Statistics

• Total Topics
632568
• Total Posts
3007119

×