/c

Notes that I made while learning to program in C

Primary LanguageC


C File Icon

C Notes

This is my notes that I made while learning to code in C

πŸ”΄1. Header file

#include <stdio.h>
  • πŸ‘† this is called "header file library"

πŸ”΄2. to insert a new line use \n

eg:

printf("hello/n")
printf("world")

output:

hello
world

πŸ”΄3. if you put 2 \n characters, it will create a blank line eg:

printf("hello\n\n")
printf("world")

output:

hello

world

πŸ”΄4. Comments:

  • πŸ‘‰ Single line comments starts with 2 forward slashes

  • eg: //this is a comments

  • πŸ‘‰ Multi line comments starts with /_ and ends with _/

  • eg:

    /*
    This is a comment
    written in
    more than just one line
    */

πŸ”΄5. Data Types

  • πŸ‘‰ int - stores integers (whole nums)
  • πŸ‘‰ float - stores decimal nums
  • πŸ‘‰ double - stores decimal nums with higher precision
  • πŸ‘‰ char - stores single characters like 'a' or 'B'. characters are surrounded by single quotes
  • πŸ‘‰ strings (text)

πŸ”΄6. Declaring Variables

  • πŸ‘‰ Syntax:
    type variableName = value;

πŸ”΄7. Format Specifiers

  • starts with % sign within double quotes, follwed by a character.
  • πŸ‘‰ "%d" : int - stores whole numbers
  • πŸ‘‰ "%f" : float - stores decimal numbers
  • πŸ‘‰ "%lf" : double - same as float, stores decimal numbers
  • πŸ‘‰ "%c" : char
  • πŸ‘‰ "%s" : strings
  • πŸ‘‰ "%lu" : print an unsigned long integer.
  • πŸ‘‰ "%p" : print a pointer address.
  • (use float mostly, double is used when more precision is needed)
  • (If you want to remove the extra zeros (set decimal precision), you can use a dot (.) followed by a number that specifies how many digits that should be shown after the decimal point:)

eg:

printf("%d\n", myNum);
printf("%c\n", myLetter);
printf("%f\n", myFloatNum);
printf("%lf\n", myDoubleNum);
printf("%s\n", myString);

eg: float myFloatNum = 3.5;

printf("%f\n", myFloatNum); // Default will show 6 digits after the decimal point
printf("%.1f\n", myFloatNum); // Only show 1 digit
printf("%.2f\n", myFloatNum); // Only show 2 digits
printf("%.4f", myFloatNum); // Only show 4 digits

πŸ”΄8. Arithmetic Operators

  • πŸ‘‰ + Addition : adds togeher two values : x + y
  • πŸ‘‰ - Subtraction : subtracts one value from another : x - y
  • πŸ‘‰ _ Multiplication: multiplies two values : x _ y
  • πŸ‘‰ / Division : divides one value by another : x/y
  • πŸ‘‰ % Modulus : returns the division remainder : x%y
  • πŸ‘‰ ++ Increment : increases the value of variable by 1 : ++x
  • πŸ‘‰ -- Decrement : decreases the value of a variable by 1 : --x

πŸ”΄9. Assignment Operators

  • πŸ‘‰ = : x = 5 : x = 5
  • πŸ‘‰ += : x += 3 : x = x + 3
  • πŸ‘‰ -= : x -= 3 : x = x - 3
  • πŸ‘‰ _= : x _= 3 : x = x * 3
  • πŸ‘‰ /= : x /= 3 : x = x / 3
  • πŸ‘‰ %= : x %= 3 : x = x % 3
  • πŸ‘‰ &= : x &= 3 : x = x & 3
  • πŸ‘‰ |= : x |= 3 : x = x | 3
  • πŸ‘‰ ^= : x ^= 3 : x = x ^ 3
  • πŸ‘‰ >>=: x >>= 3: x = x >> 3
  • πŸ‘‰ <<=: x <<= 3: x = x << 3

