thenewboston - C Programming Tutorials (Summary)
This summary is based on this playlist: https://www.youtube.com/watch?v=2NWeucMKrLI&list=PL6gx4Cwl9DGAKIXv8Yr6nhGJ9Vlcjyymq
Tutorial 2:
Naming convention: Project -> capital CamelCase.
Build and run button: converts program to binary(machine language) then runs it.
Tutorial 3 & 4:
Computer program is made of small pieces called functions:
N.B: Each line inside the function is a piece of instruction and the semicolon ”;”
is what indicates the end of this piece of instruction.
is what indicates the end of this piece of instruction.
Tutorial 5:
Commenting : For a paragraph : /* */ For a line //
Tutorial 6: (Conversion Characters :Placehoders)
String = bunch of characters
Examples:
Tutorial 7: Variable: is a placeholder for sth. else. Name convention: small letter/word
Don’t name a variable any basic function (such as: main, printf)
Examples:
Tutorial 8 & 9:
- When you calculate string length or how much memory you need for a string you need a string terminator.
- 13 characters = 14 bytes in memory (extra byte for string terminator)
- When creating/declaring a string we create an array of characters
Examples
Tutorial 10:
Before the program compiles , it runs the preprocessor directives, in other words the code will
take whatever inside the header files (<stdio.h> and <stdlib.h>) and put it & run it before
the code to be compiled. This can be done by include process directive.
Another process directive #define is used with constants (convention: UPPERCASED).
take whatever inside the header files (<stdio.h> and <stdlib.h>) and put it & run it before
the code to be compiled. This can be done by include process directive.
Another process directive #define is used with constants (convention: UPPERCASED).
N.B: Semicolon is not needed after any processor directive
Example:
Create a header file: File>New>Empty File
Name Convention: CapitalCamel case
We made a new header file called BuckysInfo.h which contains this code:
#define MYNAME "Bucky"
#define AGE 28
then in the main file:
Tutorial 11
In order to read data we must use scanf().
Examples:
scanf pauses your program and waits until you press enter.
We need to include this symbol ”&” (ampersand) before any variable except array(array has built-in ampersand) (related to pointers)
Tutorials 12 - 15
Some math & coding hints:
- % - modulus(remainder)
- int divided by int = int. float divided by float = float.
- Whatever is between Parenthesis () is done first.
For example: 4 + 2 *6 = 16 but (4+2)*6 = 48
- number *=1.1; is equivalent to number =number *1.1;
We can assign 3 integers to the same value as follows:
int a;
int b;
int c;
a=b=c=100;
Simple program to calculate the average of 3 persons:
float age1,age2,age3,average;
age1=age2=4.0;
age3=6;
average= (age1+age2+age3)/3;
Tutorial 16 - Typecasting:
Tutorials 17 - 22
if (condition1){
//run code here if condition1 is true
}
if (condition2){
//run code here if condition2 is true
}
if conditions we can use:
Nested if conditions:
if (condition1){
if (condition2){
//run code here if condition1 and condition2 are true
}
}
Hint: Always put space between " and %
If and else conditions:
if (condition1){
//run code here if condition1 is true
}
else {
//run code here if condition1 is false
}
Tutorial 23
You can test if a character is smaller than another example:
if('A'<'B') → true if('D'>'B') → true and so on
N.B: there is a difference between lowercase and uppercase letters.
(condition) ? run code here if condition is true: run code here if condition is false;
Example 1:
(num1>num2) ? printf("num1 > num2"): printf("num1 <= num2");
Example 2:
int friends=1;
printf("I have %d friend%s",friends,(friends!=1) ? "s":"");
If friends =0 the output will be : I have 0 friends
If friends =1 the output will be : I have 1 friend
Tutorial 24
Increment operator(++) example:
Tutorials 25 - 27 loops
While loop:
while(condition){
run code here while condition is true (or until condition is false)
}
Example:
Do- while loop:
do{
run the code here for the first time without checking the condition, then from the second time the code here runs while condition is true (or until condition is false)
}while(condition);
For loop:
we implement for loop to implement a certain code a certain number of times.
for(statement(mostly assignment); condition; statement(mostly increment)){
//your code here
}
Example:
Tutorial 28
How to create a table:
Tutorials 29 - 30
break keyword stops(discontinues) any loop at a certain condition
Example:
continue keyword skips/ignores any code segments after it in a loop.
Example:
Tutorial 31
Switch is alternative to if or if-else statement but it is done to check on one variable.
For example:
Tutorial 32 - 35
isalpha(char character) → checks if a certain character is alphabet
isdigit(char character) → checks if a certain character is a digit
isupper(char character) → checks if a certain character is a uppercase
toupper(char character) → converts a character to uppercase if it is lowercase ,otherwise it will leave it the same.
strcat(char[] string1, char[] string2)→ concatenates/add string2 to string1
N.B: make sure that string1 is big enough to hold the strings to be concatenated.
strcpy(char[] string1, char[] string2)→ replaces the content of string1 with the content of string2 (as if: string1 = string2 , however one array can’t be assigned to another)
We must include the <string.h> header file to use strcat and strcpy functions.
gets(char[] string) → scan input and assign it to string. Better than scanf because it can deal with String separated by space (for example: “Bill Gates”).
puts("Any string") → prints a string with a newline.
Tutorial 36-37
Some functions in the <math.h> library:
ceil(float number) → rounds up a float/double number
floor(float number) → rounds down a float/double number
abs(int number) → gets the absolute of a number (removes -ve sign)
pow(int base, int exponent) → get the base powered by the exponent. (for example: pow(X,Y) gets X power Y as: XY )
sqrt(int number) → gets the square root of a number. (sqrt(int 25) → 25)
rand() → generates a random number.
to generate a random number with a certain range you can use (rand()% rangemax)+1
For example: to get a number between 1 & 6 → (rand()% 6)+1 ,as rand()%6 will give a number between 0 and 5 , then by adding 1 the number will be between 1 & 6.
Tutorials 39-40
Tutorial 41 - Sorting Algorithms
Bubble sorting : the following code keeps swapping elements of the array until it is sorted
Tutorial 42 - pointers
The address of any variable can be accessed by using the symbol & (ampersand). For e.g:
In order to declare a pointer:
Name convention of a pointer is p attached to the variable’s name in capital case.
Tutorial 43 - dereference pointer
if we try to print *pVariable , we will get the value inside the variable that pVariable stores its memory address (this is called dereferencing a pointer). For example:
we can also change the value of variable by changing that of *pVariable.
Summary:
int * pVariable = &variable; This line will do the following:
&pVariable → %p → address of pointer
pVariable → %p → address of variable
*pVariable → %d → access the value of variable
dereferencing:
*pVariable → pVariable address → variable address → value of variable
Tutorial 44
The array name is a pointer for the first element in the array. So by default dereferencing the array name will give the value of the first element. Also dereferencing the array name plus one will get the value of the second element and so on. For example:
Tutorial 45 - Strings and Pointers
The array name is considered to be a constant pointer, therefore after initializing an array we can’t
change its value by directly assigning it to another value because it is as if saying that we want to
change the address of the array neglecting elements inside it so elements stored at a certain
address will be lost (or couldn’t be referred to by any address). For example:
change its value by directly assigning it to another value because it is as if saying that we want to
change the address of the array neglecting elements inside it so elements stored at a certain
address will be lost (or couldn’t be referred to by any address). For example:
However we can do the following:
Tutorial 46
fgets(char *string, int length, FILE * stream) → another way of taking input(instead of scanf()) but with limiting the number of characters entered (so that the program won’t crash ) and with specifying the stream.
For example:
fgets(pString, 20 ,stdin); → this will allow the user to only enter 20 characters via standard input (keyboard).
Tutorial 47 - heap
Heap is a leftover/extra memory that we can borrow whenever we need it and give it back whenever the program ends.
In order to borrow the memory we use: malloc(how much memory do we need?) → allocate memory or get memory from the heap. For example to store 5 integers in the heap we use:
int * points= (int *) malloc (5 * sizeof(int));
Go to the heap reserve place for 5 integers type cast into pointer int then assign it to the int pointer points. N.B: sizeof() gets the size of a certain data type as it may vary across different operating systems or computers.
After we finish using this memory space , we must give it back to the computer using this function: free(points)
Example using heap - let the user enters the size of an array and the elements of that array, then calculate the average:
So what is new here that we created a kind of dynamic array as its size is determined by the user.
Tutorial 49 - Structures
We can use structures to group some variables/attributes under one structure.
For example, We can define a user to have these attributes: id, first name , last name , age and weight. Mainly structures are initialized in header files ,so we can define a structure called user using the word struct in a header file. After defining a struct we can create a new user (struct) and access its members(attributes) in the main file. Check the following table for the implementation:
Tutorial 50 - 53: Files
Files could be accessed in 2 types of ways:
Sequential access file → data created in order.
Random access file → store data all over the place(doesn’t need to be in a specific order).
When dealing with a file we always need a file pointer (FILE * fPointer) to keep track of where we are in the file.
File functions:
- FILE * fopen( const char * filename, const char * mode ) → this function open/create a certain file in the same directory of the main file and do sth. to it depending on the mode ("w" → write, "r" → read, "a" → append).
- int fprintf(FILE *fp,const char *format) → this function prints a text inside a file. It takes the pointer of the file and a string.
- int fclose( FILE *fp )→closes a file and frees memory back to the computer.
- feof(FILE *fp ) → is used to find the end of a file.
- int fseek(FILE *stream, long int offset, int whence) → go to a certain place in the file . stream is the pointer of ther file , offset is the place you want start from (+ve or -ve), whence is from where you want to start(SEEK_SET → beginning of file, SEEK_CUR → Current position of the file pointer, SEEK_END → end of file)
For example:
fseek(fPointer,7,SEEK_SET)→ goes to 7th place in a text from the beginning
fseek(fPointer,-7,SEEK_END)→ goes to 7th place in a text from the end.
Tutorial 54 - 58
The following code demonstrates functions, global & local variables, arguments and return:
The output of the code above will simply be: string
5
nice job, that is a lot of work!
ReplyDeletethis is a 2019-2020 comprehensive c course for beginners: https://youtu.be/iy44Oul230U
Thank you. I'll have a look on this course.
ReplyDelete