Sign in to follow this  

Beginner C++ Programming Question?

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello everyone, I have just started teaching myself C++. I am about 100 pages into my book im reading and have reached a confusing example. The book does not explain it well enough for me so I ask you for your help! Its called "Triangle-Number Function" here is the code that goes with it. #include <iostream> using namespace std; // Function must be declared before being used. int triangle(int num); int main() { int n; cout << "Enter a number and press ENTER: "; cin >> n; cout << "Function returned " << triangle(n); return 0; } // Triangle-number function. // Return 1 + 2 + ... + n int triangle(int n) { int i; int sum = 0; for (i = 1; i <= n; i++) // For i = 1 to n, sum = sum + i; // Add i to sum return sum; } My first questions are about //Function must be declared before being used. "int triangle(int num);" Why is it declaring it before "int main() {" why is it not declaring it right below that along with "int n;". Also why does it say "int triangle(int num)" instead of "int triangle(int n)" like it shows everywhere else in the code. Also what is the need to call out "int n" inside the () if its already called out above like "int n;" My next question is about everything below "return 0; }" Why is everything below this not included in the braces {} above? Or can you include it? Next question is about "int sum = 0;" Why has it not declared sum as a variable before this? Or is this a way to declare a variable and give its value? If it is they havent shown it this way in the book yet! Last question is about "return sum;" I have only used "return 0;" why is this replacing it? Thanks for your Help and Time everyone Andrew

Share this post


Link to post
Share on other sites

Quote:

My first questions are about //Function must be declared before being used. "int triangle(int num);"

Why is it declaring it before "int main() {" why is it not declaring it right below that along with "int n;".


The compiler needs to know about the existence of something before it can be used. We do this through forward declarations.

In your example, main() is calling the routine triangle(). Thus, main is using triangle(). Remember that the compiler needs to know about the routines before being used. ...Because main() is using triangle(), it must be declared before main().

Quote:

Also why does it say "int triangle(int num)" instead of "int triangle(int n)" like it shows everywhere else in the code.

Because it does not matter to the compiler, the parameter name is only for readability. Why did the author do this? You are going to need to ask them ;)

If you wanted, you can omit the name entirely as the compiler only needs to know the data type. That is, all of these represent the same routine. Only the data types are needed for parameters -- the parameter names in declarations are only used for default parameters or for readability purposes. Your book(s) may have more information on default parameters, so I will leave that out.

int triangle(int);
int triangle(int n);
int triangle(int num);

The above are the same.

Quote:

Also why does it call it like this too? "int triangle(int n) {"
Its already called "n" out above like
"int n;"


A Code Block is the lines between { and }. The varable "n" defined in main() is local to main(). In other words - they are different.

The parameter "n" defined in the function is local to that function.

Take a look at code blocks, Local and Global variables. Your book(s) should have something about them...

Quote:

My next question is about everything below "return 0; }"

Why is everything below this not included in the braces {} above? Or can you include it?

return is used to return from a routine, not to end a program. Routines can be places anywhere within your source.

In your code, the return 0; in main() returns back to the C++ runtime library code that called main(). This usually terminates the program, and returns back to the OS.

Quote:

Third question is about "int sum = 0;"

Why has it not declared sum as a variable before this? Or is this a way to declare a variable and give its value? If it is they havent shown it this way in the book yet!

^Bingo - The bolded text is correct. This is Initialization.

It is important to understand the difference between initialization and assignment.

Initialization is assigning a value to a variable as soon as it is created (as in your above code.)

Assignment is defining (creating) the variable, and giving it a value later on.

Hope this helps!

Share this post


Link to post
Share on other sites
Note: I'm posting this because I already had it typed, but delayed posting because I was looking at the tube. Stupid tv...

Quote:
Why is it declaring it before "int main() {" why is it not declaring it right below that along with "int n;".
Perfectly valid to declare within the main. However, it's idiomatic to avoid declaring a function within another function. This example is very simple. In large blocks of code, you have one function used by ten other functions. Are you going to repeat your declaration for each function? No. Rather, you'll leave the declaration at the top, visible to all functions.