πŸ”΄10. Comparison Operators

  • πŸ‘‰ == : equal to
  • πŸ‘‰ != : not equal to
  • πŸ‘‰ > : greater than
  • πŸ‘‰ < : less than
  • πŸ‘‰ >= : greater than or equal to
  • πŸ‘‰ <= : less than or equal to

πŸ”΄11. Logical Operators

  • πŸ‘‰ && : logical and
  • πŸ‘‰ || : logical or
  • πŸ‘‰ ! : logical not

πŸ”΄13. Booleans

  • Booleans means YES/NO or TRUE/FALSE or ON/OFF

  • bool type is not built-in data type , so we must import it the header file:

    #include <stdbool.h>
  • πŸ‘‰ 0 : false

  • πŸ‘‰ 1 : true

πŸ”΄14. Memory Size

  • πŸ‘‰ int : 2 or 4 bytes
  • πŸ‘‰ float : 4 bytes
  • πŸ‘‰ double : 8 bytes
  • πŸ‘‰ char : 1 byte

πŸ”΄15. Type Conversion Converting one data type to another is called type conversion.

  • πŸ‘‰ Implicit Conversion : done automatically by the compiler
  • πŸ‘‰ Explicit Conversion : done by the programmer

πŸ”΄16. If else statements πŸ‘‡ Syntax

if (condition) {
// code
} else {
// code
}

πŸ”΄17. Else if statement πŸ‘‡ Syntax

if (condition1) {
// code
} else if (condition2) {
// code
} else {
// code
}

πŸ”΄18. Short Hand If Else... (Ternary Operator) πŸ‘‡ Syntax

variable = (condition) ? expressionTrue : expressionFalse;

πŸ”΄19. Switch Statement

  • Instead of writing many if..else statements, you can use the switch statement.
  • πŸ‘‡ Syntax
switch (expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}
  • The break keyword stops the execution of the switch statement.
  • The default keyword specifies some code to run if there is no case match.

πŸ”΄20. While Loop while loop loops through a block of code as long as a specified condition is true. πŸ‘‡Sytnax

while (condition) {
  // code block to be executed
}

πŸ”΄21. Do While Loop do while loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. πŸ‘‡Syntax

do {
  // code block to be executed
}
while (condition);

πŸ”΄22. For Loop for loop is often used when the number of iterations is predetermined/known. πŸ‘‡Syntax

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}
  • Statement 1 is executed (one time) before the execution of the code block.
  • Statement 2 defines the condition for executing the code block.
  • Statement 3 is executed (every time) after the code block has been executed.

πŸ”΄23. Nested Loops A nested loop is a loop inside a loop. πŸ‘‡Syntax

for (int i = 0; i < 5; i++) {
  for (int j = 0; j < 5; j++) {
    printf("%d %d\n", i, j);
  }
}

πŸ”΄24. Break and Continue

  • πŸ‘‰break statement is used to exit a loop. eg:

    for (int i = 0; i < 10; i++) {
      if (i == 4) {
        break;
      }
      printf("p = %d\n", p);
    }

    Output:

    p = 0
    p = 1
    p = 2
    p = 3
    
  • πŸ‘‰continue statement is used to skip the current block, and return to the loop. eg:

    for (int i = 0; i < 6; i++) {
      if (i == 4) {
        continue;
      }
      printf("p = %d\n", p);
    }

    Output:

    p = 0
    p = 1
    p = 2
    p = 3
    p = 5
    

πŸ”΄25. Arrays

  • An array is a collection of items stored at each memory location.
  • The idea is to store multiple items of the same type together.
  • Arrays can be created in two ways:
    • πŸ‘‰ Static Memory Allocation : In this, the size of the array is determined at the compile time.
    • πŸ‘‰ Dynamic Memory Allocation : In this, the size of the array is determined at the run time.

eg:

