A function is a sequence of statements designed to do a particular job. You already know that every program must have a function named main(). However, most programs have many functions, and they all work analogously to main.
Often, your program needs to interrupt what it is doing to temporarily do something else. You do this in real life all the time. For example, you might be reading a book when you remember you need to make a phone call. You put a bookmark in your book, make the phone call, and when you are done with the phone call, you return to your book where you left off.
C++ programs work the same way. A program will be executing statements sequentially inside one function when it encounters a function call. A function call is an expression that tells the CPU to interrupt the current function and execute another function. The CPU “puts a bookmark” at the current point of execution, and then calls (executes) the function named in the function call. When the called function terminates, the CPU goes back to the point it bookmarked, and resumes execution.
Here is a sample program that shows how new functions are declared and called:
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
// Declaration of function DoPrint()
void DoPrint()
{
using namespace std; // we need this in each function that uses cout and endl
cout << "In DoPrint()" << endl;
}
// Declaration of main()
int main()
{
using namespace std; // we need this in each function that uses cout and endl
cout << "Starting main()" << endl;
DoPrint(); // This is a function call to DoPrint()
cout << "Ending main()" << endl;
return 0;
}
This program produces the following output:
Starting main() In DoPrint() Ending main()
This program begins execution at the top of main(), and the first line to be executed prints Starting main(). The second line in main is a function call to DoPrint. At this point, execution of statements in main() is suspended, and the CPU jumps to DoPrint(). The first (and only) line in DoPrint prints In DoPrint(). When DoPrint() terminates, the caller (main()) resumes execution where it left off. Consequently, the next statment executed in main prints Ending main().
Functions can be called multiple times:
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
// Declaration of function DoPrint()
void DoPrint()
{
using namespace std;
cout << "In DoPrint()" << endl;
}
// Declaration of main()
int main()
{
using namespace std;
cout << "Starting main()" << endl;
DoPrint(); // This is a function call to DoPrint()
DoPrint(); // This is a function call to DoPrint()
DoPrint(); // This is a function call to DoPrint()
cout << "Ending main()" << endl;
return 0;
}
This program produces the following output:
Starting main() In DoPrint() In DoPrint() In DoPrint() Ending main()
In this case, main() is interrupted 3 times, once for each call to DoPrint().
Main isn’t the only function that can call other functions. In the following example, DoPrint() calls a second function, DoPrint2().
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
void DoPrint2()
{
using namespace std;
cout << "In DoPrint2()" << endl;
}
// Declaration of function DoPrint()
void DoPrint()
{
using namespace std;
cout << "Starting DoPrint()" << endl;
DoPrint2(); // This is a function call to DoPrint2()
DoPrint2(); // This is a function call to DoPrint2()
cout << "Ending DoPrint()" << endl;
}
// Declaration of main()
int main()
{
using namespace std;
cout << "Starting main()" << endl;
DoPrint(); // This is a function call to DoPrint()
cout << "Ending main()" << endl;
return 0;
}
This program produces the following output:
Starting main() Starting DoPrint() In DoPrint2() In DoPrint2() Ending DoPrint() Ending main()
Return values
If you remember, when main finishes executing, it returns a value back to the operating system (the caller) by using a return statement. Functions you write can return a single value to their caller as well. We do this by changing the return type of the function in the function’s declaration. A return type of void means the function does not return a value. A return type of int means the function returns an integer value to the caller.
// void means the function does not return a value to the caller
void ReturnNothing()
{
// This function does not return a value
}
// int means the function returns an integer value to the caller
int Return5()
{
return 5;
}
Let’s use these functions in a program:
cout << Return5(); // prints 5 cout << Return5() + 2; // prints 7 cout << ReturnNothing(); // This will not compile
In the first statement, Return5() is executed. The function returns the value of 5 back to the caller, which passes that value to cout.
In the second statement, Return5() is executed and returns the value of 5 back to the caller. The expression 5 + 2 is then evaluated to 7. The value of 7 is passed to cout.
In the third statement, ReturnNothing() returns void. It is not valid to pass void to cout, and the compiler will give you an error when you try to compile this line.
One commonly asked question is, “Can my function return multiple values using a return statement?”. The answer is no. Functions can only return a single value using a return statement. However, there are ways to work around the issue, which we will discuss when we get into the in-depth section on functions.
Returning to main
You now have the conceptual tools to understand how the main() function actually works. When the program is executed, the operating system makes a function call to main(). Execution then jumps to the top of main. The statements in main are executed sequentially. Finally, main returns a integer value (usually 0) back to the operating system. This is why main is declared as int main().
Some compilers will let you get away with declaring main as void main(). Technically this is illegal. When these compilers see void main(), they interpret it as:
int main()
{
// your code here
return 0;
}
You should always declare main as returning an int and your main function should return 0 (or another integer if there was an error).
Parameters
In the return values subsection, you learned that a function can return a value back to the caller. Parameters are used to allow the caller to pass information to a function! This allows functions to be written to perform generic tasks without having to worry about the specific values used, and leaves the exact values of the variables up to the caller.
This is a case that is best learned by example. Here is an example of a very simple function that adds two numbers together and returns the result to the caller.
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
// add takes two integers as parameters, and returns the result of their sum
// add does not care what the exact values of x and y are
int add(int x, int y)
{
return x + y;
}
int main()
{
using namespace std;
// It is the caller of add() that decides the exact values of x and y
cout << add(4, 5) << endl; // x=4 and y=5 are the parameters
return 0;
}
When function add() is called, x is assigned the value 4, and y is assigned the value 5. The function evaluates x + y, which is the value 9, and then returns this value to the caller. This value of 9 is then sent to cout to be printed on the screen.
Output:
9
Let’s take a look at a couple of other calls to functions():
//#include <stdafx.h> // Visual Studio users need to uncomment this line
#include <iostream>
int add(int x, int y)
{
return x + y;
}
int multiply(int z, int w)
{
return z * w;
}
int main()
{
using namespace std;
cout << add(4, 5) << endl; // evalutes 4 + 5
cout << add(3, 6) << endl; // evalues 3 + 6
cout << add(1, 8) << endl; // evalues 1 + 8
int a = 3;
int b = 5;
cout << add(a, b) << endl; // evaluates 3 + 5
cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)
cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)
return 0;
}
This program produces the output:
9 9 9 8 7 6
The first three statements are straightforward.
The fourth is relatively easy as well:
int a = 3;
int b = 5;
cout << add(a, b) << endl; // evaluates 3 + 5
In this case, add() is called where x = a and y = b. Since a = 3 and b = 5, add(a, b) = add(3, 5), which resolves to 8.
Let’s take a look at the first tricky statement in the bunch:
cout << add(1, multiply(2, 3)) << endl; // evalues 1 + (2 * 3)
When the CPU tries to call function add(), it assigns x = 1, and y = multiply(2, 3). y is not an integer, it is a function call that needs to be resolved. So before the CPU calls add(), it calls multiply() where z = 2 and w = 3. multiply(2, 3) produces the value of 6, which is assigned to add()’s parameter y. Since x = 1 and y = 6, add(1, 6) is called, which evaluates to 7. The value of 7 is passed to cout.
Or, less verbosely (where the => symbol is used to represent evaluation):
add(1, multiply(2, 3)) => add(1, 6) => 7
The following statement looks tricky because one of the parameters given to add() is another call to add().
cout << add(1, add(2, 3)) << endl; // evalues 1 + (2 + 3)
But this case works exactly the same as the above case where one of the parameters is a call to multiply().
Before the CPU can evaluate the outer call to add(), it must evaluate the inner call to add(2, 3). add(2, 3) evaluates to 5. Now it can evaluate add(1, 5), which evaluates to the value 6. cout is passed the value 6.
Less verbosely:
add(1, add(2, 3)) => add(1, 5) => 6
Effectively using functions
One of the biggest challenges new programmers encounter (besides learning the language) is learning when and how to use functions effectively. Functions offer a great way to break your program up into manageable and reusable parts, which can then be easily connected together to perform a larger and more complex task. By breaking your program into smaller parts, the overall complexity of the program is reduced, which makes the program both easier to write and to modify.
Typically, when learning C++, you will write a lot of programs that involve 3 subtasks:
- Reading inputs from the user
- Calculating a value from the inputs
- Printing the calculated value
For simple programs, reading inputs from the user can generally be done in main(). However, step #2 is a great candidate for a function. This function should take the user inputs as a parameter, and return the calculated value. The calculated value can then be printed (either directly in main(), or by another function if the calculated value is complex or has special printing requirements).
A good rule of thumb is that each function should perform one (and only one) task. New programmers often write functions that combine steps 2 and 3 together. However, because calculating a value and printing it are two different tasks, this violates the one and only one task guideline. Ideally, a function that calculates a value should return the value to the caller and let the caller decide what to do with the calculated value.
Quiz
1) What’s wrong with this program fragment?
void multiply(int x, int y)
{
return x * y;
}
int main()
{
cout << multiply(4, 5) << endl;
return 0;
}
2) What’s wrong with this program fragment?
int multiply(int x, int y)
{
int product = x * y;
}
int main()
{
cout << multiply(4, 5) << endl;
return 0;
}
3) What value does the following program fragment print?
int add(int x, int y, int z)
{
return x + y + z;
}
int multiply(int x, int y)
{
return x * y;
}
int main()
{
cout << multiply(add(1, 2, 3), 4) << endl;
return 0;
}
4) Write a function called doubleNumber() that takes one integer parameter and returns double it’s value.
5) Write a complete program that reads an integer from the user (using cin, discussed in section 1.3), doubles it using the doubleNumber() function you wrote for question 4, and then prints the doubled value out to the console.
Quiz Answers
To see these answers, select the area below with your mouse.
1.5 — A first look at operators
|
Index
|
1.3 — A first look at variables (and cin)
|
1.5 — A first look at operators
Index
1.3 — A first look at variables (and cin)
Hi Alex,
Contrary to your solution to quiz 2, it does compile on my system and prints the correct result. I am using Dev-C++ 4.9.9.2., Did I misunderstand your solution or is there another explanation? The program code follows:
#include int multiply(int x, int y) { int product = x * y; } int main() { using namespace std; multiply(4, 5) << "nn"; << "Double PRESS any KEY to EXIT"; cin.clear(); cin.ignore(255, 'n'); cin.get(); }Thanks Alex!
I compiled my first little program for Quiz Question 5 and it was great: worked like a charm and basically matched your solutions!
But then I showed it off to my girlfriend… She entered an unfathomable positive number in the console (to be doubled), but the result came back negative.
What’s going on to cause this? When I use integers of a smaller magnitude everything seems to work perfectly.
Just curious. –Joe
I may be wrong on this, but I think this is because of “rollover.” in other words, there is a maximum value that can be stored as an integer, and as I read somewhere else, when you perform an operation on a positive integer that makes it larger than the max, it rolls the number over to the smallest number (kinda like an odometer). In the case of integers, its a negative number.
I first learned MATLAB programming, and when you went overboard there, it just returned “inf” for infinity. At least with that I could understand what had happened lol.
Hmm i hope this helps. When you type int variableName; it creates a reference in RAM for variableName and occupies a specific number of bytes for int types.Either you initialize the variable or not, the number of bytes occupied by the variable are specific for ALL variables of a specific type.Now There are types of int … e.g. unsigned short int and signed short int both take same bytes in RAM which means they can hold up to a specific maximum of different numbers.
Unsigned short int range = numbers from -32768 to 32767. Total numbers stored = 32767-(-32768)= 65536 numbers
Signed short int range = numbers from 0 to 65535. Total numbers stored = 65535 plus one which would be the number zero = 65536 numbers total…
So when u type int the compiler automatically sets it to signed int…
What happens then when u make mathematical equations that exceed the limits ?
The extra digits of the calculations are overflowing so they never get saved… which results in the following for signed short int…
Let’s say we have a result of 32768…= 32767+1 so it restarts at -32768.
Further Explanation with binary system…
number 15 = 1×8 1×4 1×2 1×1 = 1111 in binary digits
number 16 = 1×16 0×8 0×4 0×2 0×1 =10000 in binary digits
Imagine now that u can only keep 4 binary digits(ammount of memmory space a variable of specific type takes) …
So 10000 that has 5 digits looses the first digit and is saved as 0000. Number 0 in decimal
4 binary digits means numbers from 0 to 15 (16 total numbers) That way if u try to store a larger number the counter will start anew as explained above…
Sorry if my explanation is not very good . English is not my native language but i really hope u understand how it goes…
i understand thiss all so far but how do i write a program that i can use on a computer without an ide?
Very well explained thanks for these tutorials:) Here is my first program using functions.
#include <iostream> void GotoPoint()//Creates a function called GotoPoint which returns nothing, hence "void". { using namespace std;//Needed for cout and endl. cout << "In GotoPoint()..." << endl;//Prints message to screen, ends line. } int main()//main function needed in every program. { using namespace std;//Needed for cout and endl. cout << "In main()..." << endl;//Prints message to screen, ends line. GotoPoint();//Calls the function GotoPoint(). cout << "Back in main()..." << endl;//Prints message to screen, ends line. cout << "Ending main()..." << endl;//Prints message to screen, ends line. cout << "Press Enter to close program. ";//Prints message to screen. cin.get();//Stops program from closing. return 0; }remember the quiz on the last page, if we [programmers] write an equation 4 a computer to solve how can we make the computer solve the sum asked by the user?
does cout mean ecout like in French
I really hadn’t thought of that. Nice.
Unfortunately Mr. Stroustrup (our beloved c++ father :) ) is not as romantic. cout is simply (c)haracter (out)put
Why doesn’t this work?
#include <iostream> int doubleNumber(int x, int y) { int product = x * y; } int main() { using namespace std; cout << "Enter a number." << endl; int z; cin >> z; cout << doubleNumber(z * 2) << endl; }you used two parameters in doubleNumber function definition, but during function call only one parameter..number of parameters must be same.
and also doubleNumber must return a value.
if you are using Visual Basic then you need the #include “stdafx.h” thing at the beginning. Other wise I don’t know
There are 2 problems in the code.
1) You did not return anything in doubleNumber fucntion
2) last line in the main() function, you did not pass the values properly
Here is the correction
#include <iostream> int doubleNumber(int x, int y) { //you wrote "int product = x * y; return x * y; } int main() { using namespace std; cout << "Enter a number." << endl; int z; cin >> z; //You wrote "cout << doubleNumber(z * 2)" //The z * 2 was causing problems, because by doing what you did, you only passed one argument to the function cout << doubleNumber(z , 2) << endl; }Hello Karan.
showx() is not a good candidate for a function being redundant (and bad as a technique).
Regarding your comments I’d say they are pretty much wrong. More specifically
we know what cout does so no need to comment it
again your variable declaration is obvious so no need to comment it
we know what cin does.
same as above
These comments could make it :) although they’d be better suited to a bigger and more complex program that has a lot of functions.
One other thing is that you probably should have also commented at the beginning of your doubleNumber function, explaining what does it do.
i have tried the following example in the tutorial but it just doesn’t work., What have missed?
//#include <stdafx.h> // Visual Studio users need to uncomment this line #include <iostream> #include <stdafx.h> void DoPrint() { using namespace std; cout << "In DoPrint()" << endl; } int main() { using namespace std; cout << "Starting main()" << endl; DoPrint(); cout << "Ending main()" << endl; return 0; }The code is alright, so it must be something with your IDE
If you are NOT using Visual Studio, remember to remove stdafx
First of all kudos for the great site you have.
I had a little problem with exercise 5. My solution was this:
#include <iostream> using namespace std; int doubleNumber (int x) { x = x * 2; return x; } int main() { int x = 0; cout << "Please enter a number: "; cin >> x; cout << endl; doubleNumber(x); cout << "The result is " << x; return 0; }The problem is that the value is not doubling. Doing a debug, I saw that the function was called correctly, x was calculated as it should inside the function, but never returned to main. Doing a x=myFunction(x) resolves it, but I don’t understand why? If I’m simply using a myFunction(x) isn’t x supposed to get the new value calculated inside the function?
Try using x=doubleNumber(x); instead of doubleNumber(x);
or
Remove doubleNumber(x); and correct the following to:
cout << "The result is " << doubleNumber(x);
The reason this happens would be if i am not mistaken that x variable in doubleNumber function is active only while in the function itself so when the control returns to main the x in main being a different variable has the set value of what u ve inserted with cin.
Note that the returned value of ur doubleNumber function is not saved anywhere thus is not accessible…
So the solution is either assign the returned value to x in main function or ask from cout to execute the doubleNumber function and print the returned value right away…
Hope i helped… :)
Hay i am having a problem as whenever i run my console window closes, its annoying me as it is preventing me from learning.
Well, I’m new to this whole programming thing as I started yesterday, but as far as I can read, you’re using
or
and as I see it, it should be
I hope I was right :)
try
#include
without .h extension.That should fix ur problem :)
I am trying to learn C++. I just started today, so please don’t say that I suck. I am trying to make a calculator that adds, divides, subtracts and multiplies. Please help me! Any help would be great. the is the code:
// FullCalculator.cpp : Defines the entry point for the console application. // #include <stdafx.h> #include <iostream> int main() { using namespace std; int x; cout << "press 1 for add, 2 for subtract, 3 for multiply, and 4 for divide" << endl; cin >> x; if (x == 1) { add(); } else { notadd(); } } int notadd() { if (x == 2) { subtract(); } else { notsubtract(); } } int notsubtract() { if (x == 3) { multiply(); } else { notmultiply(); } } int notmultiply() { if (x == 4) { divide(); } } int add() { using namespace std; int a = 0; //makes x an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> a; // saves entered number as x int b = 0; //makes y an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> b; // saves entered number as y int c = x + y; // makes c = a + b cout << a << " plus " << b << " equals " << c << endl; // diaplays x plus y = z } int subtract() { using namespace std; int d = 0; //makes d an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> d; // saves entered number as d int e = 0; //makes e an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> e; // saves entered number as e int f = d - e; // makes f = d - e cout << d << " minus " << e << " equals " << f << endl; // diaplays x plus y = z } int multiply() { using namespace std; int g = 0; //makes g an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> g; // saves entered number as g int h = 0; //makes h an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> h; // saves entered number as h int i = g * h; // makes z = x * y cout << g << " times " << h << " equals " << i << endl; // diaplays x plus y = z } int divide() { using namespace std; int j = 0; //makes j an vaiable cout << "enter first number" << endl; // diaplays "enter first number" on screen cin >> j; // saves entered number as j int k = 0; //makes k an vaiable cout << "enter second number" << endl; // diaplays "enter second number" on screen cin >> k; // saves entered number as k int l = j / k; // makes l = j / k cout << j << " divided by " << k << " equals " << l << endl; // diaplays x plus y = z }Here are the errors:
error C3861: ‘add’: identifier not found
error C3861: ‘notadd’: identifier not found
error C2065: ‘x’ : undeclared identifier
: error C3861: ‘subtract’: identifier not found
: error C3861: ‘notsubtract’: identifier not found
error C2065: ‘x’ : undeclared identifier
error C3861: ‘multiply’: identifier not found
error C3861: ‘notmultiply’: identifier not found
error C2065: ‘x’ : undeclared identifier
error C3861: ‘divide’: identifier not found
I think the: ‘x’ : undeclared identifier
is happening because the x variable ammount is not being carried over tho the other functions. how would I do this?
BTW, this is a great site. I don’t get the return stuff either.
hi salam nhn calculator main bohat error hn aur coding ho to do plz
I see a few mistakes other than the way u have designed ur program . So i ll first try to correct what mistakes i see in ur program first and then give an alternative idea on how to implement this.
error C3861: ‘add’: identifier not found
Happens cause main requests add() function to be used but it hasn’t been declared and u haven’t used a prototype either before calling it.
error C3861: ‘notadd’: identifier not found
same reason as above…
The reason u get error C3861: ‘xxxx’: identifier not found is the same as the previous ones
error C2065: ‘x’ : undeclared identifier
int add()
{
using namespace std;
int a = 0; //makes x an vaiable
cout << "enter first number" <> a; // saves entered number as x
int b = 0; //makes y an vaiable
cout << "enter second number" <> b; // saves entered number as y
int c = x + y; // makes c = a + b
cout << a << " plus " << b << " equals " << c << endl; // diaplays x plus y = z
}
take this piece of code and note the line
int c = x + y; // makes c = a + b
Then check again the add() function and u ll see u haven't declared x anywhere … If u want x to be transfered from main to add or any other function make sure when u declare add() function that it has a variable requirement for example add(int x) though i can't understand what purpose would that serve in ur programm transfering the operator variable and calculating … it's like adding potatoes and baloons … they have nothing in common and serve no purpose :P
the line should have been int c= a + b;
error C3861: ‘subtract’: identifier not found
Again it happens cause main requests add() function to be used but it hasn't been declared and u haven't used a prototype either before calling it.
error C3861: ‘notsubtract’: identifier not found
Again it happens cause main requests add() function to be used but it hasn't been declared and u haven't used a prototype either before calling it.
error C2065: ‘x’ : undeclared identifier
int notadd()
{
if (x == 2)
{
subtract();
}
else
{
notsubtract();
}
}
This is a separate function the way u have declared it. So where exactly do u see the variable x declared in it?
Variables are accessible only in the function that u have declared them. Thus u can have many functions with same variable names. but no i don't recommend the later :P Try to use variable names that have meaning to you.
same happens with all the error C2065: ‘x’ : undeclared identifier errors…
Now i noticed another mistake …
You have declared your functions as int name() but in the whole function i don't see a return value on any of them . Since they print out the result themselves and u don't need the result for further calculations u can declare em as void instead of int … or add return resultVariable; on each one of em and store it in one variable in main so u can work further on that result…
To debug such things try to find the logical sequence that the commands are going to be executed
Now an alternative version of ur program
why don't u just take all three numbers at the beggining (operator value), first number and second number?
then u get to use em in the better declared functions like imagine x = operator variable , y = first number inserted , z = second number inserted so
when u call the function would look more like
add(y,z);
and when declaring it like
int add (int y, int z)
{
return y+z;
}
and subtract, multiply, divide in a similar manner
also consider instead of calling functions for no reason something in main like …
int result=0;
char operator;
if (x==1)
{
result=add(y,z);
operator='added to';
}
else if (x==2)
{
result=subtract(y,z);
operator='subtracted from';
}
else if (x==3)
{
result=multiply(y,z);
operator='multiplied with';
}
else if (x==4)
{
result=divide(y,z);
}
else
{
cout << "This is not a valid choice…";
}
then add something like
cout << y <<"\t" << operator <<"\t" << z <<"equals to: " << result << ".\n"
Piece it together and make ur programm . hope I helped :)
Hmm heh i failed i used as variable name ”operator” which is an invalid word to begin with… also u can’t save words like that…
im writeing down for example “In DoPrint” bewten the cout and endl but i get red letters insteed of blue ones?? why?? im using visual c++ 2010
i have done everything right
Red letters are correct.
Do you always have to put all your functions above the main function?
Doublepost, sorry
Disregard the above post(s), the 1.7 tutorial explained it.
// 1.4 (4).cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int doubleNumber(int x) { return 2 * x; } int main() { cout << "Input a number to be doubled:" << endl; int x; cin >> x; cout << "The number: " << x << " has been entered" << endl; cout << "Your number has been doubled to: " << doubleNumber(x) << endl; return 0; }The program works fine when I press ctrl+F5 in Visual Studio. But, when I open the application from the directory it is in, it automatically closes instead of me pressing ENTER again.
Not sure how to edit…
Anyways, the same thing happens when I press F5 instead of CTRL+F5 in Visual Studio. Sorry, I’m new to programming. I am opening the program in the debug directory. Maybe that’s why. But where else would the program be? That is the only place where I can find the application file. So, do I have to use Visual Studio every time I want to open my program otherwise the program will close before asking me to press enter again?
I already know Javascript and some normal Java but this is not responding to things like ‘cin’ and ‘end1′ in the ‘iostream’ library. Why?
Part of the problem may be because it’s endl and not end1 (end-ell and not end-one)
I have this really wacked question I must have missed something I can’t find Why don’t we put “using namespace std;” on the very top like right after our #includes ?
Hey
just a quick one…
was wondering how i can display text before the input, this is my first go at C++ so any help is good.
Here is what i have come up with so far, but its on the same line.
cheers
int doubleNumber(int x) { return 2 * x; } int main() { using namespace std; cout <> x; cout << doubleNumber(x) << endl; return 0; }so from that to this
int doubleNumber(int x) { return 2 * x; } int main() { using namespace std; cout << "enter number to be doubled" ; int x; cin >> x; cout << doubleNumber(x) << endl; return 0; }Hi Alex,
Should function definition be there before main??? and Why??
when we write a program like this, it will not work
#include “stdafx.h”
#include “iostream”
int main()
{
using namespace std;
int numb,a;
cout << "Enter number" <> numb;
a = doubleNumber(numb);
cout << a;
return 0;
}
int doubleNumber(int x)
{
return x*2;
}
Jil,
In the third line,
should be
.
Also, int main() should be at the bottom of the program. (or write
under the
#include .
I hope that helps.
hey i have a problem with the following code:
#include <iostream> int add(int x, int y) { return x + y; } int multipliy(int z, int w) { return z * w; } int main() { using namespace std; cout << add(4, 5) << endl; cout << add(3 ,6) << endl; cout << add(1, 8) << endl; int a = 3; int b = 5; cout << add(a, b) << endl; cout << add(1, multiply(2, 3)) << endl; cout << add (1, add(2, 3)) << endl; return 0; }it gives me this error:
In function “int main()
“multiply” undeclared (first use this function)
I don’t understand what went wrong
Marco, you misspelled multiply when you wrote the function. But you spelled it correctly when you called it from main. So the compiler was expecting a function called multiply, which doesn’t exist in your program, although one called multipliy does. To fix the error, either change the function name to the correct spelling, or misspell it the same way in the function call. I’d go for my first suggestion, though either will work.
Hello, Marco its just a typo. You misspelled multiply
#include <iostream> int add(int x, int y) { return x + y; } int multipliy(int z, int w)//<--------- You misspelled multiply { return z * w; } int main() { using namespace std; cout << add(4, 5) << endl; cout << add(3 ,6) << endl; cout << add(1, 8) << endl; int a = 3; int b = 5; cout << add(a, b) << endl; cout << add(1, multiply(2, 3)) << endl; cout << add (1, add(2, 3)) << endl; return 0; }These tutorials are incredibly well constructed and very easy to understand. Many thanks to the author! I also love the quizzes! Here’s what I came up with for #5:
#include <iostream> int DoubleMe(int x) { return 2 * x; } int main() { using namespace std; cout << "Enter a number to double: "; int x; cin >> x; cout << "Your doubled number: " << x << endl; system ("pause"); return 0; }Ah, that code wasn’t working well. Mistakes are the best way to learn though :D
when I click build it says it “succeeded” but it doesnt open up the run window to show it. What is wrong?
When I press compile and run, it shows “In DoPrint” only once. Your example shows it twice. (I work on a Dev-C++)
Here is my code:
#include
void DoPrint()
{
using namespace std;
cout << "In DoPrint()" << endl;
}
int main()
{
using namespace std;
cout << "Starting main()" << endl;
DoPrint();
DoPrint();
DoPrint();
cout << "Ending main()" << endl;
system ("pause");
return 0;
}
On solution 5 you have two solutions to do the same thing:
This,
int main() { using namespace std; int x; cin >> x; cout << doubleNumber(x) << endl; return 0; }and this:
int main() { using namespace std; int x; cin >> x; x = doubleNumber(x); cout << x << endl; return 0; }I understand that this is a small simple program where performance isn’t an issue, but if hypothetically this was a program with a much larger scale, is there a difference in speed/performance between these two techniques? The first one seems shorter, and therefore faster?
//This is a superior method... #include <iostream> int main() { using namespace std; cout << "Enter a number: "; // ask user for a number int x; cin >> x; // read number from console and store it in x cout << "You entered " << x << endl; cout << "TIMES 2 IS "; cout << x * 2 << endl; system("pause"); }hey i dont understand why in q2 you have int product = x*2 instead of return x*2… i also dont understand why after the cout<< enter a number; all you have to do is say int x; how does the language know that the input of the person is now the value of x? does that make sense? like it doesnt say the entered info = x, just, int x which is just declaring it
I love my solution for question 5:
#include <iostream> using namespace std; int DoubleNumber(int a) { return a*2; } void Call(int a) { cout << "Your number doubled equals: " << a << endl; } int main() { cout << "Hello " << endl << "Enter a Number: "; int x = 0; cin >> x; cout << "Your number equals: " << x << endl; Call(DoubleNumber(x)); return 0; }Nice Tutorial so far!
Hey nIce tutorial i am understanding it :)
btw here is my code for solution 5 -.^
//solution 5 :P #include "stdafx.h" #include <iostream> int doublenumber(int a) { return a * 2; } int main() { using namespace std; int a; cout << "Please Enter A Number: " <<endl; cin >> a; cout << "Your Number Is: " << a <<endl; cout << "The Double Is: " << doublenumber(a) <<endl; system("pause"); return 0; }I have been doing fine with the tutorials up until quiz 5 which I can’t seem to get right (it keeps spitting out a large number instead of the one I want). Anyway, I decided out of frustration to build your code to see if that worked, and got this:
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|1|error: iostream: No such file or directory|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c||In function ‘main’:|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|10|error: ‘using’ undeclared (first use in this function)|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|10|error: (Each undeclared identifier is reported only once|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|10|error: for each function it appears in.)|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|10|error: expected ‘;’ before ‘namespace’|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|12|error: ‘cin’ undeclared (first use in this function)|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|13|error: ‘cout’ undeclared (first use in this function)|
C:\games\codeblocksprojects\practice1\practice 1\Untitled1.c|13|error: ‘endl’ undeclared (first use in this function)|
||=== Build finished: 8 errors, 0 warnings ===|
So wtf?
Sorry, ignore the above. I tried to delete the comment earlier but the site was laggy so apparently it didn’t go through.
Your code works fine, it was a software error (ironically).
finally! addition of 2 numbers
#include <stdafx.h> #include <iostream> int add(int x , int y) { return x + y; } int main() { using namespace std; int x; cout << "First number: "; cin >> x; int y; cout << "Second number: "; cin >> y; cout << add(x , y) << endl; return 0; }Here is what I came up with for question 5
#include "stdafx.h" #include <iostream> int doublenumber(int x) { return x * 2; } int main() { using namespace std; int number; cout << "Enter a number you would like to double: "; cin >> number; cout << "The number you entered was " << number << ", and " << number << " doubled is " << doublenumber(number) << endl; system("pause"); return 0; }When I use Code::Blocks, and I type in my code:
#include <iostream> using namespace std; void DoPrint() { cout << "In DoPrint()" << endl; } int main() { cout << "Starting main()" << endl; DoPrint(); cout << "Ending main()" << endl; return 0; }It says that: It seems that this file has not been built yet.
Would you like to build it?
I click yes, but it still hasn’t been built!
I am going on working.I wish to finish all tutorial:)Thanks again.
Hey, I’m new to C++, and I answered question 5 as follows:
int multiply(int x, int y) { return x * y; } int main() { using namespace std; cout << "Enter a number: "; int x; int y = 2; cin >> x; cout << "Number entered multiplied by 2= " << multiply(x, y) << endl; }It works, but is not included in the answers…so, is it a correct way?
Hi people . i mixed it up a bit with this lession . used bits from the last couple of lessions. which made it interesting . sorry if somone else posted somthing like this dident read all the comments.
heres what i came up with .
ps learning heaps thanks for the site .
#include "stdafx.h" #include "iostream" void doprint() { using namespace std; cout << "enter number here "; int x; cin >> x; cout << "you enterd " << x << endl; } int main() { using namespace std; cout << "Hi Thanks for coming "; doprint(); cout << "And thats all people" << endl; return 0; }Hello, Andrew
doprint() serves no purpose here.
This would be easier to read and write.
#include "stdafx.h" #include "iostream" using namespace std; int main() { cout << "enter number here "; int x; cin >> x; cout << "you enterd " << x << endl; cout << "Hi Thanks for coming, And thats all people " << endl; return 0; }In the quiz questions to this section you forgot to put
using mainspace std;
in several parts leading it to be impossible to put cout, and <<endl in some parts where they are at.
In #2 it says
int multiply(int x, int y)
{
int Product = x * y;
}
Now I know that it is meant to be corrected… However, I also noticed that because of this example I saw another comment where somebody actually made mistakes because they saw this and the answer does not point this part out speciffically and being incorrect when it say product. I do believe it should be …. return(x * y);….
I believe this might help people understand a little bit better, or prevent any confusion.
Thanks,
Nik
I felt like adding, subtracting then squaring, this is the shortest I could make the code using the callsigns and what not. I found another way, but here’s my two cents… It doubles if you input 2, 2, 2 :P
….
#include
int add(int x, int y, int g)
{
return x + y – g;
}
int square(int s)
{
return s * s;
}
int main()
{
using namespace std;
int x;
int y;
int g;
cout << "This will put your first and second number together, subtract the final number you input, then square that." <<endl;
cout << "input first value and press enter" <> x;
cout << "Now input your second value." <> y;
cout << "Now finally enter your final number to be subtracted." <> g;
cout << "your final number is…" <<endl;
int s;
s = add(x, y, g);
cout << square(s);
}
:) thank you for posting this tutorial, it is a big helper so far.
Nik
why do i need to put “endl” at the end of somethings? It tells me too but when i dont it still works.
I have a problem with this and every other section of tutorial. There is a lot of parts like this:
:( It’s not up to browser, tried it with Chrome, Opera and Internet Explorer :(
thanks Nik!
I am also totally new to C++.
Does main always execute before the other functions in a program?
Please could someone reply, I need urgent help. Paste the code below into your compiler.
When you are asked your age, I want the Main() to run again if the input is over 200. Bet instead the Main() runs regardless of any number. How could I implement the Main() to restart only if the age is over 200?
#include
int a; // this is devoted to void Beta() to find sum
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int l;
int ab; // Devoted to void Main() to find age
void Main()
{
using namespace std;
cout << "That's not it! There's more!" << endl;
cout << "Enter your age please, when you do this you will be automatically entered into our database!" <> ab;
if (ab < 10)
cout << "My you're young!" < 10 < 50)
cout << "Your're a good age" << endl;
else if (ab = 0)
cout << "You haven't been born yet? Interesting.." << endl;
else if (ab < 0)
cout << "You're that old. Sure. You're number will not be recorded for convenience reasons." < 50 < 70)
cout << "You're getting quite mature" < 100 < 120)
cout << "My you're old! Hang on there, you just might make it into the Guinness!" < 120 < 200)
cout << "How on earth is that possible?! Dear God you're old!" < 200)
cout << "Lies will not be tollerated, consequently you will sequentially have to re-innput your age for configuration" << endl; Main();
cout << "Thank you for your co-operation." << endl;
}
void Beta()
{
using namespace std;
cout << "Calling Beta" << endl;
cout << "Enter a number" <> a;
cout << "The number you entered was " << a << "!" << endl;
cout << "Okay, lets move on to the actual prototype" << endl;
}
int main()
{
using namespace std;
Beta();
cout << "Please enter nine numbers, after entering each press enter" <> b;
cin >> c;
cin >> d;
cin >> e;
cin >> f;
cin >> g;
cin >> h;
cout << "Bare with me, only one number to go now!" <> i;
cout << "You did it! (No patronising intended)" << endl;
cout << "The numbers you entered added together and timesed by 2 is " << b+c+d+e+f+g+h+i*2 < 3000 < 50000)
cout << "That's a big number!" < 1000000)
cout << "OMG! That number is huge dude!" << endl;
else if (b+c+d+e+f+g+h+i*2 < 0)
cout << "Minus number? COOL!" << endl;
Main();
return 0;
}
Please could someone reply, I need urgent help. Paste the code below into your compiler.
When you are asked your age, I want the Main() to run again if the input is over 200. Bet instead the Main() runs regardless of any number. How could I implement the Main() to restart only if the age is over 200?
#include
int a; // this is devoted to void Beta() to find sum
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int l;
int ab; // Devoted to void Main() to find age
void Main()
{
using namespace std;
cout << "That's not it! There's more!" << endl;
cout << "Enter your age please, when you do this you will be automatically entered into our database!" <> ab;
if (ab < 10)
cout << "My you're young!" < 10 < 50)
cout << "Your're a good age" << endl;
else if (ab = 0)
cout << "You haven't been born yet? Interesting.." << endl;
else if (ab < 0)
cout << "You're that old. Sure. You're number will not be recorded for convenience reasons." < 50 < 70)
cout << "You're getting quite mature" < 100 < 120)
cout << "My you're old! Hang on there, you just might make it into the Guinness!" < 120 < 200)
cout << "How on earth is that possible?! Dear God you're old!" < 200)
cout << "Lies will not be tollerated, consequently you will sequentially have to re-innput your age for configuration" << endl; Main();
cout << "Thank you for your co-operation." << endl;
}
void Beta()
{
using namespace std;
cout << "Calling Beta" << endl;
cout << "Enter a number" <> a;
cout << "The number you entered was " << a << "!" << endl;
cout << "Okay, lets move on to the actual prototype" << endl;
}
int main()
{
using namespace std;
Beta();
cout << "Please enter nine numbers, after entering each press enter" <> b;
cin >> c;
cin >> d;
cin >> e;
cin >> f;
cin >> g;
cin >> h;
cout << "Bare with me, only one number to go now!" <> i;
cout << "You did it! (No patronising intended)" << endl;
cout << "The numbers you entered added together and timesed by 2 is " << b+c+d+e+f+g+h+i*2 < 3000 < 50000)
cout << "That's a big number!" < 100000)
cout << "OMG! That number is huge dude!" << endl;
else if (b+c+d+e+f+g+h+i*2 < 0)
cout << "Minus number? COOL!" << endl;
Main();
return 0;
}
Hi
A funny thing is happening w/this code when I try to call and interrupt a call, the “In Doprint(), and In Doprint2() are continously rolling on the screen not stopping even w/esc. on keyboard. Stops when clicked on the console window.
I don’t understand why this is happing. Be great if anyone can and please explain it to me.
thanks.
The Code:
#include “stdafx.h”
#include
//Declaration of function Doprint()
void Doprint()
{
using namespace std; // we need this in each function that uses cout and enel
cout << "In Doprint()" << endl;
}
// Declaration of function Doprint2()
void Doprint2()
{
using namespace std;
cout << " Starting Doprint2()" << endl;
Doprint();
Doprint2();
Doprint();
cout << "Ending Doprint2()" << endl;
}
// Declaration of main()
int main()
{
using namespace std;
cout << "Starting main()" << endl;
Doprint(); // this is a function call to Doprint()
Doprint2();
Doprint();
cout << "Ending main()" << endl;
return 0;
}
The Result:
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
In Doprint()
Starting Doprint2()
Press any key to continue . . .
Hi,
Is anyone out there. Please help me.
what’s wrong with this code, it only returns “starting main & ending main”
I am really frustrated.
#include “stdafx.h”
#include
int Return5()
{
return 5;
}
int main()
{
using namespace std;
cout << "starting main()" << endl;
Return5();
cout << "ending main()" << endl;
return 0;
}
Hi Alex, nice work on the tutorials, I’m moving from C# to C/C++ and your blog is a great help!
Just thinking it may be noteworthy to mention that in C++, methods/classes/whatever have to be declared before the executing member.
e.g this code:
using namespace std; void DoFooBar() { cout << "Foobar!" << endl; } int main() { DoFooBar(); }Will have the user end up with a C3861: identifier not found. While turning those two around:
int main() { DoFooBar(); } void DoFooBar() { cout << "Foobar!" << endl; }Will actually compile and run correctly. Took me a while to figure this one out, since the order of declaration doesn’t matter in C#, but it turns out the C++ compiler actually moans about this.