Quote:
Also why does it say "int triangle(int num)" instead of "int triangle(int n)" like it shows everywhere else in the code.
Technically, you don't even need the name of the variable in the declaration. It's typical (and good form) to indicate variable names, especially when it isn't obvious what the function does. Let me show you an example of what I mean.

int addTwoNumbers(int, int);
int addTwoNumbers(int firstNum, int secNum);

You can probably guess what addTwoNumbers does, so giving the arguments names doesn't really inform you of much. However,

hndle getContent(hndle);
hndle getContent(hndle windowHandle);

As you start working with more and more complex code, proper naming takes on a peculiar importance. You ideally want code to be very readable and understandable intrinsically.
Oh, and the name in the declaration doesn't actually have to match the name in the definition, if you do choose to put a name in the declaration.

Quote:
Also what is the need to call out "int n" inside the () if its already called out above like
"int n;"
Make sure you understand scoping properly. The int n in main only exists in main. The int n in triangle is completely different from the int in main. They share the same variable name. And uh, that's about it. That is the int n in main only exists within the scope of main. And the same applies for the int in triangle. And both scopes are separate. triangle doesn't know about main. And main doesn't know about triangle.
Actually it does. You declared the function triangle. So main knows about triangle now.

Quote:
Why is everything below this not included in the braces {} above? Or can you include it?
Because they are demonstrating functions. You could have just written all the code in triangle within main.
Are you asking if you could have dumped the definition of triangle within main? No. I don't think so anyway. It definitely isn't idiomatic, and serves little purpose anyway. Actually, that's not a good thing to say, because of things like lambda functions which matter, but I don't want to bring you into a pedantic discussion. So to simplify, no.

Quote:
Why has it not declared sum as a variable before this? Or is this a way to declare a variable and give its value? If it is they havent shown it this way in the book yet!
Yes, it's called initializing a variable. When you define a variable, you can give it a starting value as well. To understand why one might do this, I'll give you an example:

int i;
i += 5;

I have added 5 to i. What is the value of 5? The answer is no one knows. That's because you don't know what the starting value of i is. i has a place in memory, and that memory can contain whatever garbage. You haven't set an initial value of i, so you don't know what garbage i has.

If your code ever depends on a variable having a starting value, make sure you set it to a starting value.

Quote:
Last question is about "return sum;" I have only used "return 0;" why is this replacing it?
Ok, so let me ask you this. Why did you have return 0? Well, if you look at main. main is a special function. But it is defined to have a return value of int. So main must return something. Technically, the return value is useful because if you were running programs on the commandline, you get an error value of sorts from the program. In reality, as a beginner, you will never ever care about the return value of main, and simply write "return 0;" as the safe response.

Think of a function as a big box with two ports. -- [ ] -- Something goes in. Something comes out. What goes in are the function arguments. What comes out is a single "answer". In a function that adds two numbers, you would have two numbers going in and a single number coming out. This is the basic idea of a function. Creating these "boxes" that take in something, and after some various manipulations spit out an answer.

Share this post


Link to post
Share on other sites
EDIT: Functions are incredibly easy to pick up on, so don't be discouraged. The following may be very confusing because I'm finding it hard to explain. It really is an easy concept, though.

EDIT II: Well, typing some and then taking a break resulted in others posting similar things to this...Hopefully some of it makes sense for you. Crypter did a good job of bolding keywords for you to make sure you understand.

Quote:
Why is it declaring it before "int main() {" why is it not declaring it right below that along with "int n;".

int triangle(int num);
is declaring a new function called triangle which returns an integer, as declared by the "int" part before triangle. You know this is a function because it is followed by
(int num)
which means that it accepts an integer which it will refer to as "num".

Quote:
Also why does it say "int triangle(int num)" instead of "int triangle(int n)" like it shows everywhere else in the code.

That's an interesting question. Really it should say "int triangle(int num)" down after "//triangle number function", and not "int triangle(int n)". (Or you could change it at the top. Either way, these two should probably agree.)

Quote:
Also what is the need to call out "int n" inside the () if its already called out above like
"int n;"

As I mentioned above, the code "int triangle(int num)" declares a function. For more info on functions, google them or re-read the section in the book. The first "int" indicates that the function will return an integer. "triangle" is the name of the function. The "(int num)" part means that when you call the function you will need to pass an integer to it, which is referred to throughout the function as "num". The reason it isn't the same as "int n;" is because "int n;" is creating a variable of type integer called "n". You just need to distinguish between variables and functions.