int myArray[5] = {1, 2, 3, 4, 5};
  • To access an element in an array, the index number is used.

  • The index number starts from 0.

  • eg: myArray[0] will return 1

  • Multi-dimensional Arrays : An array of arrays is known as a multi-dimensional array. eg:

    int myNumbers[2][3] = {{1, 2, 3}, {4, 5, 6}};
  • To access an element in a multi-dimensional array, the index number is used.

πŸ”΄26. Strings

  • Strings are actually one-dimensional array of characters terminated by a null character '\0'.
  • A string is defined as an array of characters.
  • A string is terminated by a null character '\0'.
  • A string literal is a sequence of characters enclosed in double-quote marks.
  • eg:
char myString[6] = "Hello";
  • To output the value of a string, you can use the %s format specifier.
  • eg:
printf("%s", myString);

πŸ”΄26. Special characters (escape characters)

  • πŸ‘‰ \n : new line
  • πŸ‘‰ \t : tab
  • πŸ‘‰ \b : backspace
  • πŸ‘‰ \r : carriage return
  • πŸ‘‰ \0 : null character
  • πŸ‘‰ \\ : backslash
  • πŸ‘‰ \' : single quote
  • πŸ‘‰ \" : double quote

πŸ”΄27. String Functions

  • πŸ‘‰ strlen() : returns the length of a string
  • πŸ‘‰ strcat() : concatenates two strings
  • πŸ‘‰ strcpy() : copies one string to another
  • πŸ‘‰ strcmp() : compares two strings

πŸ”΄28. Memory Adderss

  • When a variable is created in C, a memory address is assigned to the variable.
  • When we assign a value to the variable, it is stored in this memory address.
  • When we assign a value to the variable, it is stored in this memory address.
  • The address of the variable is assigned to the pointer using the & operator.
  • eg:
int myCurrentAge = 19;
    printf("%p\n", &myAge); // outputs: 0061FE80 - this changes everytime you run the program

πŸ”΄29. Pointers

  • A pointer is a variable whose value is the address of another variable.
  • A pointer is declared using the * operator.
  • eg:
int myAge = 19;
int *myPointer = &myAge;
  • To get the value of the variable that the pointer is pointing to, use the * operator.
  • eg:
printf("%d\n", *myPointer);

πŸ”΄30. Functions

  • A function is a block of code that performs a specific task.
  • A function is declared using the function keyword.
  • A function is called using the function name followed by parentheses.
  • eg:
void myFunction() {
  printf("Hello World\n");
}

int main() {
  myFunction();
  return 0;
}
  • Function Declaration : A function declaration tells the compiler about a function's name, return type, and parameters.
  • Function Definition : The actual body of the function is called the function definition.
  • Function Call : To call a function, you simply need to pass the required parameters along with the function name.

πŸ”΄31. Function Parameters

  • Information can be passed to functions as a parameter.
  • Parameters act as variables inside the function.
  • Parameters are specified after the function name, inside the parentheses.
  • You can add as many parameters as you want, just separate them with a comma.
  • eg:
void myFunction(int myAge) {
  printf("I am %d years old\n", myAge);
}

int main() {
  myFunction(19);
  return 0;
}

πŸ”΄32. Return Keyword

  • The return keyword is used to return a value from a function.
  • eg:
int myFunction(int x, int y) {
  return x + y;
}

int main() {
  printf("%d\n", myFunction(5, 3));
  return 0;
}

πŸ”΄33. Recursion

  • Recursion is the technique of making a function call itself.
  • This technique provides a way to break complicated problems down into simple problems which are easier to solve.
  • eg:
int myFunction(int x) {
  if (x > 0) {
    return x + myFunction(x - 1);
  } else {
    return 0;
  }
}

int main() {
  printf("%d\n", myFunction(5));
  return 0;
}

πŸ”΄34. Math Function

  • C programming has a set of built-in math functions.
  • To use these functions, you need to include the math.h library.
  • eg:
