Beruflich Dokumente
Kultur Dokumente
C++
This is a placeholder for Portal:Engineering and Technology → School:Computer
Science → Topic:Computer Programming → Topic:C++
Welcome to C++. Whether you're not certain which language to pick or you've
already decided on C++, you've come to the right place.
Arguably, C++ is the most versatile language in common use. It combines speed
with expressive power like no other language: it isn't perfect, but it represents the
current best compromise between these two, often conflicting, attributes. It also
combines "low-level" programming, as in moving bytes around, to "high-level"
programming, which is very abstract. Both of them have pros and cons that we'll
cover in this tutorial.
Why should you learn C++?
A key feature which distinguishes it from the language it grew from is that it is object-
oriented. An example can help to demonstrate what that means. If you were writing
a program to track the statistics of a racing cyclist, you might make different parts of
the program for their age, years of racing, wins, falls, what teams they've raced with
and so on. In real life, though, that's not how we think. Instead, we would think of the
cyclist as a whole, and the different statistics as being part of him. We could also
apply that general "model" of a cyclist, maybe with a few modifications, to any
cyclist, and have a complete representation of them. This is the essence of object-
oriented programming, and as you understand it more fully, it will allow you to create
powerful yet easily-understood programs. Instead of relying on data that is scattered
throughout a program, you can create a block of code that defines everything you
need, and then you reuse that throughout the code.
As a further example, think of a motor car. You unlock it with the key, and get in.
Then, you turn the ignition, put the car in reverse, release the brake, and press the
accelerator. As you drive, you use the steering wheel, the brake, and the accelerator
(and maybe the clutch). You don't know or need to know all the specifics of the car to
make it work. You just use what you need, and it's simple, too. Object-oriented
programming is like that. You can make powerful code, but it's all hidden, and you
can interact and reuse that code using the simple controls.
Other languages, such as Java, Python, Smalltalk and C#, allow the programmer to
write code in this object-orientated way. The key difference between C++ and these
languages is that C++ is designed to be compiled into efficient low-level code which
can run directly on the processor of a computer. This ability means that C++ differs
in many ways from these other languages, and lacks many of the advanced facilities
you might be familiar with if you already know one of them.
Contents
[hide]
1 Prerequisites
2 Course Description
3 Lessons
4 To be merged
5 Enrolled
Prerequisites [edit]
Your enthusiasm. This is meant for a first time user. Every lesson will only depend
on what has already been taught in previous lessons. All you need here is your
willingness to learn, experiment, and have fun with computers.
In addition, it is essential to have a compiler. These are programs that can take the
C++ code which you input and turn them into a program. There are many compilers
around: Borland C++, Microsoft Visual C++, and GNU C++. There's also a host of
free, un-sponsored compilers out there--most notably Dev-C++.
As you go through this tutorial, run the scripts through your compiler, edit them, and
muck around with your own. It will give you practical knowledge and you'll quickly
learn to program effectively.
3. Does not come with a ready-made "library" of useful code, and so requires a
vast amount of effort to create a relatively simple GUI program, for example
4. C++'s most powerful features, such as templates, have a very complex
syntax.
Lessons [edit]
Beginners
1. Lesson 1: Introduction to C++
5. Lesson 5: Loops
2. Lesson 9: Templates 1
Advanced
1. Lesson 11: The STL
To be merged [edit]
1. Switching from C to C++
2. Flow Control
Enrolled [edit]
Please sign below if you are participating in this topic. Use 4 tildes (~) to sign.
1. J Blom 18:10, 9 January 2008 (UTC) I would love to re-explore the secrets of
C++ -- Thanks guys.
2. PGalasti 04:40, 7 January 2008 (UTC) I need to re-learn C++. Great site to
re-learn.
3. Thejamesman 18:28, 12 October 2007 (UTC) I look forward to learning. I
have ALOT of computer modding and manipulation experience, but its time to
get to the bare bones!
4. Smartguy583 00:37, 30 September 2007 (UTC) This course seems so much
more comprehensible that any of the books I've tried to learn C++ from.
5. Raspberry 21:58, 29 July 2007 (UTC) I love wikiversity. Learn, and pass on
what you know! I'm learning computer science, and teaching physics,
astronomy and music!
6. Kafitz22 15:15, 24 July 2007 (UTC) Can't wait to start learning C++, although I
know nothing except a bit of TI-BASIC :P
7. Michael Z 07:42, 2 July 2007 (UTC) (Looking forward to learning the language
of C++)
8. Mortimir 01:15, 22 May 2007 (UTC)
9. Giawa 17:51, 5 October 2006 (UTC) (Here to learn, have my code torn apart,
try to help teach, everything)
10. --SB_Johnny | -- Complete and total newbie. I'd like to become less
talk
14. Miles32 06:45, 7 January 2007 (UTC) Here to learn C++. Im completely new
to programming and I heard that c++ was the way to go.
15. Blasterman 7 January 2007 -- C++ is my main programming language, so I'd
like to sometimes help write the lessons. Never used C before, though.
16. — Saivorgz 05:34, 12 January 2007 (UTC) -- January 11 2007 -- §wanting to
learn c++ since i know java
17. ex0du5 22:25, 12 January 2007 (UTC) -- Currently enrolled in Computer
Engineering, and have taken 3 Java courses. I want to learn C++ as it is more
efficient in programming visual and graphic intensive applications.
18. Modnar 09:31, 26 January 2007 (UTC) (Going to be doing this in university
this year and would like to get a head start and always wanted to learn and
now I have decided to do so and looking to use this also with creating Palm
OS programs in the future hopefully as well :D)
19. cybergig (02/01/07 5:02AM ) I'm a total newbie to this so I am here to quickly
learn this language and hopefully several others to get a head-start on
programming.
20. Liam §wanting to learn c++
21. Mattsan 19:27 10 Febuary 07 Totally new to programming but I'm really
enthusiastic on learning C++!
22. Chuboltite 10:00, 10 March 2007 (UTC) I've heard from multiple sources that
C++ is a great language to learn. Plus, the programming experience will help
me in my future studies, so why not?
23. Chyld989 09:23, 11 March 2007 (UTC) I already know some C++, some of
which I learned on my own and some of which I learned in school. Hoping to
maybe learn a bit more, and maybe help others in the process.
24. baci 09:26, 12 March 2007 (UTC) Like so many others, I'm here to learn and
then teach. I wish I more experience so that I could assist with completion of
this course.
25. Devourer09 20:38, 22 March 2007 (UTC) Here to learn and if possible help
others.
26. 72.94.226.175 03:02, 21 April 2007 (UTC) Well, I could probably help, just
need to find a topic that needs to be covered. maybe pointers?
27. --Xentalion 00:57, 2 May 2007 (UTC) I'm here to help too, I've written a few
programs in C++ and am hoping to help other people learn.
28. Jocade 010 07:25, 21 May 2007 (UTC)
29. --Topcount345 01:14, 22 May 2007 (UTC)|Talk I hope to learn more about c++,
next year I am going to be in a class( by myself) in an attempt to learn c++.
Starting to learn now in an effort to put a footstool in place to climb the wall
this will probably be.
30. Scooter 16:37, 23 May 2007 (UTC) I've been writing code for about 2 years,
one of them with C++, I am most enthusiastic about wikiversity and I plan to
contribute as much as I can.
31. Cbradleyo 17:19, 18 June 2007 (UTC) Learned programming in high school,
but that was over 10 years ago. Eager to learn C++.
32. Aamirsayid1 20:51, 10 July 2007 (UTC)Aamir Sayid
34. ali2538 22:07, August 4 2007 (UTC) I wanted to learn this language since 7
years ago and every time that I started some thing happened. I hope I can be
successful in it this time. I really want to learn c++. Good Luck to Everyone in
learning C++. Including me.
35. --Pajumed 02:12, 8 August 2007 (UTC) Just found out about wikiversity and
I've wanted to learn C++ for a while, might as well if I want to do comp sci in
college.
36. Vitor 03:01, 14 August 2007 (UTC) To teach those who know less and to learn
from everyone.
37. jolt_34500 23:44, 28 August 2007 (UTC) Want to learn more about
programming.
38. Bensaved 06:57, 31 August 2007 (UTC) Senior Computer Science major,
looking to learn more about other languages than Java.
39. icecreamsoop 13:09, 11 October 200y (UTC) I'm looking to expand my
programming knowledge beyond that of Java.
40. 205.204.242.22 13:43, 5 September 2007 (UTC)User:ki4jgt
44....
45. Speilberg0 23:47, 26 December 2007 (UTC)
46. Captain panda 05:13, 5 January 2008 (UTC) I have only just learned a few
weeks ago how little I really know about computers and I want to learn
programming languages to help teach myself. C++ seems like a good place to
start.
47. Nofrak 05:04, 23 January 2008 (UTC) Expanse of knowledge
Category: Programming Languages
1. resource
2. Discussion
3. Edit this page
4. History
1. Log in / create account
Navigation
1. Main Page
2. Browse
3. Recent changes
4. Random topic
5. Random page
6. Help
7. Help desk
8. Donate
community
1. Portal
2. Colloquium
3. News
Search
Go Search
Toolbox
1. What links here
2. Related changes
3. Upload file
4. Special pages
5. Printable version
6. Permanent link
In other languages
1. Français
2. Italiano
1. 1 Hello World
1. 1.1 Includes
2. 1.2 main()
3. 1.3 Namespaces
2. 2 Where To Go Next
int main()
{
cout << "Hello World!" << endl; //Prints Test
cin.get(); //Without this line the program ends very quickly in
Windows
return 0; //Returns Success of the program
}
Includes [edit]
Now to explain this introduction to C++ code. The commands that are used in this
example are defined in two files which are included with the #include directive.
#include <filename>
Most of the time you will need to include commands like this so you don't have to
reinvent them from scratch. When the C/C++ compiler reaches an #include directive,
it will attempt to load the file named within the symbols <filename>. This file is called
a header file, include file, or library as stated above, but it is basically just another
file with C/C++ code in it. Loading files with #include allows you to access new
functions, global variables, objects, and structures that would otherwise not be
available to you in the code. Unlike most commands in C/C++, you do not need to
end an #include directive with a semicolon. It is common practice to place the
#include directives before the body of the code, but this isn't required.
The <ostream> and <iostream> files contains functions that assist in formatting and
writing output to the screen.
main() [edit]
When you compile your code, the compiler looks for a main function and starts the
program there. Functions will be explained in greater depth in a later lesson, but
what you need to know now is that the compiler looks for main() and runs the
commands contained within main() first. You start writing your commands
immediately after the { symbol, and the program ends when it reaches the } symbol.
A note: with normal functions, you call them from another function, for instance, if
you had a function that took two numbers and multiplied them, you might use code
like this: multnumbers(6, 2);. So what calls the main function? The answer is the
operating system, and so that is where your program starts off. That is why it is so
important to include the main() function in your code. By the way, if you don't
understand this, don't worry. It will all be explained later on, like I said.
Namespaces [edit]
Within all modern programming languages there is a the concept of namespaces.
Just as I said before, using other peoples code is a great way to get your code
working. Again, there is no point in reinventing the wheel. Namespaces contain all
sorts of "identifiers" that are useful. In our program there is a namespace called std,
which contains cout and endl. The method to use an identifier within a namespace
is:
namespace::identifier
So in the case of our program, we've used the namespace std and the identifiers
cout and endl. Namespaces can be nested, you can create namespaces, and you
can be using identifiers from multiple namespaces at the same time. Coding with the
namespace::identifier format can get tedious though, especially if you are only using
one namespace in your code. For this reason, there is an easy way to let the
compiler know that you will be using the std (or any other namespace) for the rest of
your code. It's a way of telling the compiler where to look when it can't find an
identifier you used. The code looks like this:
using namespace std;
I've used the namespace "std", which is the namespace we used in our code. This
will allow us to remove std:: from all of our code. This is extremely useful, because
you can imagine how much extra space would be used up by std:: if we had more
that one line of cout and endl. "std" is also used for other identifiers that you'll be
using in your future code, so it is helpful to include the std namespace in most of
your beginner programs. After you've removed std::, your code should look like this:
int main()
{
cout << "Hello World!" << endl; //Prints Text
cin.get(); //Without this line the program ends very quickly in
Windows
return 0; //Returns Success of the program
The cin command is used to recieve user input. Without the cin.get() command the
program would run and exit in less than a second on Windows Platforms. By adding
this line, the user must press enter to end the program. This gives you a chance to
see your code work.
Another way you can do this is using "\n". \n basically means "new line after this"
here is an example of it in use:
#include <iostream>
using namespace std; // very bad practice with namespace
int main() {
cout << "I'm going to try and display Hello World! on a new
line\nHello World!\n";
system("pause"); // this won't work on many platforms - you should
stick to standard C++
return 0;
}
//this
cout << "hello";
//is the same as
cout
<<
"hello"
;
//and this
cout
<< "hello"
This makes your code neater and more organized. This rule holds for the most part,
although there are occasional things that you can't break up into two lines, but
unless you see that specified in a certain section, go ahead and do it in your code.
How to end a function [edit]
Most functions are built to return some sort of value to whatever called it in the first
place. There will be more on this later. What you need to know is that return 0;
means that a value of 0 will be returned from the code. Your compiler will normally
tell you how your program ended. For example, my compiler will say "HelloWorld
ended with code 0" after I've compiled and run my code. Different values can mean
different things depending on your program. You could set a return code of 2 to
mean there was an error, or and return code of 1 could mean your function
completed successfully. Many times, it might be an answer- for instance, above, I
wrote about the multnumbers() function that looked like this: multnumbers(6, 2);. In
this function, it might assign 6 to a and 2 to b, and the return code might be
return a*b;
So, if you had called this in your main() function, you might have written something
like
#include <stdio.h>
int main()
{
//Your code here
getchar();
}
• Another note on compilers: What if you don't have one? Well, the good news
is, there are tons of good compilers that are available for free. For most
POSIX systems, gcc (the GNU Compiler Collection) is available. It is arguably
one of the best compilers ever written and does a good job of implementing
standards. However, many people using Windows or the Mac OS like good
IDEs. For OS X, there is Xcode. It is a very powerful, yet user friendly IDE for
developing in many languages, and it uses gcc for C++. It's large however,
but if you're developing on OS X, this is vital. For Windows, there is Dev C++
(which is very popular at my university among students). Also popular (but
expensive) is Microsoft Visual C++.
2. 2 Initializing Variables
3. 3 Types of Variables
1. 3.1 Booleans
2. 3.2 Integers
3. 3.3 Char
4. 3.4 Floats
5. 3.5 Doubles
4. 4 Lesson 2 Program
2. 4.2 Casting
5. 5 Where To Go Next
Variables - What are they [edit]
Before we get into coding, let's think a little bit about what variables really are. I am
going to describe this in as simple terms as possible.
When engineers way back in the day began to work on computers, they quickly
realized that there needed to be a way to input information into the computer and
store it there. Then that information needed to be accessed again and used. You can
of course, understand why this is important. Computers would not be of much use if
they had no way to temporarily store information. Today, there are many different
types of data that can be stored on a computer. We'll take a look at them in this
lesson. Then we'll look at ways for the user to input data into a program and get a
result.
Anyways, back to my story about the engineers and the early computers. Before
languages such as C++ existed, engineers used to program their computers in a
language such as assembly. In assembly, engineers would have to keep track of
every single part of memory on the computer. Memory on a computer is stored
linearly, with a specific address for each memory location. So, if a programmer
wanted to add the contents of his working register with the contents of register 0x86,
they would have to use an instruction such as
addlw 0x86
The above, of course, would get extremely complicated if you were trying to code
something that relied on hundreds of data addresses. You would have to keep huge
tables to let you know which data address meant what, and so on. Mistakes would
be bound to happen, and that is why engineers developed a better way to organize
data.
Variable (defn): a symbol for an unspecified member of a class of things or
statements
A variable is a name that is given to a data address. When a compiler sees a
variable that is initialized it creates a data address for that variable, and assigns that
address to all instances of that variable name. This makes it much easier on the
programmer (you!). So instead of the above code example, you can now use code
that makes a lot more sense.
int myVariable=5;
myVariable = myVariable + myVariable;
variable_type variable_name;
If, for example, you would like to create 2 integers with the names "Zelda" and "Link"
you could type
int zelda;
int link;
// or, to save space you could declare them both on the same line. int
zelda, link;
variable_name = value;
This code will create two boolean variables. The variable named true will contain a
1, a logic high, whereas the variable named false will contain a 0, a logic low. These
could then be used in logic statements or be set to different values. Notice how I
have set the variables equal to their values on the same line that I initialized them.
Integers [edit]
An integer is a number that does not have any decimal places. It is a whole number,
for example 1,2,3,4 are all integers. 4.3 is not, as it is a fraction of a whole number. If
you were to try and place the number 4.3 into an integer the number will be rounded
down to 4. Originally an integer was an 8 bit value, which meant that it could store a
value from 0 to 255. It is also possible to store signed integers, which means they
can hold numbers that are below 0. Let's take a look at all the different types of
integers now.
Wow, that is a lot of variable names. Now, all of these values are guidelines for C++.
The compilers must store from AT LEAST these ranges. Some compilers will use
more bits for their long integers, but these are the guaranteed ranges regardless of
your C++ compiler. Many of these variables store the same range of values, yet
there are so many different names. What is the difference between a "long" and a
"signed long int"? In my mind, the only difference is 12 extra keystrokes. Pick one
that works for you.
Char [edit]
A char is an 8 bit integer. This means that an unsigned char can store between 0
and 255, and a signed char can store between -127 and 127. Unsigned chars are
commonly used to store text in ASCII format, and can be used to store strings of
information. A char can be initialized to hold either a number or a character.
char myChar='A';
char myOtherChar=65;
Both characters that I have just initialized would be equal. The number 65 is the
ASCII code for the letter 'A', so both characters would contain the 8-bit value of 65,
or the letter A.
Floats [edit]
Floats are floating point numbers, which means that these numbers can hold
decimal places. This allows us to store numbers such as "8.344" and
"3432432653.24123".
Like integers, floats are dependent on the hardware of the computer you are
compiling on. Later we will look at ways to see how much accuracy your computer
will get with floating point numbers.
Doubles [edit]
Doubles are like "floats", which means they can store decimal places. Doubles can
generally store more information than a standard float.
Set up a console application just like in last lesson. Make sure you include iostream
and create your main() function. If you have any problems, check your code against
mine below. So the first part of this code is easy. We've seen how to declare and
initialize variables (specify type, name, and a value). Write the code to initialize your
variables, and set banana=10 and monkey=15.
Now it is time to get user input. Remember how we used cout to write to the screen?
Now we will use cin to read from the user. The syntax is very similar. Here's a
comparison of cin and cout
Enter an integer: 15
You entered the number: 15
15 is the number that you, the user, entered. The program stored that value 15 at
the data address referenced by myVariable. Now, it is time to incorporate cin into our
program. Let's see where we can get to now.
#include <iostream>
This program initializes all of our variables and gets user input for one of them. Now
it is time to do something with the data we have stored. To do that, it is time to learn
something called casting!
Casting [edit]
Casting is extremely useful, and is used to convert one type of variable or data type
into another. An example might be an integer that you want to turn into a float. If you
wanted to divide the integer 4 by the integer 3, you would get an answer of 1. Even if
you are setting a float equal to 4/3, you would still get 1. That is because there are
no decimal places available for the division of 4 and 3, the compiler assumes you
want a integer response when dealing with two integers. Casting solves this
problem.
Casting syntax is very easy.
(cast to type)variable_name;
Let's dive right into some examples, as they are easy to understand.
answer=(float)four/(float)three;
cout<< answer; // Now that the ints have been changed to float, the
response will be 1.33333, a float!
#include <iostream>
Wonderful! We have now written a second piece of code that works! Here is what
was output by my code:
2. 2 Where To Go Next
#include <cmath> // ANSI C++ way. For ANSI C you should do: #include
<math.h>
Note that the math library is one of the 18 ANSI C language standard libraries that
can be imported in C++. Now you have made many useful functions available to
your program. Now, let's do some math.
Adding, Subtracting, Multiplying and Dividing [edit]
These are all very straightforward, and do not even need the math library to work.
The syntax for basic math with these operands are as follows:
int myResult;
myResult= 5 + 6; // A value of 11 will be stored into the integer
myResult
Now, C++ allows this all to be very flexible. So you can mix numbers, variables,
floats, ints and all sorts of things together.
C++ will perform operations via BEDMAS (or PEDMAS, or however you learned it in
middle school). That means brackets (or parantheses) will be computed first. Then
exponents, then division and multiplication, and then finally addition and subtraction.
The above code will take the number six, and then convert it to a floating point
number. Then it will multiply 6 by pi, which will return a floating point number. Then
twelve, which has been converted to a float, will be added to the result. So myResult
at this point will contain 30.84. Then five will be converted to a float and subtracted
from myResult. The result will be 25.84.
This should be pretty straightforward. Now, take a look at the last line of the above
code. Notice that we are taking the variable and adding another value to it, and then
dumping it back into itself. You've just had to type the same variable name twice in a
row, which could lead to typos, and also takes up time. There is an easier way to do
this! Each of the following lines has an equivalent line of code that follows.
myResult = myResult+5;
myResult += 5;
myResult = myResult-5;
myResult -= 5;
myResult = myResult*5;
myResult *= 5;
myResult = myResult/5;
myResult /= 5;
See the pattern? We reach another very common situation. There are many
instances where you will want to increment a variable by one, or decrement it by
one. This is very common in counters and loops. For example, everytime the user
hits a button on the keyboard you may want to increment a counter by 1. So, here's
an easy way to add one, or subtract one from a variable.
intcounter=0; // Initialize the variable
counter++; // Adds 1 to the variable counter
counter--; // Subtracts 1 from the variable counter
Let's investigate what this does. First, this program takes the square root of 25 and
stored into myResult. This leaves a 5.00 in myResult. Then this value is squared and
stored back into itself. This means 25.00 will be stored in myResult. So, more
simply:
1. 1 Comparison Operators
3. 3 The switch...case
Construct
4. 4 The Conditional
Statement
5. 5 Where To Go Next
Examples:
5 == 5 evaluates to true.
7 != 5 evaluates to true.
'a' == 'b' evaluates to false.
6 > 9 evaluates to false.
4 <= 4 evaluates to true.
!true evaluates to false.
true! is invalid.
01: if (x == 7) {
02: //this code is executed only if x does indeed contain the integer
value 7
03: }
04: else {
05: //this code is executed if the preceeding if condition evaluated
to false
06: }
Explanation:
1. This is the first line. Note that there is space
between the keyword if and the opening
parenthesis. Inside the parentheses is the
condition; in this case it is a test for equality. It is
good practice to use the same type arguments (not
comparing floating-point values to characters).
Note also the left curly brace {. This symbol
denotes a block of multiple lines of code. Without
it, the conditional would only refer to the statement
immediately following it. It is good practice to
always use the braces.
2. This comment represents the body of the
conditional statement.
3. The right curly brace is essential; it matches the
opening brace on line 1 and signals the end of the
if body.
The body of the else block can be another if statement. This is known as "nested
conditionals" because the conditionals are indeed nested; that is, placed inside of
one another.
...
case 1:
case 2:
case 4:
//code common to those three cases.
break;
...
The entire expression evaluates to the expression given in the codeIfTrue and
codeIfFalse statements. If those are complete statements, then that code is
executed. It is also possible to specify a single value for each of those, and assign
this conditional statement to a variable, like this:
int a = ( x > y ) ? x : y;
//this is equivalent to:
int a;
if (x > y)
a = x;
else
a = y;
As you can see, this makes simple conditionals all the simpler, but can complicate
readability. Use sparingly.
See if you can come up with a few usages of the conditional constructs you have
just learned.
Loops
Loops allow a programmer to execute the same code repeatedly. These are often
called "repetition" constructs. We will make heavy use of conditional statements in
this section.
Contents
[hide]
6. 6 Where To Go Next
while ( condition ) {
//body
}
Again, the curly braces surrounding the body of the while loop indicate that multiple
statements will be executed as part of this loop. If the actual code looked something
like this:
while ( x == 4 )
y += x;
x += 1;
There would be a problem. According to what was written, even though the second
line after the while was indented, only the first line corresponds to the while loop.
This is a huge problem because the variable involved in the condition (x) does not
change, so it will always evaluate to true, making this an infinite loop. This could be
alleviated by containing all statements intended to be a part of the loop body in { }.
do {
//body
} while (condition)
As you can see, it will run the loop at least once before checking the conditional.
The do...while loop is still haunted by infinite loops, so exercise the same caution
with the do...while loop as you would with the while loop. It's usefulness is much
more limited than the while loop, so use this only when necessary.
until (x == 10) {
//do something
}
This loop will do something as long as x does not equal 10. If it gets back and tests
the condition and it evaluates to true, it will stop executing the loop and proceed to
the next statement after the closing curly brace.
Note that the same functionality can be accomplished with:
while (x != 10) {
//do something
}
The only difference is that semantically, the keyword "until" means more to the
programmer, and gives an immediate indication of the behavior of that block. If he
had to read into the condition of the while statement and realize that the negated
condition meant that the loop would wait for that condition to become true, that
would be a waste of time. However, for the programming language itself, it is nice to
have such a versatile loop structure as the while loop.
To better explain how the for loop works, let's look at one:
What does this loop do? Prior to the first iteration, it sets the value of i to 0. Next, it
tests (like a normal while loop) if i is less than 10. If the statement returns true, the
body of the loop is run and the program will print the value returned by the simple
arithmetic statement i+1 and move the terminal cursor down to the next line. After
the loop is finished, i is incremented (by 1), as specified in the update statement,
and the conditional is tested again.
So, this loop will run a total of 10 times, printing the "i+1" each time. You've taught
your program to count!
The variable used in for loops is generally an integer variable named i, j, or k, and is
often initialized prior to the beginning of the for loop. Another option is to initialize
the variable at the same time that you declare the variable's initial state:
int i, j, input;
What does this program do? The user is prompted to choose an integer, which is
used in the conditional statement of the first for loop. Each iteration of the i loop will
cause the j loop to run, which counts down from 10 to 1 before allowing the i loop to
continue. The output will look something like this:
How many missiles will you fire?
3
10 9 8 7 6 5 4 3 2 1 Missile 1 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 2 has launched.
10 9 8 7 6 5 4 3 2 1 Missile 3 has launched.
All missiles have been launched.
1. 1 Functions
2. 1.2 Prototypes
3. 1.3 Calling
4. 1.4 Parameters
5. 1.5 Scope
2. 2 Recursion
3. 3 Where To Go Next
Functions [edit]
Simply put a function is a segment of code that is isolated from the main code
segment. A function is called from a section of code. When the function's code has
been executed, it returns to the calling code. The general form of a function is:
return_type function_name ([arg1_type arg1_name, ...]) { code }
5. Every function with a return type other than void must have a return
statement. This is the data that the function will be sending back to the calling
code.
Many conventions exist governing the form of
functions in C++. Generally, whatever form is most
readable to you is the one you should use. For
example, some coders will leave the opening { on the
same line as the function definition while others will
give it its own line. Also, some coders would name
the above function add_two_ints. This is mostly
personal preference.
The main Function [edit]
The main function is a special function. Every C++
program must contain a function named "main". It
serves as the entry point for the program. The
computer will start running the code from the
beginning of the main function. There are two main
types of main functions; one with and one without
parameters. Below are examples of both:
/* Without Parameters */
int main()
{
...
}
/* With Parameters */
int main(int argc, char * const argv[])
{
...
}
/*Definiton*/
int fctn2(int num1, int num2)
{ ... }
/*Prototype*/
int fctn2(int, int);
This idea will be illustrated in the following
section.
Calling [edit]
Calling refers to how a function is used from
code.
Example:
#include <iostream>
using namespace std;
void fctn1();
int fctn2(int, int);
int main()
{
int sum;
fctn1();
sum = fctn2(2,3);
return 0;
}
void fctn1()
{
cout << "This is function 1!" << endl;
}
int main
{
fctn(num1, 12);
}
fctn(num1, 23);
1 Y Y N
2+ N N Y
temp = addTwoInts();
temp = addTwoInts(33);
Recursion [edit]
Recursion is a method of function calling in which
a function calls itself during execution. Let's start
by showing an example and then discussing it.
int factorial(int n)
{
if(n == 1 || n == 0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
1. factorial(4) is called
2. factorial(3) is called
1. Since n=3, we take the else path. We return 3×factorial(n-1)
2. factorial(2) is called
2. factorial(1) is called
1. Since n=1, we take the first path and finally return 1 to the previous function
1. factorial(1) returns 1 so factorial(2) can return 2×1...2
2. 2 Where To Go Next
Creating and Editing Classes [edit]
A Description of Classes [edit]
C++ uses classes to implement the object-oriented methodology. In short, object-
oriented design is a method for design which models data objects on the idea of a
real object, using variables to create traits for the object. For instance, you could
have a class that defines a dog:
Dog:
----
int name
int gender
int age
int size
bool healthy
This class has several variables: name, the gender of the dog, the age of the dog,
it's size, and whether or not it is healthy.
public:
char name[25];
int gender;
int age;
int size;
bool healthy;
};
This class may now be accessed from inside the program. Here is an example.
#include <iostream>
class Dog
{
public:
char name[25];
int gender;
int age;
int size;
bool healthy;
};
As you can see, the program creates a dog named newDog, and sets it's gender to
1, and it's age to 3. However, this method is not advised, because it allows any class
or function to change the variables.
Creating a Class Containing Functions [edit]
To increase the safety of the variables, make them private. This will hide them from
every thing except the class that they are in. To change these variables, we create
functions inside of the class.
C++ comes with two default functions for every class you write. They are both
identical to the name of the class, so if your class is called "Dog", the default
functions will be Dog() and ~Dog() (notice the tilde at the front). The first function,
Dog() is called every time the class is created. The second one, ~Dog() is called
when the class is destroyed, or deleted. These functions do not have return values.
Here is our Dog class, with better protection for it's variables, and functions to
change them.
#include <iostream>
class Dog
{
private:
char name[25];
int gender;
int age;
int size;
bool healthy;
public:
Dog(int getAge, bool getHealthy)
{
gender = 1;
age = getAge;
healthy = getHealthy;
size = 20;
setName("Doggy");
}
//This function checks to see that the dog's age is possible, and
returns false if it is not.
bool changeAge(int getAge)
{
if (getAge >= 0 && getAge < 50)
{
age = getAge;
return true;
}
else
{
return false;
}
}
};
Templates 1
At times we find difficulties in programming, we want to make something work the
same for different objects and we often have to design the same thing several times
in order to make it work. Suppose you want to make a simple Vector class, as in
std::vector. Practically, in C, there is only one way to do it: Keeping type information
stored somewhere in your list. This is a very common problem in C, and several
people came up with several solutions for that, but now, in C++, the solution to all
type-insensitive (those who do not rely on class functions / members) classes and
functions came up. If you are one of those interested in the concept of generics
(same as type-insensitive), you are on the right place. Welcome to C++ templates.
Contents
[hide]
1. 1 Introduction
2. 2 Template
Functions
1. 2.1 Syntax
3. 3 Template
Classes
1. 3.1 Syntax
2. 3.2
Implementatio
n
4. 4 Where To Go
Next
Introduction [edit]
Templates are the mechanism by which C++ implements the generics concept. The
following example illustrates two non-generic (type-sensitive) functions for
multiplying two numbers, x and y:
Two functions that do the exactly same thing, but cannot be defined as a single
function because they use different data types.
template<class Type>
or
template<typename Type>
The keywords class and typename have the exactly same meaning in this case, but
some compilers may replace the word class for typename when giving you
information about the class, as it's often better accepted by programmers.
Type is our generic data type's name, and when the template is to be used, it would
be the same as Type was a typedef for your datatype, and that's exactly how it
behaves, therefore, whenever you use the word Type, you are talking about the data
type being used on your template. The following example now illustrates how the
multiply function would be written using a template:
template<class Type>
Type multiply ( Type x, Type y )
{
return (x * y);
}
As a syntax sugar, C++ provides the option of hiding the type information, case in
which the data type used on the function call is assumed. For instance:
int r1 = multiply ( 2, 5 );
int r2 = multiply<int> ( 2, 5 );
Both yield the same result, as they are exactly the same. An important note to take
from here is that this is the one of the very few syntax sugars that templates have.
Optionally, a template can have more type options, and the syntax is pretty simple.
For a template with three types, called First, Second and Third, we have:
And it works exactly as the single-typed template. The template data types are order
sensitive, of course, so doing:
multiply<char, int> ( 2, 5 );
multiply<int, char> ( 2, 5 );
template<class Type>
class Node
{
public:
Type value;
Node* previous;
Node* next;
};
Notice one important thing: Although the data type for Node pointers previous and
next is hidden, the type Type is assumed. The same declarations could be written
as:
Node<Type>* previous;
Node<Type>* next;
Also notice that the exact same syntax used for function calling is used for class
instantiating. You can hide data types in specific cases, but for legibility and to
establish a solid coding convention, you shouldn't, unless you are on the same class
as the variable being declared / instantiated.
There is also the possibility of setting a default type, as in:
Or
Both syntax are equally valid, and you can use previous types to define next ones
(as T1 is the template type for type T2).
Note it only works effectively (but you can do it otherwise) only when you have more
than one type, as when you have only one you would be lacking the template
argument, causing the compiler to give you an error:
template<class T1 = int>
class Useless
{
public:
T1 value;
};
Although the default type for the template class is valid, you can not lack the type
list when instantiating, and that's just why you should only define default arguments
for templates with more than one type (as the argument list would contain at least
one item), as in:
T1 x;
T2 y;
};
In that case, both T1 and T2 would be of type int, and using the single-type type list
is valid.
Note: The default type setting is available only for template classes, functions
do not present this feature, as they already set the defaults, as explained
before.
Implementation [edit]
Now lets get our hands to work on a simple yet useful class, which we'll call Vector.
Not to worry with minor problems such as dynamic memory allocation, which is
needed in this case (to make the Vector grow when needed and optionally make it
shrink when needed), we'll use an imaginary pointer that we believe contains an
allocated array for us to use as a storage.
Our Vector class will have two functions: push and pop. We will also define an
interesting thing we find in STL's std::vector, the iterators (to walk trough the list),
together with iterating functions begin and end.
To reach this goal, we will rely on a template class and some new concepts which
will be explained with the code. This is how it looks:
template<class Type>
class Vector
{
public:
size = 0;
}
~Vector ( void )
{
/* Optionally free the allocated buffer here */
}
size++;
}
Type* data;
This illustrates perfectly just how simple templates really are, now get your hands to
work and, if you know how iterators work, play a little bit with the class, if not, don't
worry, a fast and objective explanation will be given soon. If you got curious about
the typedef we used to define iterator, head to the section relative to it in this
lesson.
Aside: Iterators
Vector<int> v;
Vector<int>::iterator vit;
for ( int i = 0; i < 10; i++ )
{
v.push ( i );
}
Which then prints numbers from 0 to 10 in new lines, sequentially. It also illustrates
the use of iterators to walk trough the list.
As requested by HappyCamper, here is an example of a container template class
called List, that uses the same concept of std::list, the linked list.
template<class Type>
class Node
{
public:
prev = previous;
if ( previous != NULL )
{
previous->next = this;
}
next = NULL;
}
~Node ( void )
{
}
Type value;
Node* prev;
Node* next;
};
template<class Type>
class _List_Iterator
{
public:
_List_Iterator ( void )
{
}
~_List_Iterator ( void )
{
}
return (*this);
}
return (*this);
}
return (*this);
}
Node<Type>* node;
};
template<class Type>
class List
{
public:
~List ( void )
{
Node<Type>* node;
Node<Type>* next;
node = first;
while ( node )
{
next = node->next;
delete node;
node = next;
}
}
if ( first == NULL )
{
first = node;
}
last = node;
}
aux = last;
if ( first == last )
{
first = NULL;
last = NULL;
}
else
{
last = last->prev;
last->next = NULL;
}
delete aux;
}
protected:
Node<Type>* first;
Node<Type>* last;
};
A new iterator class had to be designed in order to overload the operators (to be the
same as our Vector class iterators, in practice). Also notice that, when the template
class instantiated (inside another class) is not of the class type, it requires the
argument list to be written.
Warning: Both of the classes, Vector and List, were written in request-time,
e.g. they didn't go through exhaustive tests to assure its secure execution, it
just illustrates the concept of template containers.
We can also easily design our counterpart of STL's std::pair, which we'll name Pair.
It goes as follows:
Pair ( void )
{
}
~Pair ( void )
{
}
T1 first;
T2 second;
};
A pair is a very simple structure that holds two values (hence the term pair) that may
be of different types. For such achievement we use two arguments in our template.
Function first returns a reference to the first value and, function second, a reference
to the second one.
To be continued
Templates 2
Templates 2 [edit]
Templates can also be used with classes
myClass<char> mc2;
for (int i = 0 ; i < 26 ; i++)
{ mc2.push((char) i+97); }
return 0;
}