Quote:
Why is everything below this not included in the braces {} above? Or can you include it?

That stuff is a different function. "main(){" begins the definition of the function called main, which is the function that the program's code should go in. That "}" after "return 0" ends the main function. Then you find the definition for the "triangle" function. Again, make sure you understand what a function is...just google it and you will find much information. What this part does is tell the program what to do when the triangle function is called in the main function. Here's an example.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a number and press ENTER: ";
cin >> n;

int i;
int sum = 0;
for (i = 1; i <= n; i++) // For i = 1 to n,
{
sum = sum + i; // Add i to sum
}

cout << "Function returned " << sum;
return 0;
}




Do you understand what that did? Well, it does the same thing as your other program. The problem is that it's main function is longer. What you've done in the other program is taken that code from "int i; to the part about "sum" and put it in a function called triangle. That way it is executed through a simple line "triangle(n);", which is defined after main to keep it more organized and sort of out of the way. Plus, if you wanted to execute that code block twice, you could just add another line "triangle(n);" instead of typing those multiple lines over.

Quote:
Next question is about "int sum = 0;"

Why has it not declared sum as a variable before this? Or is this a way to declare a variable and give its value? If it is they havent shown it this way in the book yet!

Last question is about "return sum;" I have only used "return 0;" why is this replacing it?

Sum has not been declared before because you haven't needed it before. You are correct that that one statement "int sum = 0;" both declares sum and sets it value to 0, all in one line. "return sum" means that the variable sum will be returned to the place where you called the triangle function (since it is at the end of the triangle function). Here's an easy example:

#include <iostream>
using namespace std;

int number(int x);

int main()
{
int n = 5;
cout << "the number is " << number(n);
return 0;
}
int number(int x)
{
return x;
}




The output of the code is "the number is 5".
Here's a walkthrough of that code. I have the usual #include and stuff at the top. Then I define the main() function. I create an integer called n and set it equal to 5. Then I cout a sentence, followed by a call to my number() function which is defined after main. At this point the program "jumps" to that portion of the code. This function accepts an integer referred to as "x". When I call it I pass it an integer, n, which could then be considered "x". The function returns "x", meaning that the value of x is put in the place of "number(n)" in main() when I call the number function. What the computer really sees is something like "cout << "the number is " << 5;

That's a pretty rough read, but its really hard for me to explain it without referring to more advanced topics....Its like when the only way to define a word is by using the word itself. Just re-read the chapter in the book, and google for "C++ functions tutorial" and you ought to find something clearer than what I've written. If you actually followed what I wrote, congratulations. Feel free to ask questions.

Share this post


Link to post
Share on other sites
Thank you everyone for your replys they have been really helpful. I do have some more questions though about another example I saw online. I think I know some of the answers but I want to make sure once again. Thanks again everyone!

Here is it! My questions will be inside these (((( )))) so dont mistake these for anything else please.


// Main.cpp