#include <math.h>

int main() {
  printf("%f\n", sqrt(64));
  printf("%f\n", ceil(9.6));
  printf("%f\n", floor(9.6));
  return 0;
}

πŸ”΄35. File Handling

  • You can create, open, read, write, and close files using functions.
  • To perform file processing in C, you need to include the stdio.h header file.
  • You can create, open, read, and write to files by using the fopen, fclose, fprintf, and fscanf functions.
  • eg:
#include <stdio.h>

int main() {
  FILE *myFile = fopen("test.txt", "w");
  fprintf(myFile, "Hello World\n");
  fclose(myFile);
  return 0;
}

πŸ”΄36. Write to Files

  • To write to an existing file, you must add a parameter to the fopen() function:
    • w : write mode
    • a : append mode
    • r+ : read/write mode
    • w+ : read/write mode (overwrite file)
    • a+ : read/write mode (append if file exists)
#include <stdio.h>

int main() {
  FILE *fptr;

  // open the file in writing mode
  fptr = fopen("filename.txt", "w");

  // write some text to the file
  fprintf(fptr, "Hello World\n");

  // close the file
  fclose(fptr);
}
  • NOTE: If you write to a file that already exists, it will overwrite the existing content.

πŸ”΄37. Read from Files

  • To read from an existing file, you must add a parameter to the fopen() function:
    • r : read mode
    • r+ : read/write mode
    • w+ : read/write mode (overwrite file)
    • a+ : read/write mode (append if file exists)
#include <stdio.h>

int main() {
  FILE *fptr;
  char c;

  // open the file in read mode
  fptr = fopen("filename.txt", "r");

  // Store the content of the file
  char myString[100];

  // Read the content and store it inside myString
  fgets(myString, 100, fptr);

  // Print the file content
  printf("%s", myString);

  // Close the file
  fclose(fptr);
}
  • The fgets function only reads the first line of the file.
  • To read every line of the file, use a while loop. -eg:
#include <stdio.h>

int main() {
  FILE *fptr;

// Open a file in read mode
fptr = fopen("filename.txt", "r");

// Store the content of the file
char myString[100];

// Read the content and print it
while(fgets(myString, 100, fptr)) {
  printf("%s", myString);
}

// Close the file
fclose(fptr);
}
  • If you try to open a file for reading that does not exist, the fopen() function will return NULL.

πŸ”΄38. Structure

  • A structure is a user-defined data type in C/C++.
  • A structure creates a data type that can be used to group items of possibly different types into a single type.
  • eg:
struct Person {
  char name[50];
  int age;
  float salary;
};

int main() {
  struct Person person1;
  person1.age = 19;
  person1.salary = 12000.50;
  strcpy(person1.name, "John");
  printf("%s\n", person1.name);
  printf("%d\n", person1.age);
  printf("%f\n", person1.salary);
  return 0;
}

πŸ”΄39. Enumeration (enum)

  • An enumeration is a user-defined data type that consists of integral constants.
  • To define an enumeration, use the enum keyword.
  • eg:
enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
  • By default, the value of the first name is 0, the second name is 1, and so on.
  • But you can give a name a specific value.
  • eg:
enum week { Sunday, Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday };
  • You can define the size of an enum using the sizeof operator.
  • eg:
#include <stdio.h>

enum week { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

int main() {
  printf("%d\n", sizeof(enum week));
  return 0;
}

πŸ”΄40. User Input

  • To allow user input, you can use the scanf() function.
  • The scanf() function reads the input from the standard input (keyboard).
  • eg:
#include <stdio.h>

int main() {
  int myAge;
  printf("Enter your age: ");
  scanf("%d", &myAge);
  printf("You are %d years old\n", myAge);
  return 0;
}
  • The & operator is used to get the memory address of a variable.
  • The scanf() function requires the address of the variable it is reading the input for.