Académique Documents
Professionnel Documents
Culture Documents
1. Learn C in a Minutes ........................................................................................................................ 2 2. Relational Operators, Logical Operators, If, Else, Else If, Conditional Operator, Bits, Bytes, Looping ..................................................................................................................................................... 5 3. Switch, Strings, Arrays and more.................................................................................................... 8 4. Pointers, Arrays and Functions ..................................................................................................... 12 5. All About Structs ............................................................................................................................. 15 6. Structs, Unions, Enums, Linked Lists and Recursice Structures............................................... 18 7. Messing with Strings, Chars, Booleans, Functions & Pointers .................................................. 21 8. How to Dynamically Allocate Memory with malloc() ................................................................. 22 9. Working with Struct Linked Lists ................................................................................................. 25 10. 11. 12. 13. 14. Working with Struct Linked Lists (2) ........................................................................................ 27 Text I/O File .................................................................................................................................. 30 Binary File I/O & Error Handling with C ................................................................................. 32 Converting from Base 10 to Base 2, 8 and 16 ............................................................................ 34 Convert from Others Base to Base 10 ........................................................................................ 36
15. Passing Memory Addresses, Bitwise Operators, Signed Integers, Shift Operators, Twos Compliment, Bit Masking ..................................................................................................................... 38
Tutorial_1_2
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MYNAME "Hoang Nhu Vinh" int globalVar = 100; int main() { char middleInitial; printf("What is your middle initial?\n\n"); scanf("%c",&middleInitial); printf("Middle initial is %c\n\n", middleInitial); char firstName[30], lastName[30]; printf("What is your first name\n"); scanf("%s",firstName); printf("What is your last name\n"); scanf("%s",lastName); //printf("Your name is %s &c %s \n\n",firstName,middleInitial,lastName); int month,day,year; printf("What's your birth date?\n"); scanf("%d%d%d", &month,&day,&year); return 0; }
2. Relational Operators, Logical Operators, If, Else, Else If, Conditional Operator, Bits, Bytes, Looping Tutorial_2
#include <stdio.h> void main(){ printf("\n"); int num1 = 1, num2 = 2; printf("Is 1 > 2 : %d\n\n",num1 > num2); if(num1 > num2){ printf("%d is greater then %d\n\n", num1, num2); } else if(num1 < num2){ printf("%d is less then %d\n\n", num1, num2); } else { printf("%d is equal to %d\n\n", num1, num2); } int custAge = 38; if(custAge > 21 && custAge < 35) printf("They are welcome\n\n"); else printf("They are not welcome\n\n"); printf("! turns a true into false : %d\n\n", !1); int bobMissedDays = 8, bobTotalSales = 24000, bobNewCust = 32; if(bobMissedDays < 10 && bobTotalSales > 30000 || bobNewCust > 30){ printf("Bob gets a raise\n\n"); } else { printf("Bob doesn't get a raise\n\n"); } char* legalAge = (custAge > 21) ? "true" : "false"; printf("Is the customer of legal age? %s\n\n", legalAge); int numOfProducts = 10; printf("I bought %s products\n\n", (numOfProducts > 1) ? "many" : "one"); printf("A char takes up %d bytes\n\n", sizeof(char)); printf("An int takes up %d bytes\n\n", sizeof(int)); printf("A long int takes up %d bytes\n\n", sizeof(long int)); printf("A float takes up %d bytes\n\n", sizeof(float)); printf("A double takes up %d bytes\n\n", sizeof(double)); int bigInt = 2147483648; printf("I'm bigger then you may have heard %d\n\n", bigInt); int numberHowBig = 0; printf("How Many Bits? "); scanf(" %d", &numberHowBig); printf("\n\n"); int myIncrementor = 1, myMultiplier = 1, finalValue = 1; while(myIncrementor < numberHowBig){ myMultiplier *= 2; finalValue = finalValue + myMultiplier; printf("finalValue: %d myMultiplier: %d myIncrementor: %d\n\n", finalValue, myMultiplier, myIncrementor); myIncrementor++; } if ((numberHowBig == 0) || (numberHowBig == 1)){
printf("Top Value: %d\n\n", numberHowBig); } else { printf("Top Value: %d\n\n", finalValue); } int secretNumber = 10, numberGuessed = 0; while(1){ printf("Guess My Secret Number: "); scanf(" %d", &numberGuessed); if(numberGuessed == 10){ printf("You Got It"); break; } } printf("\n\n"); char sizeOfShirt; do { printf("What Size of Shirt (S,M,L): "); scanf(" %c", &sizeOfShirt); } while(sizeOfShirt != 'S' && sizeOfShirt != 'M' && sizeOfShirt != 'L'); for(int counter = 0; counter <= 20; counter++){ printf("%d ", counter); } printf("\n\n"); for(int counter = 0; counter <= 40; counter++){ if((counter % 2) == 0) continue; printf("%d ", counter); } }
Tutorial_3_2
#include <stdio.h> #include <string.h> int void main(){ printf("\n"); char wholeName[12] = "Derek Banas"; int primeNums[3] = {2, 3, 5,}; int morePrimes[] = {13, 17, 19, 23}; printf("The first prime in the list is %d\n\n", primeNums[0]); char city[7] = {'C', 'h', 'i', 'c', 'a', 'g', 'o'}; char anotherCity[5] = {'E', 't', 'n', 'a', '\0'}; printf("A City %s\n\n", anotherCity); char thirdCity[] = "Paris"; char yourCity[30]; printf("What city do you live in? "); fgets(yourCity, 30, stdin); printf("Hello %s\n\n", yourCity); int i1; for(i1 = 0; i1 < 30; i1++){ if(yourCity[i1] == '\n'){ yourCity[i1] = '\0'; break; } } printf("Hello %s\n\n", yourCity); printf("Is your city Paris? %d\n\n", strcmp(yourCity, thirdCity));
char yourState[] = ", Pennsylvania"; strcat(yourCity, yourState); printf("You live in %s\n\n", yourCity); printf("Letters in Paris : %d\n\n", strlen(thirdCity)); strcpy(yourCity, "El Pueblo del la Reina de Los Angeles"); printf("The new name is %s\n\n", yourCity); }
Tutorial_3_3
#include <stdio.h> // Needed for exit(), rand() #include <stdlib.h> int globalVar = 0; int addTwoInts(int num1, int num2){ return num1 + num2; } void changeVariables(){ int age = 40; printf("age inside of function = %d\n\n", age); globalVar = 100; printf("globalVar inside of function = %d\n\n", globalVar); } void main(){ int total = addTwoInts(4,5); printf("The Sum is %d\n\n", total); int age = 10; globalVar = 50; printf("age before a call to the function = %d\n\n", age); printf("globalVar before a call to the function = %d\n\n", globalVar);
10
changeVariables(); printf("age after a call to the function = %d\n\n", age); printf("globalVar after a call to the function = %d\n\n", globalVar); }
11
12
Tutorial_4_2
#include <stdio.h> #include <stdlib.h> void generateTwoRandomNums(int rand1, int rand2){ rand1 = rand() % 50 + 1; rand2 = rand() % 50 + 1; printf("New rand1 in function = %d\n\n", rand1); printf("New rand2 in function = %d\n\n", rand2); } void pointerRandomNumbers(int* rand1, int* rand2){ *rand1 = rand() % 50 + 1; *rand2 = rand() % 50 + 1; printf("New rand1 in pointer function = %d\n\n", *rand1); printf("New rand2 in pointer function = %d\n\n", *rand2); } void editMessageSent(char* message, int size){ char newMessage[] = "New Message"; if(size > sizeof(newMessage)){ int i ; for(i = 0; i < sizeof(newMessage); i++){ message[i] = newMessage[i]; } } else { printf("New Message is to big\n\n"); } } void main(){ int rand1 = 0, rand2 = 0; generateTwoRandomNums(rand1, rand2); printf("rand1 = %d\n\n", rand1); printf("rand2 = %d\n\n", rand2); rand1 = 0, rand2 = 0; printf("Main Before Function Call\n\n"); printf("rand1 = %d : rand2 = %d\n\n", rand1, rand2); pointerRandomNumbers(&rand1, &rand2); printf("Main After Function Call\n\n"); printf("rand1 = %d : rand2 = %d\n\n", rand1, rand2); char randomMessage[] = "Edit my function"; printf("Old Message: %s \n\n", randomMessage); editMessageSent(randomMessage, sizeof(randomMessage)); printf("New Message: %s \n\n", randomMessage); }
13
14
15
Tutorial_5_2
#include <stdio.h> #include <stdlib.h> struct dogsFavs { char *food; char *friends; }; typedef struct dog { const char *name; const char *breed; int avgHeightCm; int avgWeightLbs; struct dogsFavs favoriteThings; } dog; void getDogsFavs(dog theDog) { printf("\n"); printf("%s loves %s and his friend is %s\n", theDog.name,theDog.favoriteThings.food,theDog.favoriteThings.friends); } void setDogWeightPtr(dog *theDog, int newWeight) { theDog->avgWeightLbs = newWeight; printf("New weight is : %d\n\n", theDog->avgWeightLbs);
16
} int main() { dog benji = {"Benji","Silky",90,180,{"Meat","Joe Camp"}}; getDogsFavs(benji); setDogWeightPtr(&benji,60); printf("Wieght in the main is: %d", benji.avgWeightLbs); return 0; }
17
18
Tutorial_6_2
#include <stdio.h> #include <stdlib.h> typedef struct product { const char *name; float price; struct product *next; } product; void printLinkedList(product *pProduct) { while (pProduct != NULL) { printf("A %s costs %.2f\n\n", pProduct->name, pProduct->price); pProduct = pProduct->next; } } int main() { product product product product
tomato = {"Tomato", .51, NULL}; potato = {"Potato", .21, NULL}; lemon = {"Lemon", .34, NULL}; milk = {"Milk", 3.51, NULL};
19
product turkey = {"Turkey", 1.51, NULL}; tomato.next = &potato; potato.next = &lemon; lemon.next = &milk; milk.next = &turkey; product apple = {"Apple",1.58, NULL}; lemon.next = &apple; apple.next = &milk; printLinkedList(&tomato); return 0; }
20
int main() { bool isANumber; int number; int sumOfNumbers = 0; printf("Enter a number: "); isANumber = (scanf("%d", &number) == 1); while(isANumber) { sumOfNumbers = sumOfNumbers +number; printf("Enter a number: "); isANumber = (scanf("%d", &number) == 1); } printf("The Sum is %d\n\n", sumOfNumbers); return 0; }
21
22
Tutorial_8_2
#include <stdio.h> #include <stdlib.h> struct product { float price; char productName[30]; }; int main() { struct product *pProducts; int i,j; int numberOfProducts; printf("Enter the Number of Products to Store"); scanf("%d", &numberOfProducts); pProducts = (struct product *) malloc(numberOfProducts * sizeof(struct product)); for (i = 0; i < numberOfProducts; ++i) { printf("Enter a Product Name:"); scanf("%s", &(pProducts+i)->productName); printf("Enter a Product Price:"); scanf("%f", &(pProducts+i)->price); } printf("Products Stored\n"); for (j = 0; j < numberOfProducts; ++j) { printf("%s\t%.2f\n", (pProducts+j)->productName, (pProducts+j)->price); } free(pProducts); return 0; }
23
24
25
{ struct product *pProducts = pFirstNode; printf("Products entered \n\n"); while (pProducts != NULL) { printf("%s costs %.2f\n\n",pProducts->productName,pProducts->price); pProducts = pProducts->next; } } int main() { inputData(); inputData(); inputData(); outputData(); return 0; }
26
10.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct product { float price; char productName[30]; struct product *next;
}; struct product *pFirstNode = NULL; struct product *pLastNode = NULL; void createNewList(){ struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); pNewStruct->next = NULL; printf("Enter Product Name"); scanf("%s", &(pNewStruct)->productName); printf("Enter Product Price"); scanf("%f", &(pNewStruct)->price); pFirstNode = pLastNode = pNewStruct; } void inputData() { if (pFirstNode == NULL) { createNewList(); }else { struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); printf("Enter Product Name"); scanf("%s", &(pNewStruct)->productName); printf("Enter Product Price"); scanf("%f", &(pNewStruct)->price); if (pFirstNode == pLastNode) { pFirstNode->next = pNewStruct; pLastNode = pNewStruct; pNewStruct->next = NULL; } else { pLastNode->next = pNewStruct; pNewStruct->next = NULL; pLastNode = pNewStruct; }
27
} } void outputData() { struct product *pProducts = pFirstNode; printf("Products entered \n\n"); while (pProducts != NULL) { printf("%s costs %.2f\n\n",pProducts->productName,pProducts->price); pProducts = pProducts->next; } } struct product *pProductBeforeProductToDelete = NULL; struct product* searchForProduct(char * productName) { struct product *pProductIterator = pFirstNode; while(pProductIterator != NULL) { int areTheyEqual = strncmp(pProductIterator->productName,productName, 30); if(!areTheyEqual) { printf("%s was found and it costs %.2f\n\n",pProductIterator>productName,pProductIterator->price); return pProductIterator; } pProductIterator = pProductIterator->next; pProductBeforeProductToDelete = pProductIterator; } printf("%s was not found", productName); return NULL; } void removeProduct(char * productName) { struct product *pProductToDelete = NULL; pProductToDelete = searchForProduct(productName); if(pProductToDelete != NULL) { printf("%s was deleted", productName); if (pProductToDelete == pFirstNode) { pFirstNode = pProductToDelete->next; }else { pProductBeforeProductToDelete->next = pProductToDelete->next; } } } int main() { inputData(); inputData(); inputData();
28
29
11.
#include <stdio.h> #include <stdlib.h> int main() { int randomNumber; FILE *pFile; pFile = fopen("randomnumbers.txt", "w"); if (!pFile) { printf("Error: could not write to File"); return 1; } int i; for (i = 0 ; i < 10; i++) { randomNumber = rand() % 100; fprintf(pFile, "%d\n", randomNumber); } printf("Succees wrtiting to File \n"); if(fclose(pFile) != 0) { printf("Error: File not closed\n"); } return 0; }
Tutorial_11_2
#include <stdio.h> #include <stdlib.h> int main(){ FILE * pFile; pFile = fopen("randomwords.txt", "r+"); char buffer[1000]; if(!pFile){ printf("Error : Couldn't Write to File\n"); return 1; } fputs("Messing With Strings", pFile); fseek(pFile, 12, SEEK_SET); fputs(" Files ", pFile); printf("Success Writing to File\n"); fseek(pFile, 0, SEEK_SET); fseek(pFile, 0, SEEK_END); long numberOfBytes = ftell(pFile); printf("Number of Bytes in File : %d\n", numberOfBytes); fseek(pFile, -20, SEEK_CUR);
30
while(fgets(buffer, 1000, pFile) != NULL){ printf("%s", buffer); } printf("\n"); if(fclose(pFile) != 0) printf("Error : File Not Closed\n"); return 0; }
31
12.
#include <stdio.h> #include <stdlib.h> #include <errno.h> int main(void){
FILE *pFile; char * buffer; size_t dataInFile; long fileSize; pFile = fopen("names.bin", "rb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); printf("File Being Created\n\n"); pFile = fopen("names.bin", "wb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(1); } } char name[] = "Derek Banas"; fwrite(name, sizeof(name[0]), sizeof(name)/sizeof(name[0]), pFile); fseek (pFile , 0 , SEEK_END); fileSize = ftell(pFile); rewind(pFile); buffer = (char*) malloc (sizeof(char)*fileSize); if(buffer == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(2); } dataInFile = fread(buffer, 1, fileSize, pFile); if(dataInFile != fileSize){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(3); } printf("%s\n", buffer); printf("\n"); fclose(pFile); free(buffer); return 0; }
Tutorial_12_2
#include <stdio.h> #include <stdlib.h> #include <errno.h>
32
int main(void){ FILE *pFile; size_t dataInFile; pFile = fopen("randomnums.bin", "rb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); printf("File Being Created\n\n"); pFile = fopen("randomnums.bin", "wb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(1); } } int randomNumbers[20]; int i; for(i = 0; i < 20; i++){ randomNumbers[i] = rand() % 100; printf("Number %d is %d\n", i, randomNumbers[i]); } fwrite(randomNumbers, sizeof(int), 20, pFile); long randomIndexNumber; int numberAtIndex; printf("Which Random Number do you Want? "); scanf("%ld", &randomIndexNumber); fseek(pFile, randomIndexNumber * sizeof(int), SEEK_SET); fread(&numberAtIndex, sizeof(int), 1, pFile); printf("The Random Number at Index %d is %d\n", randomIndexNumber, numberAtIndex); fclose(pFile); return 0; }
33
13.
#include <stdio.h> #include <stdlib.h> #include <string.h>
char * convertBase(unsigned int numberToConvert, int base){ char buffer[33]; char *pConvertedNumber; char allValues[] = "0123456789abcdef"; if(base < 2 || base > 16) { printf("Enter a Number Between 2 and 16 \n"); exit(1); } pConvertedNumber = &buffer[sizeof(buffer)-1]; *pConvertedNumber = '\0'; do { int value = numberToConvert % base; pConvertedNumber = pConvertedNumber - 1; *pConvertedNumber = allValues[value]; numberToConvert /= base; } while(numberToConvert != 0); printf("%s", pConvertedNumber); return pConvertedNumber; } int main() { unsigned int numberOne = 60; printf("%d in Base 2 = ", numberOne); convertBase(numberOne, 2); printf("\n"); printf("%d in Base 8 = ", numberOne); convertBase(numberOne, 8); printf("\n"); printf("%d in Base 16 = ", numberOne); convertBase(numberOne, 16); printf("\n"); return 0; }
34
35
14.
#include #include #include #include #include <stdio.h> <stdlib.h> <string.h> <ctype.h> <math.h>
int baseToDecimal(char* number, int baseFrom, int sizeOfNumber) { int result = 0; int toThePowerOf = 0; int i; for (i = (sizeOfNumber - 2); i >= 0 ; --i) { if(isalpha(number[i])) { int charCode = ((int)tolower(number[i])) - 87; result += charCode * pow(baseFrom, toThePowerOf); } else { result += (number[i] - '0') * pow(baseFrom, toThePowerOf); } toThePowerOf++; } printf("%s in the base %d equals %d in base 10\n",number, baseFrom,result); return result; } char * convertBase(unsigned int numberToConvert, int base){ char buffer[33]; char *pConvertedNumber; char allValues[] = "0123456789abcdef"; if(base < 2 || base > 16) { printf("Enter a Number Between 2 and 16 \n"); exit(1); } pConvertedNumber = &buffer[sizeof(buffer)-1]; *pConvertedNumber = '\0'; do { int value = numberToConvert % base; pConvertedNumber = pConvertedNumber - 1; *pConvertedNumber = allValues[value]; numberToConvert /= base; } while(numberToConvert != 0); printf("%s", pConvertedNumber); return pConvertedNumber; }
36
int main() { unsigned int numberOne = 60; printf("%d in Base 2 = ", numberOne); convertBase(numberOne, 2); printf("\n"); printf("%d in Base 8 = ", numberOne); convertBase(numberOne, 8); printf("\n"); printf("%d in Base 16 = ", numberOne); convertBase(numberOne, 16); printf("\n"); char numberToConvert[] = "3C"; baseToDecimal(numberToConvert, 16, sizeof(numberToConvert)); return 0; }
37
15.
Passing Memory Addresses, Bitwise Operators, Signed Integers, Shift Operators, Twos Compliment, Bit Masking Tutorial 15
int baseToDecimal(char* number, int baseFrom, int sizeOfNumber) { int result = 0; int toThePowerOf = 0; int i; for (i = (sizeOfNumber - 2); i >= 0 ; --i) { if(isalpha(number[i])) { int charCode = ((int)tolower(number[i])) - 87; result += charCode * pow(baseFrom, toThePowerOf); } else { result += (number[i] - '0') * pow(baseFrom, toThePowerOf); } toThePowerOf++; } printf("%s in the base %d equals %d in base 10\n",number, baseFrom,result); return result; } char * convertBase(unsigned int numberToConvert, int base, char *pConvertedNumber){ char allValues[] = "0123456789abcdef"; if(base < 2 || base > 16) { printf("Enter a Number Between 2 and 16 \n"); exit(1); } pConvertedNumber[32] = '\0'; do { int value = numberToConvert % base; pConvertedNumber = pConvertedNumber - 1; *pConvertedNumber = allValues[value]; numberToConvert /= base; } while(numberToConvert != 0); return pConvertedNumber; } int main() { unsigned int numberSix = 6; unsigned int numberSeven = 7;
38
char *pConvertedNumber; pConvertedNumber = malloc(33 * sizeof(char)); printf("%s\n", convertBase(numberSix,2,pConvertedNumber)); unsigned int andSolution = numberSix & numberSeven; unsigned int orSolution = numberSix | numberSeven; unsigned int exOrSolution = numberSix ^ numberSeven; unsigned int onesCompSoultion = ~numberSix; unsigned int shitfLeftTwo = numberSix << 2; unsigned int analyzeMyBits = 170; //10101010 unsigned int theMask = 15; // 00001111 unsigned int last4Bits = analyzeMyBits & theMask; printf("%s & ", convertBase(numberSix,2,pConvertedNumber)); printf("%s = ", convertBase(numberSeven,2, pConvertedNumber)); printf("%s \n\n ", convertBase(andSolution, 2, pConvertedNumber)); printf("%s | ", convertBase(numberSix,2,pConvertedNumber)); printf("%s = ", convertBase(numberSeven,2, pConvertedNumber)); printf("%s \n\n ", convertBase(orSolution, 2, pConvertedNumber)); printf("%s ^ ", convertBase(numberSix,2,pConvertedNumber)); printf("%s = ", convertBase(numberSeven,2, pConvertedNumber)); printf("%s \n\n ", convertBase(exOrSolution, 2, pConvertedNumber)); printf("~%s = ", convertBase(numberSix,2, pConvertedNumber)); printf("%s\n\n",convertBase(onesCompSoultion, 2, pConvertedNumber)); printf("%s << 2 = ", convertBase(numberSix,2, pConvertedNumber)); printf("%s = %d\n\n",convertBase(shitfLeftTwo, 2, pConvertedNumber), shitfLeftTwo); printf("%s & ", convertBase(analyzeMyBits,2,pConvertedNumber)); printf("%s = ", convertBase(theMask,2, pConvertedNumber)); printf("%s \n\n ", convertBase(last4Bits, 2, pConvertedNumber)); free(pConvertedNumber); return 0; }
39
40
41