Steven Christian
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # C/C++ Cheatsheet for NAR Do not use for actually cheating # C ## Data Types ![](https://cdn.techbeamers.com/wp-content/uploads/2019/01/C-Datatypes-Range-and-Sizes.png) #### Booleans in C ```c= #include <stdbool.h> bool foo = true; ``` ## Input Output ### Printf ```c= printf ("Characters: %c %c \n", 'a', 65); printf ("Decimals: %d %ld\n", 1977, 650000L); printf ("Preceding with blanks: %10d \n", 1977); printf ("Preceding with zeros: %010d \n", 1977); printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100); printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416); printf ("Width trick: %*d \n", 5, 10); printf ("%s \n", "A string"); ``` Output: ``` Characters: a A Decimals: 1977 650000 Preceding with blanks: 1977 Preceding with zeros: 0000001977 Some different radices: 100 64 144 0x64 0144 floats: 3.14 +3e+000 3.141600E+000 Width trick: 10 A string ``` ### Scanf ```c= scanf("%[^\n]%*c", str); scanf("%s", str); ``` ## stdio.h Standard input output library For more info on scanf, visit [this link](https://www.gnu.org/software/libc/manual/html_node/Formatted-Input.html) ```c!= // Read from formatted input buffer scanf(); // Print formatted output printf(); // Print single character int putchar(int char); // Print string + newline int puts(const char *str); // Get single character int getchar(); // Get string (until '\0' or white-space character is encountered) char *gets(char *str); // Flushes the input buffer int fflush(FILE *stream); fflush(); // Example ``` ## stdlib.h Standard library ```c= // Allocates memory in bytes, returns first address of the array void *malloc(size_t size); // Allocates memory in bytes, sets everything as 0, returns first address of array void *calloc(size_t nitems, size_t size); // Attempts to resize ptr void *realloc(void *ptr, size_t size); // Deallocate memory block in ptr void free(void *ptr); // Quicksort algorithm void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)); qsort(values, 5, sizeof(int), cmpfunc); // Example // Type Conversions atoi(str); // String to integer atol(str); // String to long int atoll(str); // String to long long atof(str); // String to float // Integer to string char* itoa ( int value, char * str, int base ); itoa(5, &foo, 10); // String to long int long int strtol(const char *string, char **laststr,int basenumber); ``` ## math.h ```c= // Rounds double down double floor(double x); // Rounds double up double ceil(double x); // Rounds x double round(double round); // Power double pow(double base, double power); // Square root double sqrt(double x); // Truncates digits after comma double trunc(double x); ``` ## string.h ```c!= // String compare, 0 if equal int strcmp (const char* str1, const char* str2); // String concatenate char *strcat(char *destination, const char *source); // String length int strlen(const char *str); // String copy, copy by value char *strcpy(char* destination, const char* source); strtok ``` ## ctype ```c!= // Is alphanumeric?, 0 if it's not int isalnum(int c); // Is alphabet? int isalpha(int c); // Is digit? int isdigit(int c); // Is lowercase letter? int islower(int c); // Is capital letter? int isupper(int c); // Checks if white-space (\t, \n, \f, \r, etc) int isspace(char c); // Converts alphabet into lower case letters int tolower(int c); // Converts alphabet into capital letters int toupper(int c); ``` ## conio.h Console input ouput (deprecated) ```c!= // Get character without printing it onto the console (deprecated) int getch(void); // Get character while printing it onto the console (deprecated) int getche(void); ``` # C++ ## bits/stdc++.h Collection of common C++ libraries ## iostream Input output stream ```cpp= // Basic input output cout << "" << endl; cin >> a; // Writing floating-point values in fixed-point notation ios_base& fixed (ios_base& str); ``` ## iomanip Input output manipulation ```cpp= //set the ios library floating point precision based on input std::cout << std::fixed << std::setprecision(2) << 2 << endl; // 2.00 // Prints number as hexadecimal std::cout << std::hex << x << endl; // Prints number as octal std::cout << std::oct << x << endl; // Prints integer with padding std::cout << std::setfill('0') << std::setw(5) << 25; //00025 ``` ## vector C++'s version of dynamic array. View cheatsheet [here](https://hackingcpp.com/cpp/std/vector.png) ```cpp= // Vector declaration vector<int> v; vector<int> v(int size, int ?defaultValue); vector<int> v(iteratorStart, iteratorEnd); vector<int> v{0,1,2,3,4} // Element manipulation v.push_back(n); // Appends at the end v.pop_back(); // Remove last element v.insert(startIndex, data); // Inserts data to array at startIndex v.erase(startIterator, endIterator); // Erases data in array v.empty(); // Empties the array // Vector properties v.size(); // Vector length v.begin(); // Start iterator v.end(); // End iterator v.rbegin(); // Reverse iterator from last element v.rend(); // Reverse iterator from first element // Map functions *max_element(v.begin(), v.end()); // Returns max element *min_element(v.begin(), v.end()); // Returns min element std::find(v.begin(), v.end(), 5); // Returns iterator of the element, returns last iterator if fails (needs <algorithm> library) std::accumulate(v.begin(), v.end()); // Returns sum of all elements (needs <numeric> library) std::replace(startIterator, endIterator, oldValue, newValue); // Replaces elements between iterators which has the oldValue to the newValue (needs <algorithm> library) std::sort(v.begin(), v.end()) // Sorts the array // For loop for (auto& n: v) { // n is the value } ``` ## string ```cpp= // String declaration std::string str = ""; // String length str.length() // Type Conversions stoi(n); // String to integer stof(n); // String to float stod(n); // String to double stold(n); // String to long double to_string(n); // Number to string // Substring str.substr(startIndex, length); // Replace string str.replace(str.begin(), str.end(), "replace"); // Find start index of foo str.find(str2); // Returns std::string::npos if not foo is not found // Insert string str.insert(startIndex, str2); ``` ## cmath ```cpp= // Rounds double down double floor(double x); // Rounds double up double ceil(double x); // Rounds x double round(double round); // Power double pow(double base, double power); // Square root double sqrt(double x); // Truncates digits after comma double trunc(double x); ``` # Common Algorithms ## Bubble sort ```c= void bubbleSort(int arr[], int n) { int i, j; for (i = 0; i < n - 1; i++) // Last i elements are already in place for (j = 0; j < n - i - 1; j++) if (arr[j] > arr[j + 1]) swap(&arr[j], &arr[j + 1]); } ``` ## Decimal to Binary ```c= void decToBinary(int n) { // array to store binary number int binaryNum[32]; // counter for binary array int i = 0; while (n > 0) { // storing remainder in binary array binaryNum[i] = n % 2; n = n / 2; i++; } // printing binary array in reverse order for (int j = i - 1; j >= 0; j--) printf("%d", binaryNum[j]); } ``` # TODO: * string functions(find, replace, substring, trim, insert, slice, strtok) * C scanf/printf * rand() Summarized by: <img src="https://cdn.discordapp.com/avatars/322362818982707210/0720c1b7a6a2ac582b401ee4783f2dc7.webp?size=100" style="height: 30px; border-radius: 50%;"/>**Stevenn#1001** <img src="https://cdn.discordapp.com/avatars/747805874394759198/58247f1bdce2bcb0d539202c26367c18.webp?size=96" style="height: 30px; border-radius: 50%;"/>**bolakecil#0542**

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully