by JusApee » 20 Dec 2016, 13:28
C Programming - Course #2
Data Types
ThinkIT! Win 50 FC...First of all, I introduced a couple of questions in the course that I hope you'll be happy to answer as you read it. These questions are not directly answered in the course, but if you think about them for a bit, you'll get the hang of them.
Look around the course for
ThinkITs and answer them. The one who has the most ThinkITs at the end of the course (the entire course, not just course #2) gets 50 FC. If more of you have the maximum amount of ThinkITs, I'll choose two of you with
random.orgPlease comment your answers and try not to copy others' answers. I can figure out who copied who.
What is Data?Data is everything around you. Today's date can be stored in a computer as "data". Your name is "data". Your name, converted into ASCII and added to the radius of the Sun cubed, can be called "data".
So data is basically information. In programming, we have to types of data, based on who is giving out the information:
- INPUT data - the information you provide your computer with in order to solve a certain problem;
- OUTPUT data - the computer's answer to the problem, given your input;
For example, say we have a program that adds two numbers
a and
b. The computer can't know what you're thinking of adding, so you have to tell it: add 5 and 7.
Therefore, the input data for our program would be a = 5 and b = 7. Those values follow the program's instructions, giving us the answer 5+7 = 12. And that would be the output data.
How does that look in code?- Code: Select all
#include <stdio.h> // this is the library taking care of input and output
int main() { // main function getting executed at runtime
int a, b; // our two integers a and b
printf("a: "); // printing out "a:" so we know what we have to insert
scanf("%d", &a); // waiting for you to pass an integer
printf("b: "); // printing out "b:" this time
scanf("%d", &b); // again waiting for passing an integer
printf("a + b = %d", a+b); // finally priting out the result
return 0;
}
Input:
a: 5
b: 7
Output:
a + b = 12
This is an easy problem. The problems you'll have to deal with are going to be much harder than adding two numbers.
So what's a Data Type?We encountered in the
last course the following template of declaring a variable:
- Code: Select all
<DATA TYPE> <VAR NAME> (= <INITIALIZATION VALUE>);
Now, we won't always have to initialize a variable with a value before using it, but be careful:
!! In C, a local variable is AUTOMATICALLY INITIALIZED with a random value of its type existent in the memory taken by that variable.This sounds weird, but let's get an example:
- Code: Select all
#include <stdio.h>
int main() {
int a;
printf("a = %d", a);
return 0;
}
Output:
a = 43
ThinkIT! #1: As you can see, my variable a is not being initialized with any value, but it still outputs an integer. Can 'a' output a real number (float) or a string of random characters if I run the program again (remember 'a' gets reallocated everytime the program is ran, so the value will be different everytime)? Why?
A data type describes what a certain variable is supposed to mean and the eventual restrictions that come with it. The compiler
ALWAYS checks for data-type matching between operators in a written (by you) operation. For example, adding a string "abc" with an integer "3" will result in an error.
In most systems, data can be represented using the following sets of characters:
- letters (a-z, A-Z);
- digits (0-9);
- usual punctuation marks (. ,);
- most of the mathematical symbols (*+-^ etc).
Inside the system, though, data is represented binary. A computer's hardware has two devices which can be found in two distinct physical states. We will call those two physical states
0 and
1. So, we can say that such a device is called a
binary digit or a
bit.
If you have been using the Internet, I think you're more accustomed to the term of
Byte. A Byte is actually 8 bits.
Now, let's enumerate the data types:
- Scalar types:
- arithmetic: int (integer), float (real number: 0.5, 0.58349 etc.);
- character: char (alphanumerical characters + symbols);
- pointer: points to an address of memory of a given type (not today);
- enumeration: enum
- Structured types (not our topic today):
- array
- structure: struct
- union: union
- void - mostly used when working with functions and pointers, it means "nothing" or "anything"
Basic types can be preceded by an attribute:
- short
- long
- signed
- unsigned
Now, let's assume or compiler represents integers with 16 bits of data (we'll stick to this convention during the course, but most systems and compilers can do more than 16 bits). These are a couple of examples of data types that can be declared:
- Code: Select all
int -> 2 Bytes (16 bits) -> values domain: [-32768 ... 32768]
long int -> 4 Bytes (32 bits) -> values domain: [-2147483648 ... 2147483648]
unsigned long int -> 4 Bytes -> values domain: [0 ... 4294967295]
char -> 1 Byte -> values domain: [-128 ... 127]
Do I have to memorize all these values? Operator sizeof().No, obviously not. The operator
sizeof() will do the job for you. We know from the above chart that an int takes up 2 Bytes of memory.
Let's call
sizeof(int). The output will be 2. So we can say that the operator sizeof() gives us the dimension of a certain type in Bytes.
- Code: Select all
printf("int is represented on %d bytes\n", sizeof(int));
printf("long int is represented on %d bytes\n", sizeof(long int));
printf("Value %d is represented on %d bytes\n", 1 + 2, sizeof(1+2));
Output:
int is represented on 2 bytes
long int is represented on 4 bytes
Value 3 is represented on 2 bytes
ThinkIT! #2: Why is value 3 represented on 2 Bytes of memory?
Reading or Writing variablesReading or writing variables can be achieved using
stdio's standard in/out functions
printf, scanf.
1. Reading a variableReading a variable can be done using the built-in function:
scanf.
scanf() has the following syntax:
- Code: Select all
scanf(FORMAT, <VARIABLE ADDRESS>);
At first, this won't tell you much, and I'm not going to explain you why you need the variable's address yet. I'll keep this for the Pointer course.
As for the FORMAT parameter, it is represented by a string (strings are char arrays).
Format strings are different for every data type, so a list of every format is:
- %d - decimal number format, used to read a decimal (usually integer) number
- %l - long decimal
- %f - float real number (1.352, 3.14 etc)
- %c - character
- %s - string
- %lf - long float
- %x - hexadecimal (base 16)
- %o - octal (base 8)
- %u - unsigned
!! Not using the proper format may result in ugly errors or incorrect answers even if the algorithm itself is working properly. The errors generated by an incorrect format are HARD to detect. Be careful!Additionally, the float format can be accustomed to your needs. For example, if you only need a 2 zecimals long float, the format is modified like this:
[*]
%.2fExample of reading a value for our integer 'a':
- Code: Select all
scanf("%d", &a); // note that putting & before the variable name gives us its address
ThinkIT! #3: What happens if you instead use the following line to read the variable 'a'? Does it work? Why?
- Code: Select all
scanf("a = %d", &a);
2. Printing a variableTo print a variable, we use
printf. The syntax for this function is:
- Code: Select all
printf(FORMAT, <VARIABLE>); // NOT VARIABLE ADDRESS
Printing is the exact same thing as reading, but it does not require a memory address in order to print a variable. It just requires its value. So as an example:
- Code: Select all
int a = 5;
printf("a is equal to %d", a);
// Output:
// a is equal to 5
Float NumbersFloat numbers are real numbers, not just integers. There are two types of real number data types:
- float - has a precision of 7 zecimals
- double - has a precision of 16 decimals (hence the type's name)
Char typeIn C, characters are no different than numbers. Every character is coded into a code called ASCII, therefore:
- Code: Select all
char c = 'a';
char c2 = 97;
printf("c:%c \nc2:%c", c, c2);
// Output:
// c: a
// c2: a
As you can see, by assigning c2 the number 97 (even if it's a char), we can output the character 'a'. Why is that? Because when we assigned the value 97 to the char, we actually assigned the 97th character from the ASCII table. 97 is the character 'a's ASCII code.
Characters support comparisons, meaning that we can make sense of things like:
- Code: Select all
c >= 'a' || c <= 'z'
(meaning that our character has to be a small letter).
Let's now talk about some commonly used constant special characters. We use these characters in formatting strings or text.
- \n - I used this one in the example above. It simply inserts a new line (enter) where it is placed. That's why the Output in my example was on a new line.
- \b - Used to go back one character. This does not remove a character, but instead moves the typing cursor on the previous character's slot. For instance, if we have the string "string_example101\b2" and we print that out, the output will be "string_example102", because \b moves the typing cursor on the last '1' in the string and then types a 2 over it.
- \t - Horizontal tab (indentation)
- \v - Vertical tab
- \\ - character '\'
- \' - character "'"
- \" - character '"'
Constant strings are written in quotation marks: "Constant String".
A little bit of insight... Pointer Type- Code: Select all
int a, b;
int* p; // this line defines a variable p of type int* (int* is read "pointer to int")
a = 10; // assigns a the value of 10
p = &a; // now p is assigned a's address, because a pointer POINTS towards an address of memory
b = *p; // b is assigned the value at the address that p points at
As I said above, when we need a variable's address, we put & before it, therefore p = &a is a correct operation. Imagine pointers as a finger pointing towards a house. That house has an address. At that address, we can find a family (the value of the address). So what does a pointer actually store? It stores the address of the house. If we want the family name (value) of that address, we have to put a * before the pointer's name. That's why b = *p makes sense. Our b is an integer and it stores an integer value, not an address, so in order for that to make sense, we need to give it p's value, *p.
A pointer is defined using the same data type that it is going to point at. We can't point an integer pointer to a float, for example. We define pointers to a type by adding an * to the data type.
- Code: Select all
int* p;
char *q; // the * doesnt have to be written together with the data type. it just has to exist somewhere between the data type and variable name
I personally preffer writing the * next to the variable name, so I can see clearly that it's a pointer. If we have for example:
- Code: Select all
int* p, q, r;
Which one is the pointer in this situation?
- [+] Spoiler
- p is the pointer, because it has an asterisk. Even though every variable appears to be of type int*, the asterisk only applies to the first one. That's why I always type pointer defining like this:
- Code: Select all
int *p, *q, r;
Now it is clear that p and q are pointers, while r is an integer.
So that's basically it, pointers store an address of memory. We will see why is that useful in the next courses.
In the end...Thank you again for reading, I hope I made myself clear about these data types. It's not really a big deal, but if you have any unclear things after reading this you're free to ask in the comments.
Have a nice day!
[center][size=200]C Programming - Course #2 [/size][/center]
[center][size=150]Data Types[/size][/center]
[size=150]ThinkIT! Win 50 FC...[/size]
First of all, I introduced a couple of questions in the course that I hope you'll be happy to answer as you read it. These questions are not directly answered in the course, but if you think about them for a bit, you'll get the hang of them.
Look around the course for [i][b]ThinkIT[/i][/b]s and answer them. The one who has the most ThinkITs at the end of the course (the entire course, not just course #2) gets 50 FC. If more of you have the maximum amount of ThinkITs, I'll choose two of you with [url=http://random.org]random.org[/url]
Please comment your answers and try not to copy others' answers. I can figure out who copied who.
[size=150]What is [u]Data[/u]?[/size]
Data is everything around you. Today's date can be stored in a computer as "data". Your name is "data". Your name, converted into ASCII and added to the radius of the Sun cubed, can be called "data".
So data is basically information. In programming, we have to types of data, based on who is giving out the information:
[list]
[*] [b]INPUT[/b] data - the information you provide your computer with in order to solve a certain problem;
[*] [b]OUTPUT[/b] data - the computer's answer to the problem, given your input;[/list]
For example, say we have a program that adds two numbers [b]a[/b] and [b]b[/b]. The computer can't know what you're thinking of adding, so you have to tell it: add 5 and 7.
Therefore, the input data for our program would be a = 5 and b = 7. Those values follow the program's instructions, giving us the answer 5+7 = 12. And that would be the output data.
[b]How does that look in code?[/b]
[code]
#include <stdio.h> // this is the library taking care of input and output
int main() { // main function getting executed at runtime
int a, b; // our two integers a and b
printf("a: "); // printing out "a:" so we know what we have to insert
scanf("%d", &a); // waiting for you to pass an integer
printf("b: "); // printing out "b:" this time
scanf("%d", &b); // again waiting for passing an integer
printf("a + b = %d", a+b); // finally priting out the result
return 0;
}
Input:
a: 5
b: 7
Output:
a + b = 12
[/code]
This is an easy problem. The problems you'll have to deal with are going to be much harder than adding two numbers.
[size=150]So what's a Data Type?[/size]
We encountered in the [url=http://forumcoin.com/viewtopic.php?f=67&t=14607]last course[/url] the following template of declaring a variable:
[code]<DATA TYPE> <VAR NAME> (= <INITIALIZATION VALUE>);[/code]
Now, we won't always have to initialize a variable with a value before using it, but be careful:
[b]!![/b][i] In C, a local variable is AUTOMATICALLY INITIALIZED with a random value of its type existent in the memory taken by that variable.[/i]
This sounds weird, but let's get an example:
[code]
#include <stdio.h>
int main() {
int a;
printf("a = %d", a);
return 0;
}
Output:
a = 43
[/code]
[i][b]ThinkIT! #1[/i][/b]: As you can see, my variable a is not being initialized with any value, but it still outputs an integer. Can 'a' output a real number (float) or a string of random characters if I run the program again (remember 'a' gets reallocated everytime the program is ran, so the value will be different everytime)? Why?
A data type describes what a certain variable is supposed to mean and the eventual restrictions that come with it. The compiler [i]ALWAYS[/i] checks for data-type matching between operators in a written (by you) operation. For example, adding a string "abc" with an integer "3" will result in an error.
In most systems, data can be represented using the following sets of characters:
[list]
[*] letters (a-z, A-Z);
[*] digits (0-9);
[*] usual punctuation marks (. ,);
[*] most of the mathematical symbols (*+-^ etc).[/list]
Inside the system, though, data is represented binary. A computer's hardware has two devices which can be found in two distinct physical states. We will call those two physical states [b]0[/b] and [b]1[/b]. So, we can say that such a device is called a [i]binary digit[/i] or a [i]bit[/i].
If you have been using the Internet, I think you're more accustomed to the term of [b]Byte[/b]. A Byte is actually 8 bits.
Now, let's enumerate the data types:
[list]
[*] Scalar types:
[list]
[*] arithmetic: int (integer), float (real number: 0.5, 0.58349 etc.);
[*] character: char (alphanumerical characters + symbols);
[*] pointer: points to an address of memory of a given type (not today);
[*] enumeration: enum
[/list]
[*] Structured types (not our topic today):
[list]
[*] array
[*] structure: struct
[*] union: union
[/list]
[*] [i]void[/i] - mostly used when working with functions and pointers, it means "nothing" or "anything" [/list]
Basic types can be preceded by an attribute:
[list]
[*] short
[*] long
[*] signed
[*] unsigned [/list]
Now, let's assume or compiler represents integers with 16 bits of data (we'll stick to this convention during the course, but most systems and compilers can do more than 16 bits). These are a couple of examples of data types that can be declared:
[code]
int -> 2 Bytes (16 bits) -> values domain: [-32768 ... 32768]
long int -> 4 Bytes (32 bits) -> values domain: [-2147483648 ... 2147483648]
unsigned long int -> 4 Bytes -> values domain: [0 ... 4294967295]
char -> 1 Byte -> values domain: [-128 ... 127]
[/code]
[size=150]Do I have to memorize all these values? Operator sizeof().[/size]
No, obviously not. The operator [b]sizeof()[/b] will do the job for you. We know from the above chart that an int takes up 2 Bytes of memory.
Let's call [b]sizeof(int)[/b]. The output will be 2. So we can say that the operator sizeof() gives us the dimension of a certain type in Bytes.
[code]
printf("int is represented on %d bytes\n", sizeof(int));
printf("long int is represented on %d bytes\n", sizeof(long int));
printf("Value %d is represented on %d bytes\n", 1 + 2, sizeof(1+2));
Output:
int is represented on 2 bytes
long int is represented on 4 bytes
Value 3 is represented on 2 bytes
[/code]
[b][i]ThinkIT! #2[/b][/i]: Why is value 3 represented on 2 Bytes of memory?
[size=150]Reading or Writing variables[/size]
Reading or writing variables can be achieved using [i]stdio[/i]'s standard in/out functions [i][b]printf, scanf[/b][/i].
[b]1. Reading a variable[/b]
Reading a variable can be done using the built-in function: [i]scanf[/i].
scanf() has the following syntax:
[code]
scanf(FORMAT, <VARIABLE ADDRESS>);
[/code]
At first, this won't tell you much, and I'm not going to explain you why you need the variable's address yet. I'll keep this for the Pointer course.
As for the FORMAT parameter, it is represented by a string (strings are char arrays).
Format strings are different for every data type, so a list of every format is:
[list]
[*] [b]%d[/b] - decimal number format, used to read a decimal (usually integer) number
[*] [b]%l[/b] - long decimal
[*] [b]%f[/b] - float real number (1.352, 3.14 etc)
[*] [b]%c[/b] - character
[*] [b]%s[/b] - string
[*] [b]%lf[/b] - long float
[*] [b]%x[/b] - hexadecimal (base 16)
[*] [b]%o[/b] - octal (base 8)
[*] [b]%u[/b] - unsigned[/list]
[b]!![/b] [i]Not using the proper format may result in ugly errors or incorrect answers even if the algorithm itself is working properly. The errors generated by an incorrect format are HARD to detect. Be careful![/i]
Additionally, the float format can be accustomed to your needs. For example, if you only need a 2 zecimals long float, the format is modified like this:
[*] [b]%.2f[/b]
Example of reading a value for our integer 'a':
[code]
scanf("%d", &a); // note that putting & before the variable name gives us its address
[/code]
[b][i]ThinkIT! #3[/i][/b]: What happens if you instead use the following line to read the variable 'a'? Does it work? Why?
[code]
scanf("a = %d", &a);
[/code]
[b]2. Printing a variable[/b]
To print a variable, we use [i]printf[/i]. The syntax for this function is:
[code]
printf(FORMAT, <VARIABLE>); // NOT VARIABLE ADDRESS
[/code]
Printing is the exact same thing as reading, but it does not require a memory address in order to print a variable. It just requires its value. So as an example:
[code]
int a = 5;
printf("a is equal to %d", a);
// Output:
// a is equal to 5
[/code]
[size=150]Float Numbers[/size]
Float numbers are real numbers, not just integers. There are two types of real number data types:
[list]
[*] [b]float[/b] - has a precision of 7 zecimals
[*] [b]double[/b] - has a precision of 16 decimals (hence the type's name)[/list]
[size=150]Char type[/size]
In C, characters are no different than numbers. Every character is coded into a code called ASCII, therefore:
[code]
char c = 'a';
char c2 = 97;
printf("c:%c \nc2:%c", c, c2);
// Output:
// c: a
// c2: a
[/code]
As you can see, by assigning c2 the number 97 (even if it's a char), we can output the character 'a'. Why is that? Because when we assigned the value 97 to the char, we actually assigned the 97th character from the ASCII table. 97 is the character 'a's ASCII code.
Characters support comparisons, meaning that we can make sense of things like:
[code]c >= 'a' || c <= 'z'[/code]
(meaning that our character has to be a small letter).
Let's now talk about some commonly used constant special characters. We use these characters in formatting strings or text.
[list]
[*] [b]\n[/b] - I used this one in the example above. It simply inserts a new line (enter) where it is placed. That's why the Output in my example was on a new line.
[*] [b]\b[/b] - Used to go back one character. This does not remove a character, but instead moves the typing cursor on the previous character's slot. For instance, if we have the string "string_example101\b2" and we print that out, the output will be "string_example102", because \b moves the typing cursor on the last '1' in the string and then types a 2 over it.
[*] [b]\t[/b] - Horizontal tab (indentation)
[*] [b]\v[/b] - Vertical tab
[*] [b]\\[/b] - character '\'
[*] [b]\'[/b] - character "'"
[*] [b]\"[/b] - character '"'[/list]
Constant strings are written in quotation marks: "Constant String".
[size=150]A little bit of insight... Pointer Type[/size]
[code]
int a, b;
int* p; // this line defines a variable p of type int* (int* is read "pointer to int")
a = 10; // assigns a the value of 10
p = &a; // now p is assigned a's address, because a pointer POINTS towards an address of memory
b = *p; // b is assigned the value at the address that p points at
[/code]
As I said above, when we need a variable's address, we put & before it, therefore p = &a is a correct operation. Imagine pointers as a finger pointing towards a house. That house has an address. At that address, we can find a family (the value of the address). So what does a pointer actually store? It stores the address of the house. If we want the family name (value) of that address, we have to put a * before the pointer's name. That's why b = *p makes sense. Our b is an integer and it stores an integer value, not an address, so in order for that to make sense, we need to give it p's value, *p.
A pointer is defined using the same data type that it is going to point at. We can't point an integer pointer to a float, for example. We define pointers to a type by adding an * to the data type.
[code]
int* p;
char *q; // the * doesnt have to be written together with the data type. it just has to exist somewhere between the data type and variable name
[/code]
I personally preffer writing the * next to the variable name, so I can see clearly that it's a pointer. If we have for example:
[code]
int* p, q, r;
[/code]
Which one is the pointer in this situation?
[spoiler]p is the pointer, because it has an asterisk. Even though every variable appears to be of type int*, the asterisk only applies to the first one. That's why I always type pointer defining like this:
[code]
int *p, *q, r;
[/code]
Now it is clear that p and q are pointers, while r is an integer.[/spoiler]
So that's basically it, pointers store an address of memory. We will see why is that useful in the next courses.
[size=150]In the end...[/size]
Thank you again for reading, I hope I made myself clear about these data types. It's not really a big deal, but if you have any unclear things after reading this you're free to ask in the comments.
Have a nice day!