# C/C++ Cheatsheet for NAR
Do not use for actually cheating
# C
## Data Types

#### 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**