#include <fstream.h>
((((What is this used for? I know #include <iostream> is for cout and cin.))))

int Add(int,int); //function prototype
((((So nothing has to be inside of the () it could be blank if I wanted?))))

int a,b,c;
(((( Are these being called out here so that they can be used in any of the braces {} without having to type int a,b,c; everytime? And if this is true are you able to do this and give it a value at the same time, like "int a = 1;? So u wouldnt have to give it a value everytime also? Im sure this would not be a good thing because the value will probably change every time. But I would like to know in case it would be handy!))))

int main()
{
a=2;
b=3;
c=Add(a,b); //function call
((((Why would this not say "c=Add(a+b);" Or is this another one that could be blank?))))

cout << c << endl;
(((( Did he forget to put "#include <iostream>" at the top? I was under the impression you couldnt use "cout" and "cin" without this?))))

return 0;
}

int Add(int a, int b) //function definition
((((Once again it can be blank inside the () right? This is for clarity only?))))

{
c=a+b;
return c;
}




I have two other question too?

Do you always have to put "system("pause");" in the code for the "Command Prompt" window not to close immediately?

Do you have to call out "int Add(int,int); at the top of the program or before the "int main()" or can you put this anywhere in the code as long as its outside of the braces {}?




Here is the code again if this is confusing. It doesnt have my questions in it.


// Main.cpp

#include <fstream.h>

int Add(int,int); //function prototype

int a,b,c;

int main()
{
a=2;
b=3;
c=Add(a,b); //function call
cout << c << endl;
return 0;
}

int Add(int a, int b) //function definition
{
c=a+b;
return c;
}



Thanks Andrew

Share this post


Link to post
Share on other sites
Quote:

Here is it! My questions will be inside these (((( )))) so dont mistake these for anything else please.


If you like, you can use code tags ( [ code ]*code here*[/ code ] ) or [ source ]*code here*[/ source ]-without spaces to create nice looking code blocks to make everything easier to read. Please read the GDNet FAQ for more information.

I put your code in code tags to improve readability for everyone:


// Main.cpp

#include <fstream.h>

((((What is this used for? I know #include <iostream>
is for cout and cin.))))

This should actually be #include <fstream> NOT #include <fstream.h>. fstream.h is the older header file that should not be used anymore.

fstream is for file operation streams. It provides an interface for operating, reading and writing files, and other file operations.


int Add(int,int); //function prototype
((((So nothing has to be inside of the () it could be blank if I
wanted?))))


Yep. You can also use Add (void) to specify that the routine does not take any parameters.


int a,b,c;
(((( Are these being called out here so that they can be used in any of the
braces {} without having to type int a,b,c; everytime? And if this is true are
you able to do this and give it a value at the same time, like "int a = 1;? So
u wouldnt have to give it a value everytime also? Im sure this would not be a
good thing because the value will probably change every time. But I would like
to know in case it would be handy!))))


All this does is define the existence of a global variable, and its initil value, if any. They allows you to reference the variables by name.

int a = 1; will work fine, and is actually the preferred over simply int a; as it will contain a known value. Remember that this is initialization, and C++ never clears anything for you. In other words, the data in this variable contains garbage data. This is very important to know when you get to pointers.

After defining the variable, remember that you can reference it by name. Because it is global, it can be used throughout anywhere in the source file.

For an example of everything...


int a = 0; // define the variable, and initialize it to 0

void function () {

a = 1; // access the variable by its name
}


Next up...


int main()
{
a=2;
b=3;
c=Add(a,b); //function call
((((Why would this not say "c=Add(a+b);" Or is this another one that could be
blank?))))


No no no. In the above, Add() is being executed from main(). You have defined and declared Add() like this:

int Add(int,int); //function prototype

This says that Add() takes 2 parameters of type int that Add() requires. How do we pass these parameters to this function? By calling it with the paramerters to pass. This is what the above is doing.

It is passing the value of the variables 'a' and 'b' as the parameters to pass to the routine Add(), and calls Add() with those parameters.


cout << c << endl;
(((( Did he forget to put "#include <iostream>" at the top? I was under
the impression you couldnt use "cout" and "cin" without this?))))

...Not entirely true.

Header files can include other header files. If <fstream> #includes <iostream>, then you can use <iostream> objects and types. That is, you can access cout and cin.


return 0;
}

int Add(int a, int b) //function definition
((((Once again it can be blank inside the () right? This is for clarity only?))))

No no no no. Only if the routine Add() is declared with no parameters in the parameter list. That is, if you have an Add() routine defined like this:

void Add () {

}

Then you can call it with an empty parameter list (nothing inside the () ).

Disclaimer: The above disregards routines with default parameters. Dont worry much about these yet though until later.


{
c=a+b;
return c;
}


Quote:

I have two other question too?

Do you always have to put "system("pause");" in the code for the "Command Prompt" window not to close immediately?


Using system() is not recommended as its parameter is system specific. It is better practice to use cin.get() (or similar), or simply running your program from the command prompt.

In either case, I recommend not worrying about this yet - focus on the basics of the language first.

Quote:

Do you have to call out "int Add(int,int); at the top of the program or before the "int main()" or can you put this anywhere in the code as long as its outside of the braces {}?

It must be before the routine is used. No more.

If the routine is defined before being used (For example, if you move your Add() routine above main() ) then you can completely omit that line out.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this