Congrats. You are one tutorial closer in the wonderful world of programming. Up to now, you should be somewhat comfortable with CodeBlocks, and have a very basic understanding of how a program works. In this tutorial we are going to look at something called variables.
A variable in the programming world is a special type of container that can hold a value. This container is then stored in memory with its value. In other words, your program can make a request to the operating system to store a value into memory, and then later on, it can request that value back at any time. This is useful for a lot of reasons, especially when you need to do calculations.
There are several types of values you can store into memory. Here's a list of some of them:
| Keyword |
Type |
Size* |
| char |
Character/Small Integer |
1 Byte |
| short int |
Short Integer |
2 Bytes |
| int |
Integer |
4 Bytes |
| long int |
Long Integer |
4 Bytes |
| long long int |
Long Integer (64-bits) |
8 Bytes |
| float |
Single-precision floating point value |
4 Bytes |
| double |
Double-precision floating point value |
8 Bytes |
*Please note that the sizes listed here are simply for reference and based upon commonality. Some machines are different.
So what does this table mean really? Well, each variable keyword can basically hold a certain size, or, in other words, each variable keyword says how much memory we are going to take up. So, for example, if we wanted to store the user's age into a variable, a good choice would be short int. Why? Because short int doesn't take up very much memory, and we don't expect people to start living to thousands of years of age anytime soon. But lets say we are storing the average age between 10 people, and lets say the average we come up with is 20.7. We would use a float type to store this value because floats can store decimals (that is what "floating point value" means). Look at it this way:
Can hold integer values:
char, short int, int, long int, long long int
Can hold floating point values:
float, double
Those that hold integer values have nothing different between them other than the amount of data they can store. Same goes for floating point types. Take a look at the chart again, but this time with limits in place:
| Keyword |
Type |
Size |
| char |
Character/Small Integer |
0 - 255 |
| short int |
Short Integer |
0 to 65535 |
| int |
Integer |
0 to 4294967295 |
| long int |
Long Integer |
0 to 4294967295 |
| long long int |
Long Integer (64-bits) |
0 to 18446744073709551615 |
| float |
Single-precision floating point value |
+/- 3.4e +/- 38 (~7 digits) |
| double |
Double-precision floating point value |
+/- 1.7e +/- 308 (~15 digits) |
(Please note table data was taken from http://www.cplusplus.com/doc/tutorial/variables/ and http://home.att.net/~jackklein/c/inttypes.html#long_long).
You can see, depending on what you need to store into memory, you can choose the appropriate data type. We don't want our program to take up all memory on the system, so we must choose the appropriate data types. Notice that int and long int are shown as the same. As I mentioned above, not all systems set these sizes / ranges the same, long int may actually be larger than int on some systems. Also, please note that char, though a rather small integer type, is special in the regard that is can hold characters (letters, and such). We'll get into that aspect in later tutorials.
So why is this all important? First, we need to know our limitations when dealing with data. Secondly, we need to know which data types to use when we do need to store data.
If you notice from the table above there doesn't seem to be a way to hold negative values. C++ deals with this by introducing two keywords called unsigned / signed. Unsigned means the data type will only hold positive values (including 0). Signed means the data type can hold negative and positive values, but when you make a variable signed, that effectively cuts the positive range in half. For example:
signed char
Range: -128 to 127
unsigned char
Range: 0 to 255
You see what happened there? In order to accommodate negative values we had to give up half of our possible positive values.
Also, to make a further note on this, all data types except for char are signed by default (meaning they can hold negative and positive values). A char can be signed or unsigned depending on the compiler involved, this is because a char is usually used to hold characters (which are all positive numbers) - most of the time you'll find a char is unsigned by default.
So enough fuss, lets get to some coding to show you how to use this new information. Load up CodeBlocks like you did the last tutorial, create a new project, and empty file (if you need help on that please look at the first C++ tutorial). Then, from memory if you can, try to code out the bare bones of your program:
#include <iostream>
int main() {
return 0;
}
We are going to make a simple program that will hold your age, and your age in dog years (boring, yes, I know). So, we'll use a short int for the person's age, and a float for the average. Why didn't I use a char for the person's age? Well, this is related to what I briefly said about characters. When cout / printf, or other functions that print text to the screen see a char come across, they will print the corresponding character instead of the value. You can see what I mean by this example:
char X = 97 ;
std::cout << X;
Instead of printing 97 like you would want, it actually prints 'a'. Again, char is sort of a special data type that is really meant for characters. Please note there are ways to force the program to print the value instead of a char, but we won't get into that.
So, back to the program, we have an int and float. Lets put that into our program:
#include <iostream>
int main() {
int Age = 0;
float AgeInDogYears = 0;
return 0;
}
Notice what's going on here. We first declare our data type, then a name for our variable, and then give it an initial value. You can make the name of the variable whatever you want. For instance, I could have put:
int TimothysAge = 0;
Note that a variable name must begin with a character or underscore _, but after the first character it can contain numbers. These variable names are all valid:
int _Age;
int Age;
int Age1;
int aGE;
These variable names are not valid:
int 1Age;
int !Age;
So, now that we have our variables made, lets make them do something. Set the variable "Age" to your actual age. For me, I would do:
#include <iostream>
int main() {
int Age = 23;
float AgeInDogYears = 0;
return 0;
}
Now, just like in school, we can also create equations and perform math. We know that a person's age in Dog years is actually the person's age divided by 7.
#include <iostream>
int main() {
int Age = 23;
float AgeInDogYears = Age / 7;
return 0;
}
You see what I did there? I was able to use the Age variable and treat it like a number. So when our program comes to the AgeInDogYears line, it will look up the value of Age (23), and divide it by 7. Lets actually make this value print out now:
#include <iostream>
int main() {
int Age = 23;
float AgeInDogYears = Age / 7;
std::cout << "My age in dog years: " << AgeInDogYears;
return 0;
}
Look at what we did with cout. First, we print out a normal string (like we did in the first tutorial), but then notice we used another double arrow << to also print out AgeInDogYears. When we use cout that mixes strings and variables, you have to use multiple << to separate the two. For example, these are valid ways to use cout:
std::cout << "Your age " << Age << " in dog years is " << AgeInDogYears;
These are wrong / invalid ways of using cout:
std::cout << "You are Age years old"; //Will actually say "Age" instead of printing the value of Age
std::cout << "You are " Age " years old"; //Syntax error
std::cout << "You are " + Age + " years old"; //Syntax error
Now, take our code above and compile it. You should see it print out the correct number (for me that number is 3). But notice something, even though we used a float to hold decimal numbers, our value is not showing decimal numbers (unless you age is exactly divisible by 7). My age in dog years should really be 3.28571. Look back at this line:
float AgeInDogYears = Age / 7;
Look at the number 7. When the system comes across hard-coded numbers in your program it treats them one of two ways, as integers or floating point numbers. The way it distinguinshes between them is if a decimal is used on the number of not:
Treated as integer
7
Treated as floating point
7.0
So, when our age in dog years is calculated, the decimal number is automatically dropped because 7 is treated like an integer. In any division operations, the denominator always determines the end data type. So, if the numerator is an integer value and the denominator is a floating point value, we'll end up with a floating point value. But, if it was the other way around, with a floating point as the numerator and an integer as the denominator, we'd up with an integer. Example:
int X = 7.0 / 3; // Equals 2
int X = 7 / 3.0 // Equals 2.33333
So, lets modify our program to fix this floating point issue:
#include <iostream>
int main() {
int Age = 23;
float AgeInDogYears = Age / 7.0;
std::cout << "My age in dog years: " << AgeInDogYears;
return 0;
}
I will end this tutorial on this final note. You can perform all mathematical operations on variables and hard-coded values. These operations are:
Multiplication
*
Division
/
Addition
+
Subtraction
-
You can also use parenthesis like in algebra to group operations:
int X = 5;
int Y = (X * X) * 5;
Play around with some equations and try to get used to them.
Congrats! We've successfully used variables. We'll be using them a lot in up coming tutorials so try to get a firm grasp on how they are used, the subtle differences between them.
Email (required, not published):
Website:
Email (required, not published):
Website:
"Nunca definir una función sin parámetros de entrada, vuelve a quien lea dicha función medio loco queriendo entender qué quiso realmente poner ahí".
Partiendo de este principio fundamental que se aplica muchísimo en software libre, recomiendo que cambies
int main () {
por
int main(void)
{
Las llaves deberían estar alineadas para que no haya problemas identificando "zonas". No entiendo la manía que tienen los programas que automatizan funciones estilo XCode o Codeblocks de ponerlo de forma errónea. Provoca confusión y hace que programadores que no deben perder tiempo entendiendo "qué quiso decir con esto" lo pierdan de forma inútil.
Corrígelo y mi próximo post lo pongo en inglés.
Email (required, not published):
Website:
Email (required, not published):
Website:
Email (required, not published):
Website:
No pienso poner esto en inglés, si me molesto en aprender el idioma de otros, sería lo mínimo que esos otros aprendiesen mi idioma.
Mi respuesta viene a ser lo que se define como "estilo" en cuanto a escribir en C/C++.
Más importante que aprender C++ es aprender a hacer una única y sola manera de escribir en C/C++. Estoy harto de ver códigos de gente que de forma idiota no tiene un estilo definido de escritura, y uno se tiene que romper la cabeza entendiendo qué quiso poner el programador original ahí.
Nada de "si funciona tal y como está, se deja así, sin tocar", eso es lo primero que en cualquier trabajo de programador provocaría que te echasen a la calle.
Hay miles de estilos, Geany, por ejemplo, tiene su propio estilo a la hora de querer añadir herramientas a su programa, y no acepta código que esté hecho con otro estilo.
Antes que enseñar C/C++, deberías definir qué codigo usas tú.
Por que alguien que lee algo que fue escrito por un escritor famoso (introducir el nombre que se quiera) no puede comparar, en cuanto a estilo de escritura, por alguien no tan famoso que hizo una obra similar.
Si quieres que la gente aprenda a programar, enséñales "qué quieren hacer" con ese código y luego, cómo hacerlo. Hacer eso al revés, tal y como está hecho aquí, es como construir la casa por el tejado.
Un saludo para todos los hispano-hablantes.
PD: Sufro viendo como alguien que no sabe inglés trata de hacer un estropicio usando el traductor de Google. Que alguien que habla inglés sufra también nuestra pena.
Email (required, not published):
Website:
Email (required, not published):
Website:
Email (required, not published):
Website: