https://github.com/reshinto/programming_language_syntax_comparison
Compare syntax differences between programming languages (python, javascript, ruby, java, c#, c/c++). This would be deprecated soon. Moving to https://www.terencekong.net/docs/documentation
https://github.com/reshinto/programming_language_syntax_comparison
c-plus-plus csharp java javascript python ruby
Last synced: 4 months ago
JSON representation
Compare syntax differences between programming languages (python, javascript, ruby, java, c#, c/c++). This would be deprecated soon. Moving to https://www.terencekong.net/docs/documentation
- Host: GitHub
- URL: https://github.com/reshinto/programming_language_syntax_comparison
- Owner: reshinto
- Created: 2019-02-17T17:00:41.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2025-03-11T19:55:50.000Z (over 1 year ago)
- Last Synced: 2025-03-11T20:33:38.413Z (over 1 year ago)
- Topics: c-plus-plus, csharp, java, javascript, python, ruby
- Homepage:
- Size: 7.72 MB
- Stars: 87
- Watchers: 4
- Forks: 22
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# PROGRAMMING LANGUAGE SYNTAX COMPARISON
> A syntax summary, which also compares the differences between each programming language.
- List of languages
- Python, Javascript (Typescript), Ruby, Kotlin, Java, C#, C/C++, Groovy
## Table of Contents
- [Interpreted Language](#interpreted-language)
- [Compiled Language](#compiled-language)
- [Both Interpreted And Compiled Language](#both-interpreted-and-compiled-language)
- [Hello World](#hello-world)
- [Comments](#comments)
- [Data types](#data-types)
- [Variable declaration int](#variable-declaration-int)
- [Variable declaration float](#variable-declaration-float)
- [Variable declaration None](#variable-declaration-none)
- [Strings](#strings)
- [Boolean](#boolean)
- [Arithmetic Operators](#arithmetic-operators)
- [Comparison Operators](#comparison-operators)
- [Logical Operators](#logical-operators)
- [Getting Input](#getting-input)
- [Bitwise Operators](#bitwise-operators)
- [Increment](#increment)
- [Arrays and Lists](#arrays-and-lists)
- [Conditional Statement](#conditional-statement)
- [Loops](#loops)
- [Instantiation](#instantiation)
- [Functions](#functions)
- [Higher order functions](#higher-order-functions)
- [Hash Tables](#hash-tables)
- [Destructuring](#destructuring)
- [Spread Operator](#spread-operator)
- [Rest parameters](#rest-parameters)
- [Class](#class)
- [Importing Libraries](#importing-libraries)
- [Type Conversions](#type-conversions)
- [Find Data Type](#find-data-type)
- [String Concatenation](#string-concatenation)
- [JSON](#json)
- [Program Entry Point](#program-entry-point)
- [Swapping values](#swapping-values)
- [Error Handling](#error-handling)
- [Custom Error](#custom-error)
- [Asynchronous](#asynchronous)
- [Math](#math)
- [Date and Time](#date-and-time)
- [Access modifier](#access-modifier)
- [File System](#file-system)
- [Iterators](#iterators)
- [Generators](#generators)
- [Fetching Web Data](#fetching-web-data)
- [Enum](#enum)
- [Language Specific](#language-specific)
## Interpreted Language
### Dynamically-typed Language: resolution of types, members, properties, methods are done at run-time
#### lose compile-time checking, have to write more unit tests to ensure app behaves properly at run-time
- Python
- Javascript
- Features
- based on ECMAScript standard
- not compiled, interpreted at runtime
- no native function calls in browser
- runtime differ between environments
- restricted to browser sandbox
- managed memory access
- prototype-based inheritance
- Ruby
## Compiled Language
### Statically-typed Language: resolution of types, members, properties, methods are done at compile-time
#### trying to access a method that is not defined in an object when compiling the app will get an immediate error feedback
- Java: compiled to bytecode then interpreted by Java virtual machine into machine code
- Features
- not compatible with other languages
- calls to native functions go through Java Native Interface (JNI)
- write once, run anywhere
- runs in a protected Java Virtual Machine (JVM)
- managed memory access
- limited to single inheritance
- class-based inheritance
- Types
- Java Platform, Standard Edition (SE)
- Core language and Java Runtime Environment (JRE)
- Java Platform, Enterprise Edition (EE)
- Recommendation for industrial-strength web applications
- Java Platform, Micro Edition (ME)
- Microcontrollers, sensors, mobile devices, telephone sim cards
- A subset of Java SE
- Java FX
- Desktop appication framework (windows, mac, linux)
- Automatic memory management
- memory for objects are allocated automatically
- local variables & function calls are stored in stack
- objects & member variables are stored in heap
- objects are retained in memory until dereferenced
- object is eligible for collection when all references expire
- when do references expire
- variables local to methods or code blocks expire with scope
```java
void changeString() {
String localVar = "Won't be around for long!";
System.out.println("In function: " + localVar);
}
```
- explicitly dereference variables with null keyword
```java
void changeString() {
String localVar = "Won't be around for long!";
tempVar = null;
}
```
- when Java Virtual Machine runs out of memory for a newly requested object
- the system throws `OutOfMemoryError`
- Tips for managing memory
- minimize the number of objects created
- find out how much memory is available & is currently in used in the virtual machine
- `Runtime.maxMemory()` & `Runtime.totalMemory()`
- setting available memory
- use command line options to manage amount of available heap memory
- set inital heap size `java -Xms256s HelloWord`
- set max heap size `java -Xmx256m HelloWord`
- set heap size for new objects `java -Xmn256n HelloWord`
- Java Garbage Collector
- runs in its own thread
- allocates & deallocates memory
- can destroy dereferenced objects, but not required
- garbage collection is managed by the Virtual Machine
- cannot force garbage collection as it is an automatic process
- Can run System methods to call garbage collection
- Methods `System.gc()` & `Runtime.gc()` can request garbage collection
- but there is no guarantee it will happen
- Identifiers and Keywords
- Keywords can't be used as class or other identifiers
- class, method, field, and other names are identifiers
- identifiers must start with alpha character or underscore
- Identifier conventions
- classes are always Pascal case `class MyClass {}`
- methods and variables are Camel case `void doSomething(String withThis) {}`
- constants are all uppercase `public static final String FIRSTNAME="Myname";`
- `final` means once it has been set, it can't be changed
- C#: compiled to an Intermediate Language (IL), which is then translated by the Common Language Runtime (CLR) into machine code
- from .NET 4, dynamic capability was added to improve interoperability with COM & Dynamic languages
- C++: compiled into native machine language
- what it is
- it is a **standardized, compiled, statically typed, multi-paradigm systems language** built to deliver **high performance with strong abstraction mechanisms**.
- Its design centers on **zero-overhead abstractions**, **deterministic resource management (RAII)**, a **formal concurrency/memory model**, and a rich **standard library** that has evolved substantially in **C++20/23** (concepts, modules, coroutines, ranges, expected, mdspan).
- It interoperates with C but is not a strict superset, and it remains a foundational tool for building complex, performance-critical software.
- Design goals & principles
- C++ is designed to give **efficient low-level control** together with **high-level abstractions**, guided by the **zero-overhead principle** (“you don’t pay for what you don’t use,” and used abstractions are as efficient as hand-written code).
- These principles explain C++’s emphasis on performance with abstractions like classes, templates, and RAII.
- Standardization & versions
- C++ is maintained via ISO standards with regular releases (e.g., **C++11, C++14, C++17, C++20, C++23**, and ongoing work toward **C++26**).
- C++20 introduced **concepts**, **modules**, **coroutines**, and the **ranges** library; `C++23` added new library types such as **`std::expected`** and **`std::mdspan`**.
- Compiler support tables are tracked publicly.
- Compilation model
- C++ is primarily **ahead-of-time (AOT) compiled** to native code.
- Traditional organization is by **translation units** and headers; **C++20 modules** add a language mechanism to publish/import interfaces, improving build times and isolation.
- Type system & object model
- C++ has a **static** and **nominal** type system with fundamental types (integers, floating-point, `bool`, character types, pointer/reference types), user-defined types (enums, classes/structs, unions), function and array types, and **cv-qualification** (`const`/`volatile`).
- Objects have precise lifetimes and storage durations; initialization and destruction semantics are part of the core model.
- Programming paradigms
- C++ is **multi-paradigm**:
- **Procedural** (free functions, control flow)
- **Object-oriented** (encapsulation, virtual dispatch, class hierarchies)
- **Generic programming & templates** (compile-time polymorphism; concepts in C++20)
- **Functional style** (lambdas, higher-order algorithms)
- **Metaprogramming** (`constexpr`, template metaprogramming)
- Resource management & safety model
- C++ emphasizes **deterministic destruction** and **RAII** (Resource Acquisition Is Initialization):
- acquire resources in constructors, release them in destructors.
- Modern guidelines recommend using **resource handles** and **smart pointers** to avoid leaks and dangling resources.
- C++ deliberately leaves some behavior **undefined** to enable aggressive optimization (e.g., out-of-bounds access, data races, signed-overflow).
- Understanding and avoiding **undefined behavior** is part of writing correct and portable C++.
- Error handling
- C++ supports **exceptions** (with zero-overhead when absent, but runtime cost when used) and non-exception patterns such as returning status objects.
- **`std::expected`** (C++23) is a standard vocabulary type for functions that return either a value or an error.
- Concurrency & memory model
- C++ defines a **formal memory model** and provides **threads**, **atomics**, and **memory orderings** for writing correct concurrent code, including lock-free algorithms when possible.
- **Coroutines (C++20)** provide a language mechanism for asynchronous workflows.
- Standard library
- The C++ Standard Library supplies containers, iterators, algorithms, strings, time utilities, I/O, numerics, concurrency primitives, ranges (C++20), multi-dimensional views (`mdspan`, C++23), and more.
- It also exposes C compatibility headers for interop.
- Interoperability with C (and ABIs)
- C++ interoperates with C at the **linkage** level using `extern "C"` for C function names (no C++ name mangling).
- C and C++ are **closely related but different languages**;
- C is **not a subset** of C++, and some valid C code is ill-formed or behaves differently in C++.
- C++ compilers don’t share a single universal ABI; platforms commonly use ABIs like the Itanium C++ ABI for cross-compiler compatibility.
- Typical domains
- Because it combines **close-to-the-metal control** with **high-level abstractions**, C++ is widely used for **systems software, embedded, game engines, high-performance computing, finance/low-latency, browsers, databases**, and other performance-critical infrastructure.
- (For a concise perspective from the language’s creator on these aims and domains, see Stroustrup’s writings on C++ as an “invisible foundation.”)
## Both Interpreted And Compiled Language
- Groovy
- it is a Java-syntax-compatible object-oriented programming language for the Java platform
- is both a static and dynamic language with features similar to those of Python
- can be used as both a programming language and a scripting language for the Java Platform, is compiled to Java virtual machine (JVM) bytecode
- interoperates seamlessly with other Java code and libraries
- allows optionally-typed dynamic capabilities
- do not need to spell out the type of field
- allows advance programming
- metaprogramming, functional programming, closures
- supports authoring of domain-sepcific languages
- jenkins file: to create a built pipeline with jenkins
- gradle build script
- requires installation of Java Development Kit (JDK) to work
- allows duck typing: provides the option to use the `def` keyword to determine the type at runtime
- can also have a variable assign a concrete type
- can tell groovy compiler to enforce static typing if needed
- auto generates getter and setter methods at runtime for class members
- contains Abstract Syntax Tree (AST) transformations: provides annotations for generating methods at runtime
- such as defining contructors, equals, hashCode, toString methods
- automatically imports commonly-used packages
- like `java.util.*` and `java.io.*`
- makes the default modifier as public, leading to less verbose code
- semicolons are optional, only required if want to define more than 1 statement on a single line
## Hello World
### python 2
```python
print "Hello World"
```
### python 3
```python
print("Hello World") # "Hello World\n"
print("Hello", "World", sep="/") # "Hello/World"
print("Hello World", end="") # "Hello World"
```
### javascript
```javascript
console.log("Hello World"); // "Hello World"
console.log("Hello", "World"); // "Hello World"
```
### ruby
```ruby
print "Hello World" # takes whatever you give it and prints it to the screen
puts "Hello World" # adds a new (blank) line after the thing you want it to print
p "Hello World" # same as puts
```
### kotlin
```kotlin
// fun for function declaration
fun main() { // main method, a must to have
println("Hello, world") // adds new line after printing
}
```
### java
- java classes are typically organized into packages
- package is a global unique string that usually starts with your domain name in reverse domain order
- ensures globally unique identifiers (e.g.: Main)
- if there are more than 1 class named Main in an app
- can be distinguished by using the package
- each source code file will contain 1 public class
- `public` visible to all classes
- `protected` visible to class they belong and any subclasses
- `private` (most restricted): visible only to class they belong
- `static` can be accessed without creating a class instance
- `final` constant value, value cannot be changed
- `void` means that the method doesn't return any value
```java
package com.example; // package declaration
// class declaration
public class HelloWorld {
// main method: always have the 3 keywords (public, static, void)
// must also receive an array of strings as an argument
public static void main(String[] args) {
// executable code
System.out.println("Hello World"); // adds new line after printing
System.out.print("Hello World"); // no new line is added after
}
}
```
### c#
```c#
public class HelloWorld {
public static void Main() {
System.Console.WriteLine("Hello World"); // adds new line after printing
System.Console.Write("Hello World"); // no new line is added after printing
}
}
```
### c++
```c++
#include // required for printing
int main()
{
std::cout << "Hello, World!";
return 0;
}
```
### groovy
- using dynamic type method
```groovy
println "Hello World"
```
- using static type method
```groovy
class HelloWorld {
static void main(String[] args) {
println("Hello World");
}
}
```
### assembly
```assembly
; x86 32 bit Mac OSX
; to run file, compile and run with the following command
; nasm -f macho hello_world32.asm && ld -macosx_version_min 10.7.0 -o hello_world32 hello_world32.o && ./hello_world32
global start
section .text
start:
push dword msg.len
push dword msg
push dword 1
mov eax, 4
sub esp, 4
int 0x80
add esp, 16
push dword 0
mov eax, 1
sub esp, 12
int 0x80
section .data
msg: db "Hello, world!", 10
.len: equ $ - msg
```
```assembly
; x86_64 64 bit Mac OSX
; to run file, compile and run with the following command
; nasm -f macho64 hello_world64.asm && ld -macosx_version_min 10.7.0 -lSystem -o hello_world64 hello_world64.o && ./hello_world64
global start
section .text
start:
mov rax, 0x2000004 ; write
mov rdi, 1 ; stdout
mov rsi, msg
mov rdx, msg.len
syscall
mov rax, 0x2000001 ; exit
mov rdi, 0
syscall
section .data
msg: db "Hello, world!", 10
.len: equ $ - msg
```
[back to top](#table-of-contents)
## Comments
### python 2 & 3
```python
# Single line comment
"""
multi-line comments
"""
```
### javascript
```javascript
// Single line comment
/*
multi-line comments
*/
```
### ruby
```ruby
# Single line comment
=begin
multi-line comments
=end
```
### java
```java
// Single line comment
/*
multi-line comments
*/
/**
* javadoc comments for classes, javadocs can be used to auto generate documentation documents for code commented with javadocs
*/
/**
* javadoc comments for methods with parameters - example main method
* @param args - an array of string values
*/
```
### c#
```c#
// Single line comment
/*
multi-line comments
*/
```
### c++
```c++
// Single line comment
/*
multi-line comments
*/
```
### assembly
```assembly
; Single line comment
```
[back to top](#table-of-contents)
## Data types
### python
#### 8 main data types
- Text type
- `str`, `x = "Hello World" `, `x = str("Hello World")`
- Numeric types
- `int`, `x = 20 `, `x = int(20)`
- `float`, `x = 20.5`, `x = float(20.5)`
- `complex`, `x = 1j`, `x = complex(1j)`
- Sequence types
- `list`, `x = ["apple", "banana", "cherry"]`, `x = list(("apple", "banana", "cherry"))`
- `tuple`, `x = ("apple", "banana", "cherry")`, `x = tuple(("apple", "banana", "cherry"))`
- `range`, `x = range(6)`, `x = range(6)`
- Mapping type
- `dict`, `x = {"name" : "John", "age" : 36}`, `x = dict(name="John", age=36)`
- Set types
- `set`, `x = {"apple", "banana", "cherry"}`, `x = set(("apple", "banana", "cherry"))`
- frozenset`, `x = frozenset({"apple", "banana", "cherry"})`, `x = frozenset(("apple", "banana", "cherry"))```
- Boolean type
- `bool`, `x = True`, `x = bool(5)`
- Binary types
- `bytes`, `x = b"Hello"`, `x = bytes(5)`
- `bytearray`, `x = bytearray(5)`, `x = bytearray(5)`
- `memoryview`, `x = memoryview(bytes(5))`, `x = memoryview(bytes(5))`
- None type
- `None`, `x = None`
### javascript
#### 1 primitive structural root
- null
- unknown values – a standalone type that has a single value null
#### 2 Structual types
- object
- for more complex data structures
- new Object, new Array, new Map, new Set, new WeakMap, new Date, new ...
#### 6 basic primitive data types
- number
- for numbers of any kind: integer or floating-point, integers are limited by ±(2^53-1) === ±9007199254740991
- contain
- regular numbers
```javascript
let n = 123;
```
- floats
```javascript
let n = 1.23;
```
- special numeric values
- Infinity
```javascript
let n = 1 / 0;
let n2 = Infinity;
```
- -Infinity
- NaN
```javascript
let n = "not a number" / 2; // NaN
```
- bigint
- no maximum limit to a BigInt
```javascript
let bigInt = 1234567890123456789012345678901234567890n; // ends with n
```
- string
- may have zero or more characters, there’s no separate single-character type
- boolean
- true / false.
- undefined
- unassigned values – a standalone type that has a single value undefined
- symbol
- for unique identifiers
```javascript
// id is a new symbol
let id = Symbol();
// can give symbol a description (also called a symbol name), mostly useful for debugging purposes
let _id = Symbol("id2");
// symbol in an object literal
let obj = {
[_id]: 123, // not "id": 123
};
// guaranteed to be unique
let id1 = Symbol("id");
let id2 = Symbol("id");
console.log(id1 == id2); // false
// convert symbol to string
id1.toString(); // "Symbol(id)"
// get symbol description
id1.description; // "id"
```
- Symbols allow us to create “hidden” properties of an object, that no other part of code can accidentally access or overwrite
```javascript
let user = {
// belongs to another code
name: "John",
};
let id = Symbol("id");
user[id] = 1;
console.log(user[id]); // 1
console.log(user); // { name: 'John', [Symbol(id)]: 1 }
```
- benefit of using symbol over string
- objects belongs to another code, and that code also works with them, we shouldn’t just add any fields to it
- symbol cannot be accessed accidentally, the third-party code probably won’t even see it
- Symbols are skipped by for...in loop
```javascript
let id = Symbol("id");
let user = {
name: "John",
age: 30,
[id]: 123,
};
for (let key in user) console.log(key); // name age undefined
```
- Symbol can be cloned with Object.assign
```javascript
let id = Symbol("id");
let user = {
[id]: 123,
};
let clone = Object.assign({}, user);
console.log(clone); // { [Symbol(id)]: 123 }
```
- global symbols
- use if want same-named symbols to be same entities
```javascript
// get symbol by name
let id1 = Symbol.for("id");
let id2 = Symbol.for("id");
console.log(id1 === id2); // true
// get name by symbol, can only use for global symbol
console.log(Symbol.keyFor(id1)); // "id"
```
### java 8
#### 2 major data types
1. Primitive data types
- stored in fastest available memory
- names are all camel case
- Java class library includes helper classes for each primitive
- helper classes support conversion and formatting tools
- `import java.lang.Byte;` import not required from java.lang libraries
- all primitive numeric variables default to 0
```java
public class Main {
private static int myInt; // must be declared as static of a class to have default value
public static void main(String args[]) {
System.out.println(myInt); // 0
}
}
```
- data types
- numbers
- byte
- 8 bits
- -128 to 127
- default value `0`
- helper class `Byte`
- short
- 16 bits
- -32,768 to 32,767
- default value `0`
- helper class `Short`
- int
- 32 bits
- -2,147,483,648 to 2,147,483,647
- default value `0`
- helper class `Integer`
- long
- 64 bits
- -9.22337E+18 to 9.22337E+18
- default value `0L`
- helper class `Long`
- float
- 32 bits
- default value `0.0f` or `0.0F` or `.0f` or `.0F`
- helper class `Float`
- double
- 64 bits
- default value `0.0d` or `0.0D` or `.0d` or `.0D`
- helper class `Double`
```java
double doubleValue = 156.5d;
Double doubleObj = new Double(doubleValue); // declare instance of the double class
int intValue = doubleObj.intValue(); // 156, use helper object to convert to desired numeric data type
```
- characters
- '\u0000' (or 0) to '\uffff' (or 65,535 inclusive)
- default value `'\u0000'`
- booleans
- default value `false`
2. Objects
- an object is an instance of a class
- nonprimitive variables are references to objects
- objects can have multiple references
- Object data types
- String
- a complex object
- is an instance of the string class
- is an array of characters
- string objects are immutable
- reasigning the string value creates a new object
- the old object can be cleared from memory thrown garbage collection process
- helper class is `java.lang.String`, thus import not required
```java
String string1 = new String("Hello");
```
### c++
- it is a strict data typed language
- the data type can be changed implicitly or explicitly
- implicit happens when you have compatible data types
- can assign a short variable to an integer variable
- a float can be assigned to a double value
- must go from smaller to larger for data integrity
- a bool variable can be assigned to an int
- a character can also be assigned to an int
- ``static_cast<>` can be used to change a data type
```c++
double x{45.765};
int y = static_cast(x); // 45
int b = true; // 1
int c = 'c'; // 97
```
#### Fundamental Data Types
- The Microsoft C++ 32-bit and 64-bit compilers recognize the types below.
- If a type name begins with `__`, it is **non-standard**.
#### Recognized integral type names
`int (unsigned int)`, `__int8 (unsigned __int8)`, `__int16 (unsigned __int16)`, `__int32 (unsigned __int32)`, `__int64 (unsigned __int64)`, `short (unsigned short)`, `long (unsigned long)`, `long long (unsigned long long)`
| Type Name | Bytes | Other Names | Range of Values |
|------------------------|:-----:|--------------------------------------------------|----------------------------------------------------------------------------------|
| `int` | 4 | `signed` | −2,147,483,648 to 2,147,483,647 |
| `unsigned int` | 4 | `unsigned` | 0 to 4,294,967,295 |
| `__int8` | 1 | `char` | −128 to 127 |
| `unsigned __int8` | 1 | `unsigned char` | 0 to 255 |
| `__int16` | 2 | `short`, `short int`, `signed short int` | −32,768 to 32,767 |
| `unsigned __int16` | 2 | `unsigned short`, `unsigned short int` | 0 to 65,535 |
| `__int32` | 4 | `signed`, `signed int`, `int` | −2,147,483,648 to 2,147,483,647 |
| `unsigned __int32` | 4 | `unsigned`, `unsigned int` | 0 to 4,294,967,295 |
| `__int64` | 8 | `long long`, `signed long long` | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| `unsigned __int64` | 8 | `unsigned long long` | 0 to 18,446,744,073,709,551,615 |
| `bool` | 1 | — | `false` or `true` |
| `char` | 1 | — | −128 to 127 (default)
**0 to 255 when compiled with `/J`** |
| `signed char` | 1 | — | −128 to 127 |
| `unsigned char` | 1 | — | 0 to 255 |
| `short` | 2 | `short int`, `signed short int` | −32,768 to 32,767 |
| `unsigned short` | 2 | `unsigned short int` | 0 to 65,535 |
| `long` | 4 | `long int`, `signed long int` | −2,147,483,648 to 2,147,483,647 |
| `unsigned long` | 4 | `unsigned long int` | 0 to 4,294,967,295 |
| `long long` | 8 | — (equivalent to `__int64`) | −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| `unsigned long long` | 8 | — (equivalent to `unsigned __int64`) | 0 to 18,446,744,073,709,551,615 |
| `enum` | varies| — | implementation-dependent |
| `float` | 4 | — | approx. 3.4E ± 38 (seven digits) |
| `double` | 8 | — | approx. 1.7E ± 308 (fifteen digits) |
| `long double` | 8 | — | approx. 1.7E ± 308 (fifteen digits) |
| `wchar_t` | 2 | `__wchar_t` | 0 to 65,535 |
#### Notes
- `signed`/`unsigned` modifiers apply to any integral type **except** `bool`.
- `char`, `signed char`, and `unsigned char` are **three distinct types** (affects overloading/templates).
- On MSVC, `int`/`unsigned int` are 4 bytes; avoid assuming `int` size in portable code.
- MSVC also supports sized integer types: `__int8`, `__int16`, `__int32`, `__int64`.
- For precise limits in code, use `` (`std::numeric_limits`).
- `__wchar_t`/`wchar_t`: use the `L` prefix for wide character/string literals.
#### Others
- `&` a reference value (address of)
- `*` identifies a point value
#### Compoimd Types
- string `#include`
- A string is an array of characters
- vector `#include`
- array `#include`
- list `#include`
[back to top](#table-of-contents)
## Variable declaration int
- integer ...-2, -1, 0, 1, 2...
### python 2
```python
# int: -2147483648 ~ 2147483647
integer_name = 123
# long: -9223372036854775808L ~ 9223372036854775807L
long_name = 123L # int beyond int size will automatically be converted to long
```
### python 3
```python
# python 3: int and long are combined into int
integer_name = 123
```
### javascript ES5
```javascript
// method 1
var integer_name;
integer_name = 123; // accessible within the function
// method 2
var integer_name = 123;
```
### javascript ES6
```javascript
// method 1
let integer_name;
integer_name = 123; // accessible only within the block {}
// method 2
let integer_name = 123;
// method 3
const integer_name = 123; // variable value cannot be reassigned
```
### typescript
```typescript
let integer_name: number = 123; // method 1
let integer_name2 = 123; // method 2, not required to declare type if assigning to value
let integer_name3: number; // must declare the value type
integer_name3 = 123;
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
```
### ruby
```ruby
integer_name = 123
```
### java
```java
// public/private/protected static final byte/short/int/long integerName = 123;
/*
public: visible to all classes
protected: visible to class they belong and any subclasses
private (most restricted): visible only to class they belong
static: can be accessed without creating a class instance
final: constant value, value cannot be changed
*/
// byte: -128 ~ 127, 8 bits
byte byteName = 123;
// short: -32768 ~ 32767, 16 bits
short shortName = 123;
// int: -2147483648 ~ 2147483647, -2_147_483_648 ~ 2_147_483_647, 32 bits
int integerName; integerName = 123;
int integerName2 = 123; // default is visible within the same package
// long: -9223372036854775808L ~ 9223372036854775807L, can use _ same as int, 64 bits
long longName1 = 123l; // 123
long longName2 = 123L; // 123
long longName3 = 10_000; // 10000, introduced in java 7, just makes it easier to read
```
### c#
```c#
// var can be used to handle declarations when the data type is unknown
// once a variable is declared with var, the variable cannot be reassigned to a different data type
var variableName = 123;
variableName = "123"; // error CS0029: Cannot implicitly convert type `string' to `int'
// byte: -128 ~ 127, 8 bits
byte byteName = 123; // type Byte
System.Byte byteName2 = 123;
// short: -32768 ~ 32767, 16 bits
short shortName = 123; // type Int16
System.Int16 shortName2 = 123;
// int: -2,147,483,648 ~ 2,147,483,647
int integerName1 = 123; // type Int32
int integerName2 = int.MaxValue; // 2147483647
System.Int32 integerName3 = 123;
// Add const before variable declaration to make it a constant
const int integerName3 = 123;
// long: -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807
long longName1 = 123; // type Int64
long longName2 = long.MaxValue; // 9223372036854775807
System.Int64 longName3 = 123;
// decimal: max value 79,228,162,514,264,337,593,543,950,335
decimal decimalName1 = 123; // type Decimal
decimal decimalName2 = 123m;
decimal decimalName3 = decimal.MaxValue; // 79228162514264337593543950335
System.Decimal decimalName4 = 123;
// use System.Numerics.BigInteger for larger values (need add references to System.Numerics.dll)
```
### c++
```c++
// const unsigned char/short/int/long/long long integer_name = 123;
/*
const: constant value, value cannot be changed
integer are signed by default: can assign both positive & negative values
unsigned integer (use when dealing with bit values): 0 ~ ...
e.g. char: -128 ~ 127
e.g. unsigned char: 0 ~ 255 // 128 + 127 = 255
*/
// char: 1 byte, -128 ~ 127, use C code to print "#include<stdio.h> printf("%d", char_name);"
// 1 char has 8 bits
char char_name;
char_name = 123;
// similar to the rest of int variable declaration
// short/short int: 16 bits, 2 bytes, -32768 ~ 32767
short short_name;
short_name = 123;
short int short_name; short_name = 123;
// similar to the rest of int variable declaration
// int: 16 bits, 4 bytes, -2147483648 ~ 2147483647
int integer_name;
integer_name = 123; // uninitialized
int integer_name = 123; // C-like initialization
int integer_name (123); // Constructor initialization
int age {123}; // C++11 list initialization syntax
// long/long int: 32 bits, 4 bytes, -2147483648 ~ 2147483647 bytes
long long_name;
long_name = 123;
long int long_name;
long_name = 123;
// similar to the rest of int variable declaration
// long long/long long int: 64 bits, 8 bytes, -9223372036854775808 ~ 9223372036854775807
long long long_name;
long_name = 123;
long long int long_name; long_name = 123;
// similar to the rest of int variable declaration
```
[back to top](#table-of-contents)
## Variable declaration float
- float, double
### python 2 & 3
```python
float_name = 1.123
float_name = 0.1123e1 # equals to 1.123
float_name = 0.1123E1 # equals to 1.123
float_name = 1123e-3 # equals to 1.123
float_name = 1123E-3 # equals to 1.123
```
- float have inaccurate values
```python
print(.1 + .2 + .3) # 0.6000000000000001
# use the decimal library to make it accurate
from decimal import *
# do not do this
Decimal(.1) + Decimal(.2) + Decimal(.3) # Decimal('0.6000000000000000055511151231')
# do this: convert float to a string first
x = Decimal(".1") + Decimal(".2") + Decimal(".3") # Decimal('0.6')
f"{x}" # "0.6
print(type(x)) #
```
### javascript ES5
```javascript
var float_name = 1.123;
```
### javascript ES6
```javascript
let float_name = 1.123;
const float_name = 1.123;
```
### typescript
```typescript
let float_name: number = 1.123;
```
### ruby
### java:
```java
// float: 32 bits, 4 bytes
float float_name = 1.123f; // 1.123, have 7 decimal digits
float float_name = (float) 1.123;
// double: 64 bits, 8 bytes
double double_name = 1.123d; // 1.123, have 16 decimal digits
double double_name = 1.123;
// using BigDecimal math class
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double value = .012;
double pSum = value + value + value;
System.out.println(pSum); // 0.036000000000000004
String strValue = Double.toString(value);
System.out.println(strValue); // 0.012
BigDecimal bigValue1 = new BigDecimal(value);
BigDecimal bSum1 = bigValue1.add(bigValue1).add(bigValue1);
System.out.println(bSum1.toString()); // 0.0360000000000000007494005416219806647859513759613037109375
BigDecimal bigValue2 = new BigDecimal(strValue);
BigDecimal bSum2 = bigValue2.add(bigValue2).add(bigValue2);
System.out.println(bSum2.toString()); // 0.036
}
}
```
### c#
```c#
// float: 32 bit max value with 7 decimals of precision 3.402823E+38
float floatName1 = 1.123f; // type Single
float floatName2 = float.MaxValue; // 3.402823E+38
System.Single floatName3 = 1.123f;
// double: 64 bit max value with 15 decimals of precision 1.79769313486232E+308
double doubleName1 = 1.123d; // type Double
double doubleName2 = 1.123; // all floats are double by default
double doubleName3 = double.MaxValue; // 1.79769313486232E+308
System.Double doubleName4 = 1.123;
```
### c++
```c++
// float: 4 bytes
float float_name;
float_name = 1.123; // have 7 decimal digits
// similar to the rest of int variable declaration
// double: 8 bytes
double double_name;
double_name = 1.123; // have 15 decimal digits
// similar to the rest of int variable declaration
// long double: 12 bytes
long double double_name;
double_name = 1.123; // have 19 decimal digits
// similar to the rest of int variable declaration
```
[back to top](#table-of-contents)
## Variable declaration None
### python 2 & 3
```python
variable_name = None
# nan in python
import math
math.inf - math.inf # nan
```
### javascript
```javascript
// undefined is reserved for variables whose values have not yet been set.
let variable_name; // undefined
//null is reserved for variables whose values are explicitly nothing — instead of just “not yet defined.”
let variable_name2 = null;
// NaN is a special numeric value meaning “Not a Number”
let variable_name3 = NaN;
```
### typescript
```typescript
let variable_name: void = undefined; // method 1
let variable_name2 = undefined; // method 2
let variable_name: undefined; // method 3
let variable_name2: void = null;
let variable_name3: number = NaN;
```
### ruby
```ruby
variable_name = nil # nil is returned when no values are assigned, but nothing is displayed on screen
```
### java
```java
String stringName = null;
// NaN is produced if a floating point operation
float floatName = Float.NaN; // NaN
double doubleName = Double.NaN; // NaN
Double x = new Double(-2.0/0.0); // -Infinity
Double y = new Double(0.0/0.0); // NaN
x.isNaN(); // false
y.isNaN(); // true
System.out.println(2.0 / 0); // Infinity
// set infinity value
double inf = Double.POSITIVE_INFINITY; // Infinity
double inf = Double.NEGATIVE_INFINITY; // -Infinty
```
### c#
```c#
string stringName = null;
string stringName2 = String.Empty;
// method 1: use the nullable method
Nullable integerName1 = null;
// method 2: value type requires ? during declaration
int? integerName2 = null;
```
### c++
```c++
#include
int main() {
int* raw = nullptr; // explicit "no object"
if (raw == nullptr) std::cout << "raw is null\n";
}
```
[back to top](#table-of-contents)
## Strings
### python 2 & 3
```python
string_name = "string"
string_name = 'string'
# back slash not required, but will produce a new line if not given
string_name = """multi-line \
string\
"""
# raw strings (ignore escape characters)
string_name = r"\n raw string" # "\n raw string"
len(string_name) # 6
# Character unicode point
# only accepts 1 character
ord("b") # 98
# reverse string
string_name = string_name[::-1] # "gnirts"
string_name = "Gnirts"
string_name = string_name.swapcase() # "gNIRTS"
string_name = string_name.upper() # "GNIRTS"
string_name = string_name.lower() # "gnirts"
# casefold: it is more aggressive than lower(), it removes all case distinctions even in unicode
string_name_casefold = "Hello World ß"
string_name_casefold.casefold() # "hello world ss"
# capitalize string
string_name_caps = "test me"
string_name_caps.title() # "Test Me"
string_name_caps.capitalize() # "Test me"
# Replace string in string, string_name.replace(old, new, max)
string_name = string_name.replace("g", "xxx") # "xxxnirts"
string_name = string_name.replace("x", "g", 1) # "gxxnirts"
# Find character or string in string and return the index of the 1st character, return -1 if not found
string_name.find("x") # 1
string_name.find("v") # -1
# string slicing
# extract characters from a string, from start position to but not including end position
new_string_name = string_name[1:4] # "xxn"
# Split strings, string_name.split(separator, max)
string_name = string_name.split() # ["gxxnirts"] only works for string without spaces
string_name = "test string"
string_name1 = string_name.split() # ["test", "string"]
string_name2 = string_name.split("s") # ["te", "t ", "tring"]
string_name3 = string_name.split("s", 1) # ["te", "t string"]
# Split string into an array of letters
string_name4 = list(string_name) # ['t', 'e', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g']
# Remove empty spaces
string_name = " string "
# remove all left spaces
string_name1 = string_name.lstrip() # "string "
# remove all right spaces
string_name2 = string_name.rstrip() # " string"
# remove all spaces
string_name3 = string_name.strip() # "string"
# Check if string has alphabet and integer characters
string_name3.isalnum() # False
string_name = "123"
string_name.isalnum() # True
string_name = "s 123"
string_name.isalnum() # False
string_name = "s123"
string_name.isalnum() # True
# Check if string has all alphabet characters
string_name3.isalpha() # True
string_name = "A e"
string_name.isalpha() # False
string_name = "a2"
string_name.isalpha() # False
# Check if string has all digit characters
string_name = "123"
string_name.isdigit() # True
string_name = "12 3"
string_name.isdigit() # False
string_name = "12d"
string_name.isdigit() # False
# Join an array of string elements
arr = ["a", "b"]
"_".join(arr) # "a_b"
```
### javascript ES5
```javascript
var stringName = "string";
var stringName = "string";
// back slash required
var stringName =
"multi-line \
string";
stringName.length; // 6
// Character unicode point
string.charCodeAt(stringIndex);
"abc".charCodeAt(1); // 98
// reverse string
stringName.split("").reverse().join(""); // "gnirts"
stringName = stringName.toUpperCase(); // "GNIRTS"
stringName = stringName.toLowerCase(); // "gnirts"
// capitalize string
stringName = stringName.charAt(0).toUpperCase() + stringName.slice(1); // "Gnirts"
// replace 1 string occurance with string, stringName.replace(old, new)
stringName = stringName.replace("G", "xxx"); // "xxxnirts"
let stringName0 = "test_test_123";
// replace all string occurances with string, stringName.replaceAll(old, new)
stringName0 = stringName0.replaceAll("_", " "); // "test test 123"
// extract characters from a string, from start position to but not including end position
newStringName = stringName.substring(1, 4); // "xxn"
// Split string into arrays
stringName = "test string";
stringName1 = stringName.split(); // ["test string"]
stringName2 = stringName.split(""); // ['t', 'e', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g']
stringName3 = stringName.split("s"); // ["te", "t ", "tring"]
```
### javascript ES6 // Almost all of ES5 are included in ES6
```javascript
// back slash not required, but will produce a new line if not given
var stringName = `multi-line \
string`;
let stringName = "string";
const stringName = "string";
// raw strings (ignore escape characters)
String.raw`\n raw string`; // "\n raw string"
```
### typescript
```typescript
let stringName: string = "string";
// declare string and/or other types
let strOrNum: string | number;
strOrNum = "abc";
strOrNum = 123; // can be reassigned to a declared type
```
### ruby
```ruby
string_name = <
signed char sc = -1;
std::cout << sc; // �
std::cout << int(sc); // -1
unsigned char uc = 255;
cout << uc; // �
cout << int(uc); // 255
char16_t u = u'字';
char32_t U = U'𐀀';
char8_t e = u8'é';
```
strings
- C-style strings: an ARRAY of characters, must use double quotes ""
- THIS IS NOT A TRUE STRING, IT IS AN ARRAY OF CHARACTERS!!!!!!!
```c++
char * stringName = "string";
const char * stringName = "string"; // const is normally used
char stringName[] = "string"; // creates array of 7 chars, last char is null "\0"
char stringName[7] = "string"; // need give 7 slots for chars and null char
char stringName[7] = {'s', 't', 'r', 'i', 'n', 'g', 0}; // no 0 = error
char stringName[7] = {'s', 't', 'r', 'i', 'n', 'g', '\0'}; // no '\0' = error
// C++ strings: must add at the top "#include<string>", must use double quotes ""
#include<string>
std::string stringName;
stringName = "string";
// back slash not required, but can use if want to
std::string stringName = "multi-line"
"string";
std::string stringName ("string");
```
[back to top](#table-of-contents)
## Boolean
### python 2 & 3
```python
boolean_name = True
boolean_name = False
not True # False
not False # True
```
### javascript ES5
```javascript
var boolean_name;
boolean_name = true;
var boolean_name = false;
!true; // false
!false; // true
```
- truthy: "xxx", 1, -1, 2.5, true
- falsey: false, 0, "", null, undefined, NaN
### javascript ES6
```javascript
let boolean_name;
boolean_name = true;
let boolean_name = false;
const boolean_name = true;
```
### typescript
```typescript
let isDone: boolean = false;
```
### ruby
```ruby
boolean_name = true
boolean_name = false
```
- truthy: true, 0, 1, -1, "",
- falsey: false, nil
- Check if method exist
- obj.respond_to?(:method)
- example 1
> [1, 2, 3].respond_to?(:push) # true
- example 2
> 123.respond_to?(:next) # true
- example 3: false because array can't be turned into a symbol
> [1, 2, 3].respond_to?(:to_sym) # false
### java
```java
boolean booleanName1 = true;
boolean booleanName2 = false;
boolean booleanName3 = !booleanName2; // true
String sBoolean = "true";
boolean booleanName4 = Boolean.parseBoolean(sBoolean); // true
```
### c#
```c#
type Boolean
bool booleanName = true; // displayed as True when printed
bool booleanName = false; // displayed as False when printed
System.Boolean booleanName = false;
```
### c++: 8 bits
```c++
bool boolean_name; boolean_name = true; // produces a 1 output
bool boolean_name = false; // produces a 0 output
bool boolean_name (true);
bool boolean_name {false};
```
[back to top](#table-of-contents)
## Arithmetic Operators
### python 2
- addition: `+`
- subtraction: `-`
- multiplication: `*`
- division: `3.0/2 # output 1.5, 3/2 output 1`
- modulus: `%`
- exponent: `**`
- floor division: `3//2 # output 1`
### python 3
- division: `3/2 # output 1.5`
- floor division: `3//2 # output 1`
### javascript
- addition: `+`
- subtraction: `-`
- multiplication: `*`
- division: `3/2 // output 1.5`
- modulus: `%`
- exponent: `**`
- floor division: `Math.floor(3/2) // output 1`
### ruby
- addition: `+`
- subtraction: `-`
- multiplication: `*`
- division: `3.0/2 # output 1.5, 3/2 output 1`
- modulus: `%`
- exponent: `**`
- floor division: `3/2.floor`
### java
- addition: `+`
- subtraction: `-`
- multiplication: `*`
- division: `double double_name = 3.0/2; // output 1.5, 3/2 output 1`
- modulus: `%`
- exponent: `Math.pow(3, 2); // output 9`
- floor division: `int integer_name = 3/2; // output 1`
### c#
- addition: `+`
- subtraction: `-`
- multiplication: `*`
- division: `3.0/2; // output 1.5, 3/2 output 1`
- modulus: `%`
- exponent: `Math.Pow(3, 2); // output 9`
- floor division: `3/2; // output 1`
### c++
- addition: `+`
- subtraction: `-`
- multiplication: `*`
- division: `double double_name = 3.0/2 // output 1.5, 3/2 output 1`
- modulus: `%`
- exponent:
- must add this to the top `#include<cmath>`
- `int integer_name = pow(3, 2); // output 9`
- floor division: `3/2 // output 1`
[back to top](#table-of-contents)
## Comparison Operators
### python 2 & 3
- `==` condition is True if both operand have equal contents
```python
list1 = []
list2 = []
list1 == list2 # True
```
- `is` condition is True if both operand points to the same identical object
```python
list1 = []
list2 = []
list1 is list2 # False
list1 = None
list2 = None
list1 is list2 # True
```
- `!=` condition is True if both operand do not have equal contents
- `is not` condition is True if both operand do not points to the same identical object
- `<>` py2 only, condition is True if both operands do not equal contents
- `>` condition is True if right operand is less than left operand
- `<` condition is True if left operand is less than right operand
- `>=` condition is True if right operand is less than or equal to left operand
- `<=` condition is True is left operand is less than or equal to right operand
### javascript
- `==` not type-safe, e.g.: string or int will be automatically converted before comparison, only checks the value
```javascript
var x = 5;
x == 5; // is true
x == "5"; // is also true
```
- `===` string or int will NOT be converted before comparison, checks both the value and type
- NaN and NaN comparison are not equal
- +0 and -0 are equal
```javascript
var x = 5;
x === 5; // is true
x === "5"; // is false
```
- `Object.is(var1, var2);` similar to `===`
- NaN and NaN comparison are equal
- +0 and -0 are not equal
- `!=`
- `!==`
- `>`
- `<`
- `>=`
- `<=`
- `??` Nullish coalescing operator: returns right-hand side operand when left-hand side operand is null or undefined, and otherwise returns its left-hand side operand
```javascript
const foo = null ?? "default string";
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
```
### ruby
- `==`
- `!=`
- `>`
- `<`
- `>=`
- `<=`
- `<=>` Combined Comparison Operator
- `object1.equal?object2`
```ruby
string1 = "string"
string2 = "string"
string1 == string2 # returns true
string1.equal?string2 # returns false
string1.equal?string1 # returns true
num1 = 2
num2 = 5
puts num1 <=> num2 # -1
puts num2 <=> num1 # 1
num1 = 3
num2 = 3
puts num1 <=> num2 # 0
string1 = "b" # looks at only the 1st letter, "bz" will not change the outcome, unless both strings start with the same 1st letter
string2 = "e"
puts string1 <=> string2 # -1
puts string2 <=> string1 # 1
string1 = "c"
string2 = "c"
puts string1 <=> string2 # 0
```
### java
- `==`
- reference comparison
```java
String s1 = new String("string value");
String s2 = new String("string value");
System.out.println(s1 == s2); // false
```
- use equals method to compare string values
```java
String s1 = new String("string value");
String s2 = new String("string value");
System.out.println(s1.equals(s2)); // true
```
- `!=`
- `>`
- `<`
- `>=`
- `<=`
- `instanceof` class membership
```java
String s = "Hello";
if (s instanceof java.lang.String) {
System.out.println(true);
}
```
### c#
- `==`
- `!=`
- `>`
- `<`
- `>=`
- `<=`
### c++
- `==`
- `!=`
- `>`
- `<`
- `>=`
- `<=`
[back to top](#table-of-contents)
## Logical Operators
### python 2 & 3
- `and`
- `or`
- `not`
### javascript
- `&&` and
- `||` or
- `!` not
- truthy and falsey examples
- `truthy1 && truthy2` truthy2
- `falsey && truthy` falsey
- `truthy && falsey` falsey
- `falsey1 && falsey2` falsey1
- `truthy1 || truthy2` truthy1
- `truthy || falsey` truthy
- `falsey1 || falsey2` falsey2
### ruby
- `&&` and
- `||` or
- `!` not
### java
- `&&` and
- `||` or
- `^` exclusive or
- `!` not
### c#
- `&&` and
- `||` or
- `^` exclusive or
- `!` not
### c++
- `&&` and
- `||` or
- `!` not
[back to top](#table-of-contents)
## Getting Input
### python 2
```python
raw_input("What's your name?")
# input must be the same data type as xxx else return an error
input(xxx)
```
### python 3
```python
input("What's your name?")
```
### javascript
```javascript
// install readline-sync package locally via npm i readline-sync
var readlineSync = require("readline-sync"); // import package
var getInput = readlineSync.question("What's your name?");
```
### ruby
```ruby
# print question
print "What's your name?"
# get input
name = gets.chomp
```
### java
- must import scanner library
```java
import java.util.Scanner;
```
```java
// print question
System.out.println("What's your name?");
// get raw input
Scanner scanner = new Scanner(System.in);
// convert raw value to string type
// can read the input only till the space
// It can't read two words separated by a space
// places the cursor in the same line after reading the input
String input = scanner.next();
// reads input including space between the words till the end of line \n
// Once the input is read, positions the cursor in the next line
String input1 = scanner.nextLine();
// convert raw value to int type
Int input2 = scanner.nextInt();
```
### c#
```c#
// print question
System.Console.WriteLine("What's your name?");
// get input
string name = System.Console.ReadLine();
```
### c++
[back to top](#table-of-contents)
## Bitwise Operators
### python 2 & 3
```python
# Each digit is 1 bit, all bitwise operators converts to signed 32-bit integers, except for zero-fill right shift which results to unsigned 32 bit integer
a = 60 # 60 = ...0011 1100
b = 13 # 13 = ...0000 1101
c = 9 # 9 = ...0000 1001
# & is binary AND, return 1 if both a and b are 1
a & b # 12 = ...0000 1100
# | is binary OR, return 1 if either a and or b HAVE a 1
a | b # 61 = ...0011 1101
# ^ is binary XOR, return 1 if both a and b are not 1 or 0
a ^ b # 49 = ...0011 0001
# ~ is binary ones complement, invert everything, 1 change to 0 and vice versa
~a # -61 = ...1100 0011
# << is binary left shift, shift everything to the left by n digit(s)
a << 2 # 240 = ...1111 0000
# >> is binary right shift, shift everything to the right by n digit(s)
a >> 2 # 15 = ...0000 1111
c >> 2 # 3 = ...0000 0010, count the 1s
c = -9 # -9 = ...1111 0111
c >> 2 # -3 = ...1111 1101, count the 0s
# Zero fill right shift, shift everything to the right by n digits(s), leftmost will add n 0s
def zero_fill_right_shift(val, n):
return (val >> n) if val >= 0 else ((val + 0x100000000) >> n)
zero_fill_right_shift(9, 2) # 2 = ...0000 0010, count the 1s
c = -9 # -9 = ...1111 0111
zero_fill_right_shift(-9, 2) # 1073741821 = 0011...1111 1101, count the 0s
```
### javascript
```javascript
// Each digit is 1 bit, all bitwise operators converts to signed 32-bit integers, except for zero-fill right shift which results to unsigned 32 bit integer
let a = 60; // 60 = ...0011 1100
let b = 13; // 13 = ...0000 1101
let c = 9; // 9 = ...0000 1001
// & is binary AND, return 1 if both a and b are 1, count the 1s
a & b; // 12 = ...0000 1100
// | is binary OR, return 1 if either a and or b HAVE a 1
a | b; // 61 = ...0011 1101
// ^ is binary XOR, return 1 if both a and b are not 1 or 0
a ^ b; // 49 = ...0011 0001
// ~ is binary ones complement, invert everything, 1 change to 0 and vice versa, count the 0s
~a; // -61 = ...1100 0011
// << is binary left shift, shift everything to the left by n digit(s)
a << 2; // 240 = ...1111 0000
// >> is Sign-propagating right shift, a binary right shift, shift everything to the right by n digit(s)
a >> 2; // 15 = ...0000 1111
c >> 2; // 3 = ...0000 0010, count the 1s
c = -9; // -9 = ...1111 0111
c >> 2; // -3 = ...1111 1101, count the 0s
// >>> is Zero fill right shift, shift everything to the right by n digits(s), leftmost will add n 0s
c >>> 2; // 2 = ...0000 0010, count the 1s
c = -9; // -9 = ...1111 0111
c >>> 2; // 1073741821 = 0011...1111 1101, count the 0s
```
### ruby
### java
```java
// & is binary AND, return 1 if both a and b are 1, count the 1s
a & b // 12 = ...0000 1100
// | is binary OR, return 1 if either a and or b HAVE a 1
a | b // 61 = ...0011 1101
// ^ is binary XOR, return 1 if both a and b are not 1 or 0
a ^ b // 49 = ...0011 0001
// ~ is binary ones complement, invert everything, 1 change to 0 and vice versa, count the 0s
~a // -61 = ...1100 0011
// << is binary left shift, shift everything to the left by n digit(s)
a << 2 // 240 = ...1111 0000
// >> is Sign-propagating right shift, a binary right shift, shift everything to the right by n digit(s)
a >> 2 // 15 = ...0000 1111
c >> 2 // 3 = ...0000 0010, count the 1s
c = -9 // -9 = ...1111 0111
c >> 2 // -3 = ...1111 1101, count the 0s
// >>> is Zero fill right shift, shift everything to the right by n digits(s), leftmost will add n 0s
c >>> 2 // 2 = ...0000 0010, count the 1s
c = -9 // -9 = ...1111 0111
c >>> 2 // 1073741821 = 0011...1111 1101, count the 0s
```
### c#
```c#
// & is binary AND, return 1 if both a and b are 1, count the 1s
a & b // 12 = ...0000 1100
// | is binary OR, return 1 if either a and or b HAVE a 1
a | b // 61 = ...0011 1101
```
### c++
[back to top](#table-of-contents)
## Increment
### python 2 & 3
- `x = x + 1` increment
- `x += 1`
### javascript
- `x = x + 1;` add 1 now
- `x += 1;` add 1 now
- `++x;` preincrement, add 1 now
- `x++;` postincrement, display without addition now then add 1 later when called again
### ruby
- `x = x + 1` increment
- `x += 1`
### java
- `x = x + 1;`
- `x += 1;`
- `++x;` preincrement, add 1 now
- `x++;` postincrement, display without addition now then add 1 later when called again
### c#
- `x = x + 1;`
- `x += 1;`
- `++x;` preincrement, add 1 now
- `x++;` postincrement, display without addition now then add 1 later when called again
### c++
- `x = x + 1;`
- `x += 1;`
- `++x;` preincrement, add 1 now
- `x++;` postincrement, display without addition now then add 1 later when called again
[back to top](#table-of-contents)
## Arrays and Lists
### python 2 & 3
```python
# Empty list
list_name = []
# List with elements
list_name = [1, "one", True]
# Nested lists
list_name = [1, ["two", 3]]
# Find list size
len(list_name)
# Get index of element, return ValueError if element does not exist
list_name.index(element)
# Add element to list (left to right)
list_name.append(element)
# Add element to list at index
list_name.insert(index, element)
# Extends list by appending elements from the iterable
list_name = [1, 2]
list_name.extend([3, 4]) # [1, 2, 3, 4]
# Access an element
list_name[index]
# Modify an element
list_name[index] = element
# Remove element from list (right to left)
list_name.pop()
# Remove element from list at index
list_name.pop(index)
# Remove any element from list at element
list_name.remove(element)
# Method 1: remove all elements
del list_name[:]
# Method 2: remove all elements
list_name = []
# Method 3: remove all elements, only in python 3
list_name.clear()
Slice notation
# items start through stop-1
list_name[start:stop]
# items start through the rest of the array
list_name[start:]
# items from the beginning through stop-1
list_name[:stop]
# a copy of the whole array
list_name[:]
# start through not past stop, by step
list_name[start:stop:step]
list_name = [1, 2, 3, 4, 5]
list_name[::2] # [1, 3, 5]
# last item in the array
list_name[-1]
# last two items in the array
list_name[-2:]
# everything except the last two items
list_name[:-2]
# all items in the array, reversed
list_name[::-1]
# the first two items, reversed
list_name[1::-1]
# the last two items, reversed
list_name[:-3:-1]
# everything except the last two items, reversed
list_name[-3::-1]
# Reverse an array
list_name.reverse()
# Merge 2 or more arrays together
new_list = list_name + list_name2
# Sort an array in ascending order
list_name = [2, 3, 1, 4]
# method 1
list_name2 = sorted(list_name) # [1, 2, 3, 4]
# method 2
list_name.sort() # [1, 2, 3, 4]
# sort an array of dictionaries in ascending order
dict_name = [{"key_name": value1}, {"key_name": value2}]
# sort by value
dict_name2 = sorted(dict_name, key=lambda k: k["key_name"])
# Sort an array in descending order
# method 1
list_name2 = sorted(list_name2, reverse=True) # [4, 3, 2, 1]
# method 2
list_name.sort(reverse=True) # [4, 3, 2, 1]
# sort an array of dictionaries in descending order
# sort by value
dict_name2 = sorted(dict_name, key=lambda k: k["key_name"], reverse=True)
# Join array into a string
list_name = ["a", "b", "c"]
x = ", ".join(list_name)
print(x) # "a, b, c"
# Split string into an array
y = x.split(", ")
print(y) # ['a', 'b', 'c']
```
### javascript
```javascript
// Method 1: empty list
var list_name = [];
// Method 2: empty list
var list_name = new Array();
// create list of empty elements
var list_name = new Array(3); // [undefined, undefined, undefined]
var list_name = Array.from({ length: 3}); // [undefined, undefined, undefined]
// List with elements
var list_name = [1, "one", true];
var list_name = new Array(3).fill("-") // ["-", "-", "-"]
// Nested lists
var list_name = [1, ["two", 3]];
var list_name = new Array(3).fill(new Array(2).fill("-")) // [["-", "-"], ["-", "-"], ["-", "-"]]
// Modify an element
list_name[index] = element;
// Access an element
list_name[index];
// Remove element from list (right to left)
list_name.pop();
// Remove element from list (left to right)
list_name.shift();
// Remove number of elements (left to right) from index and insert new elements (left to right)
list_name.splice(index, number_of_element);
// Add element to list (left to right)
list_name.push(element);
// Add element to list (right to left)
list_name.unshift(element);
// Add element to list at index (left to right)
list_name.splice(index, 0, new_element1, new_element2...);
// Add & Remove elements to & from list at index (left to right)
list_name.splice(index, number_of_element, new_element1, new_element2...);
// Return the selected elements in an array, as a new array object
list_name.slice();
// Return the elements starting at the given 1st argument,
// and ends at, but does not include, the given 2nd argument
list_name.slice(1, 3);
list_name.slice(1); // if 1 argument is given, return all elements from array from the 1st argument index
// Find list size
list_name.length;
// Remove all elements
list_name = [];
// Merge 2 or more arrays together
list_name1 = [1, 2, 3];
list_name2 = [4, 5, 6];
new_list = list_name1.concat(list_name2);
// Get index of element, return -1 if not present
list_name = ["element1", "element2", "element1"]
list_name.indexOf("element1") // returns index of 0
list_name.indexOf("element1", 1); // returns index of 2
list_name.indexOf("element1", 2); // also returns index of 2
list_name.indexOf("element1", 0); // returns index of 0
// Sort array in ascending order
list_name = [2, 3, 1, 4];
list_name.sort(); // [1, 2, 3, 4] work only only positive integers and strings
list_name = [2, -1, 4, 3];
list_name.sort((a, b) => a - b); // [ -1, 2, 3, 4 ] work for negative and positive integers
// Sort array in descending order
list_name.sort((a, b) => (b - a)); // [4, 3, 2, 1] work for negative and positive integers
list_nameStr = ["b", "a", "c"];
// method 1: most optimal
list_nameStr.sort().reverse(); // ["c", "b", "a"]
// method 2
list_nameStr.sort((a, b) => (a > b ? -1 : 1));
// method 3
list_nameStr.sort((a, b) => b.localeCompare(a));
// Determine whether an array contains a specified element
list_name = ["a", "b", "c", "a"]
console.log(list_name.includes("b")) // true
// Determine whether an array contains a specified element from starting index
console.log(list_name.includes("b", 2) // false
console.log(list_name.includes("a", 2) // true
// Flatten nested arrays
list_name = [1, 2, [3, 4]];
list_name.flat() // [1, 2, 3, 4]
// Check if all elements in array pass the conditional check
function helper(currentValue) {
return currentValue < 3;
}
list_name = [1, 2, 3, 4];
list_name.every(helper); // false
list_name = [1, 2];
list_name.every(helper); // true
```
### typescript
```typescript
// method 1
let numArr: number[] = [1, 2, 3];
let strArr: string[] = ["a", "bc", "def"];
// method 2
let numArr2: Array = [1, 2, 3];
let strArr2: Array = ["a", "bc", "def"];
// declare more than 1 type
// with tuples
let strOrNumArr1: [string, number] = ["a", 1]; // must follow and limited to declared format
// with union
let strOrNumArr2: (string | number)[]; // allows unlimited mixture of number and/or string values in 1 array
```
### ruby
```ruby
# Empty list
list_name = [] # method 1
list_name = Array.new # method 2
# List with elements
list_name = [1, "one", True]
list_name = Array.new(3) # creates 3 slots of nil in array [nil, nil, nil]
list_name = Array.new(3, "new") # creates 3 slots of object in array ["new", "new", "new"]
# Nested lists
list_name = [1, ["two", 3]]
# join elements in array at index into a string (to join all elements, all indexes must be listed)
list_name.values_at(0, 1).join(", ") # "1, two, 3"
# join all elements in array into a string
list_name.join(", ") # "1, two, 3"
# Add element to list (left to right)
# method 1
list_name.push(element);
# method 2
list_name << element;
# Add element to list (right to left)
list_name.unshift("new") # ["new", 1, ["two", 3]]
# delete element from list (right to left)
list_name.pop() # ["new", 1]
# delete element from list (left to right)
list_name.shift() # [1]
# concat 2 arrays
# method 1
[1] + [2] # [1, 2]
# method 2
[1].concat([2]) # [1, 2]
# find length of array
[1, 2].size # 2
# check if element exist in array
[1, 2].include?(1) # true
# count how many similar elements are in the array
[1, 2, 1].count(1) # 2
# check if array is empty
[1, 2].empty? # false
# Add 0 to 10 to an array
(0..10).to_a # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Add 0 to 10 excluding 10 to an array
(0...10).to_a # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Access an elment
list_name[index]
# Sort an array in ascending
list_name = [3, 4, 1, 2]
# method 1
list_name1 = list_name.sort # [1, 2, 3, 4]
# method 2
list_name.sort! # [1, 2, 3, 4]
# Reverse sort an array, only works on already sorted array
# arrays that are not sorted will be reversed without sorting
# method 1 (modify list_name temporarily)
list_name1 = list_name.reverse # [4, 3, 2, 1]
# method 2 (directly modify list_name)
list_name.reverse!
# Modifies every value in an array
# (modify list_name temporarily)
# method 1
list_name2 = list_name.collect {|num| num * 2} # [8, 6, 4, 2]
# method 2
list_name2 = list_name.map {|num| num * 2} # [8, 6, 4, 2]
# (directly modify list_name)
# method 1
list_name.collect! {|num| num * 2} # [8, 6, 4, 2]
# method 2
list_name.map! {|num| num / 2} # [4, 3, 2, 1]
```
### java
```java
// Arrays: can only have 1 data type: string, int, etc.
// printing this only shows the memory
// Empty string array of desired array size
String[] string_array = new String[length_of_desired_array];
// New string array with elements inside
String [] string_array = new String [] {string1, string2,...}; // Method 1
String[] string_array = {string1, string2,...}; // Method 2
// Add string array element, limited to array size
// Modify string array element value
string_array[index] = element;
// Access an element
string_array[index];
// Find array size
string_array.length;
// Sort array, can sort numbers, strings, etc.
// must import
// import java.util.Arrays;
String[] sourceArr = {"orange", "apple", "pear"};
Arrays.sort(sourceArr); // {"apple", "orange", "pear"}
// Copy array
int sourceArrStartingIndex = 1;
int destinationArrStartingIndex = 0;
int copiedArrLen = 2;
String[] copiedArr = new String[copiedArrLen];
System.arraycopy(sourceArr, sourceArrStartingIndex, copiedArr, destinationArrStartingIndex, copiedArrLen); // {"apple", "pear"}
// multidimensional array
String[][] states = new String[3][2];
states[0][0] = "Japan";
states[0][1] = "Tokyo";
// Arraylists: it is a class, extends the AbstractList class and implements List interface
// can be instantiated
// used to create a dynamic array that contains objects
// creates an array of objects where the array can grow dynamically
// can only have 1 data type: string, int, etc.
// import java.util.ArrayList; // Must import to use
// Empty string arrayList
ArrayList arrayList = new ArrayList();
// Add element to string arrayList (left to right)
arrayList.add(element);
// Modify an element at index
arrayList.set(index, element);
// Access an element
arrayList.get(index);
// Remove element from arrayList at index
arrayList.remove(index);
// Find arrayList size
arrayList.size();
// Remove all elements
arrayList.clear();
// List: it is an interface, extends the Collection framework
// cannot be instantiated
// used to create a list of elements(objects) which are associated with their index numbers
// creates a collection of elements that are stored in a sequence and they are identified and accessed using the index
// print this shows the actual array
// import java.util.List; // must import to use
// import java.util.ArrayList; // Must import to use
List list = new ArrayList<>(); // from java 7 onwards redundent is not required, can just use <>
// Add element to string List (left to right)
list.add(element);
// Remove element from list at index
list.remove(index);
// Access an element
list.get(index);
// Find index of an element
list.indexOf(element);
```
### c#
- Arrays: can only have 1 data type: string, int, etc. (size cannot be modified after declaration)
```c#
// Empty string array of desired array size
string[] stringArray = new string[lengthOfDesiredArray];
// New string array with elements inside
string [] stringArray2 = new string [] {string1, string2, ...}; // Method 1, size is determined by number of elements declared
string [] stringArray2 = new string [2] {string1, string2}; // Method 2, size is determined by the array size declared
string[] stringArray3 = {string1, string2, ...}; // Method 3, size is determined by number of elements declared
string[] stringArray5 = new[] {string1, string2, ...}; // Method 4
var stringArray6 = new[] {string1, string2, ...}; // Method 5, use var to auto determine data type
// Multi-dimensional Rectangular Arrays
int[] rectArray = new int[3, 5];
int[] rectArray2 = new int[3, 5] {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15}
};
// Multi-dimensional Jagged Arrays
int[] jaggedArray = new int[3][]; // create an array of 3 empty arrays
jaggedArray[0] = new int[4]; // create an array of size 4
jaggedArray[1] = new int[5]; // create an array of size 5
jaggedArray[2] = new int[3]; // create an array of size 3
// Add string array element, limited to array size
// Modify string array element value
stringArray[index] = element;
// Access an element
stringArray[index];
rectArray2[index1, index2];
jaggedArray[0][0];
// Find array size
string[] strArr = {"a", "b", "c"};
strArr.Length; // 3
// Find index of an element in an array
string element = "a";
int index = System.Array.IndexOf(strArr, element); // 0
// Clear the element in the array (0 for int, false for bool, null for other objects), exclude the endIndex value
int startIndex = 0;
int endIndex = 1;
System.Array.Clear(strArr, startIndex, endIndex);
// Copy the elements into a new array
int firstFewElem = 3;
string[] copiedStrArr = new string[3];
System.Array.Copy(strArr, copiedStrArr, firstFewElem);
// Sort (ascending order)
System.Array.Sort(strArr);
// Reverse (only works on sorted arrays)
System.Array.Reverse(strArr); // ["c", "b", "a"]
System.Array.Reverse(strArr); // ["a", "b", "c"]
// Join elements of an array into a string
System.String.Join("", strArr); // "abc"
System.String.Join(",", strArr); // "a,b,c"
```
- List (dynamic array)
```c#
// Empty int array of desired array size
System.Collections.Generic.List intList = new System.Collections.Generic.List(); // empty list
System.Collections.Generic.List intList2 = new System.Collections.Generic.List() {1, 2, 3, 4}; // list with values
// import to write less code when declaring
using System.Collections.Generic;
List intList3 = new List(); // empty list
List intList4 = new List() {1, 2, 3, 4}; // list with values
// Add 1 new element to the list (left to right)
intList4.Add(5); // [1, 2, 3, 4, 5]
// Add a range of elements to the list with an array
intList4.AddRange(new int[3] {6, 7, 8}); // [1, 2, 3, 4, 5, 6, 7, 8]
// Find index of an element in a list (return -1 if element is not found)
intList4.IndexOf(2); // 1
// Find last index of elements with similar values in a list
int[] intList5 = new List() {1, 2, 1, 3};
intList5.LastIndexOf(1); // 2
// Get length of list
intList4.Count; // 8
// Remove an element at element in list
intList4.Remove(2); // [1, 3, 4, 5, 6, 7, 8]
// Remove an element at index of list
intList4.RemoveAt(0); // [3, 4, 5, 6, 7, 8]
// Remove all elements from the list
intList4.Clear(); // [];
```
- ArrayList (dynamic list of multiple data types, does not offer the best performance)
```c#
// Empty array list
System.Collections.ArrayList list = new System.Collections.ArrayList(); // empty list
// Add 1 new element to the list (left to right)
list.Add(1); // [1]
list.Add("abc") // [1, "abc"]
// methods are similar to List
```
### c++
```c++
// Arrays
// Empty int array of desired array size
int int_array[length_of_desired_array];
// New int array with elements inside
int int_array [length_of_desired_array] {element1, element2,...}; // size declared
int int_array[] = {element1, element2,...}; // size automatically calculated
// Assign int element, limited to array size
// Modify int element value
int_array[index] = element;
// Access an element
int_array[index];
// Find array size: size of array (bytes) / size of an element of an array (bytes)
sizeof(int_array) / sizeof(int_array[0]);
// Vectors: a type of dynamic array
#include // Must import to use
// Empty int vector of desired vector size, each element of 0 value will automatically be included
std::vector int_vector (length_of_desired_array);
// New int vector with elements inside
std::vector int_vector {element1, element2,...};
// New int vector with length of desired array and all value in parameter
// Method 1
std::vector int_vector (length_of_desired_array, constant_value_for_all_elements);
// Method 2
std::vector int_vector;
int_vector.assign(length_of_desired_array, constant_value_for_all_elements);
// Assign int element
int_vector[index] = element;
// Access an element
int_vector[index];
int_vector.at(index);
// Add element to vector (left to right), vector size will automatically increase
int_vector.push_back(element);
// Add element to vector at index
std::vector::iterator it; // Must create iterator for inserting or emplacing to work
it = int_vector.begin() // Set it at index 0
// insert method: copies or moves the elements into the container by calling copy constructor or move constructor
int_vector.insert(it + index, element); // Add element at index
// emplace method: elements are constructed in place, no copy or move operations are performed (better performance)
int_vector.emplace(it + index, element); // Add element at index
// Remove element from vector at index
std::vector::iterator it; // Must create iterator for erase to work
it = int_vector.begin() // Set it at index 0
int_vector.erase(it + index) // Remove element at index
int_vector.erase(it + index, it + index) // Remove a range of elements in the vector
// Remove element from vector (right to left)
int_vector.pop_back(); // does not return value
// Find vector size
int_vector.size();
// Resize vector
int_vector.resize(length_of_desired_array);
// Remove all elements
int_vector.clear();
```
[back to top](#table-of-contents)
## Conditional Statement
### python 2 & 3
```python
# If else statement
if condition_a:
do_A
elif condition_b:
do_B
else:
do_something_else
# Ternary operator
do_A if condition_a else do_B
# Switch Statement is not available in python, but can create similar function
def switch(choice):
case = {
1: do_A,
2: do_B,
}
case.get(choice, do_something_else)
# comparing between 2 objects (array, dictionaries, etc.) is allowed
x = [1, 2, 3]
y = [1, 2, 3]
x == y # returns True
```
### javascript
```javascript
// If else statement
if (condition_a) {
do_A;
} else if (condition_b) {
do_B;
} else {
do_something_else;
}
// Ternary operator
condition_a ? do_A : do_B;
// Switch statement
switch (choice) {
case choice_A:
do_A;
break;
case choice_B:
do_B;
break;
default:
do_something_else;
}
// comparing between 2 objects (array, object, etc.) is NOT allowed
var x = [1, 2, 3];
var y = [1, 2, 3];
x === y ? true : false; // returns false
// solution: use JSON.stringify()
JSON.stringify(x) === JSON.stringify(y) ? true : false; // return true
```
### ruby
```ruby
# If else statement
if condition_a
do_A
elsif condition_b
do_B
else
do_something_else
end
# Unless statement
condition_variable = boolValue
do_A unless condition_variable
# Unless else statement
# Check if something is false
unless condition_a
do_A
else
do_something_else
end
# check if a string exist in a string
if word.include? alphabet
do_something
end
# check if value is nil, if not nil return false
object.nil? # if object != nil returns false, else returns true
# check if array, hash, set, string is empty, return true if empty else false
object.empty? # if object == [] or {} or "" or Set.new, return true
# Ternary operator
condition_a ? (do_A) : (do_B);
# example 1
puts true ? "yes" : "no"
# example 2
true ? (puts "yes") : (puts "no")
# Simpler if
do_A if condition_a
# One line Unless
do_A unless condition_a # do_A if condition_a is false
# Case expression (similar to switch statement)
case choice
when choice_A:
do_A;
when choice_B:
do_B;
else
do_something_else
end
# Conditional Assignment: assign only if variable is nil
favorite_book = nil
favorite_book ||= "book 1"
puts favorite_book # "book 1"
favorite_book ||= "book 2"
puts favorite_book # "book 1"
```
### java
```java
// If else statement
if (condition_a) {
do_A;
} else if (condition_b) {
do_B;
} else {
do_something_else;
}
// {} not required if statement is a single line
if (condition_a)
do_A; // Single line statement
else if (condition_b)
do_B; // Single line statement
else
do_something_else; // Single line statement
// Ternary operator
condition_a ? do_A : do_B;
//Using Boolean Value for Return:
boolean result = condition_a ? true : false;
// Switch statement
switch(choice) { // choice value can only be primitive values in java 7, since java 8 strings are also accepted
case choice_A:
do_A;
break;
case choice_B:
do_B;
break;
default:
do_something_else;
break; // not required, but good to have in Java
}
```
### c#
```c#
// If else statement
if (condition_a) {
do_A;
} else if (condition_b) {
do_B;
} else {
do_something_else;
}
// Ternary operator
condition_a ? do_A : do_B;
// Switch statement
switch(choice) {
case choiceA:
doA;
break;
case choiceB:
doB;
goto doSomethingSpecial; // go to a special case that is written outside the switch statement and run it (not advised to use it
default:
do_something_else;
break;
}
doSomethingSpecial:
doingSomething;
```
### c++
```c++
// If else statement
if (condition_a) {
do_A;
} else if (condition_b) {
do_B;
} else {
do_something_else;
}
// {} not required if statement is a single line
if (condition_a)
do_A; // Single line statement
else if (condition_b)
do_B; // Single line statement
else
do_something_else; // Single line statement
// Ternary operator
condition_a ? do_A : do_B;
// Null coalescing operator
return_this_variable_value_if_not_null ?? else_return_this_value
// Switch statement
switch(choice) {
case choice_A:
do_A;
break;
case choice_B:
do_B;
break;
default:
do_something_else;
}
```
[back to top](#table-of-contents)
## Loops
### python 2
```python
# While loop
# declare_initial_conditional_value
i = 0
# Set condition
while i<5: # Start from 0 to 4
do_this
# Include condition_increment_or_decrement
i += 1
# Can use break, continue, and pass statements to add additional functionality, or not use any
break # Breaks out of the current closest enclosing loop
continue # Goes to the top of the closest enclosing loop
pass # Does nothing at all
# For loop
# range() creates a list in python 2
# Looping with xrange()
for i in xrange(5): # Starts from 0 to 4 (5 - 1)
do_this
# Can use break, continue, and pass statements to add additional functionality, or not use any
break # Breaks out of the current closest enclosing loop
continue # Goes to the top of the closest enclosing loop
pass # Does nothing at all
# Looping with xrange() and multiple parameters
for i in xrange(0, 5, 2): # Start from 0 to 4 at every 2 steps (0,2,4)
do_this
# Reverse loop
for i in xrange(4, -1, -1): # Start from 4 to 0 at every -1 steps
do_this
# Looping and getting each value
for value in list_name: # [i1_value, i2_value, i3_value,...]
print value
# Looping and getting index and value
for index, value in enumerate(list_name):
print index, value # output index, value
```
### python 3
```python
# For loop
# Looping with range()
for i in range(5): # Starts from 0 to (5 - 1)
do_this
# Can use break, continue, and pass statements to add additional functionality, or not use any
break # Breaks out of the current closest enclosing loop
continue # Goes to the top of the closest enclosing loop
pass # Does nothing at all
# Looping with range() and multiple parameters
for i in range(0, 5, 2): # Start from 0 to 4 at every 2 steps (0,2,4)
do_this
# Reverse loop
for i in range(4, -1, -1): # Start from 4 to 0 at every -1 steps
do_this
# Looping and getting each value
for value in list_name: # [value1, value2, value3,...]
print(value)
# Looping and getting index and value
for index, value in enumerate(list_name):
print(index, value) # output index, value
# Loops and getting both key and value of a dict
x = { "one": 1, "two": 2}
for k, v in x.items():
print(f"k: {k}, v: {v}")
```
### javascript ES5
```javascript
// While loop
// declare_initial_conditional_value
var i = 0;
// Set condition
while (i < 5) {
// Start from 0 to 4
do_this;
// Include condition_increment_or_decrement;
i++;
// Can use break or continue to add additional functionality, or not use any
break; // Breaks out of the current closest enclosing loop
continue; // Goes to the top of the closest enclosing loop
}
// Do While loop
var i = 0;
do {
do_this;
i++;
} while (i < 5);
// For loop
for (var i = 0; i < 5; i++) {
// Start from 0 to 4
do_this;
// Can use break or continue to add additional functionality, or not use any
break; // Breaks out of the current closest enclosing loop
continue; // Goes to the top of the closest enclosing loop
}
// Reverse loop
for (var i = 4; i >= 0; i--) {
// Start from 4 to 0
do_this;
}
// forEach loop
// Looping through a list while calling a function
list_name.forEach(function (value, index, list) {
// do not need to include all 3 parameters, but must be in order
console.log(index, value, list); // outputs index value list
});
```
### javascript ES6: Use let in loops when declaring
```javascript
// For of loop
// Looping and getting each value
for (let value of list_name) {
// [value1, value2, value3,...]
console.log(value); // output value
}
// Looping and getting index and value
for (let index_and_value of list_name.entries()) {
console.log(index_and_value); // output a list [index, value]
}
// For in loop
for (let index in list_name) {
console.log(list_name[index]);
}
// For in loop normally used to get values from objects (hash table, dictionaries) than to arrays
// object = {key1:value1, key2:value2,...}
for (let key in object) {
console.log(object[key]); // outputs value, normally calling this way will not output value from objects
}
```
### ruby
```ruby
# While loop
# declare_initial_conditional_value
i = 0
# Set condition
while i<5 do # Start from 0 to 4, do keyword is not mandatory
do_this
# Include condition_increment_or_decrement
i += 1
end
# Until loop, backward while loop
i = 0
until i == 4 # Start from 0 to 4
i += 1
end
# For loop, with ... (3 dots)
for i in numStart...numEnd # for i in the range numStart up to but don't include numEnd
do_this
end
# For loop, with .. (2 dots)
for i in numStart..numEnd ## for i in the range numStart up to and include numEnd
dot_this
end
# Loop method, an infinite loop, requireds break to stop loop
i = 4
loop do
i -= 1
break if i ==0 # Breaks out of the current closest enclosing loop
end
# Next keyword: used to skip over certain steps in loop
for i in 0...5
next if i % 2 == 0 # do not do anything if i is an even number
do_this
end
# Each Iterator
array = [1, 2, 3, 4, 5]
array2 = []
array.each { |value| # Method 1: using {}
value += 10
array2.push(value)
}
puts array2 # [11, 12, 13, 14, 15]
array3 = []
array2.each do |value| # Method 2: using do keyword
value -= 10
array3.push(value)
end
puts array3 # [1, 2, 3, 4, 5]
# Iterating over Multidimensional Arrays with Each Iterator
multiArray = [[1, 2], [3, 4], [5, 6]]
multiArray.each {
|sub_array| sub_array.each {
|value| do_something
}
}
# Times Iterator
n.times { do_this } # do_this will repeat n times
# Upto Iterator
# method 1: number
0.upto(5) { |num| print num, " " } # 0 1 2 3 4 5
# method 2: alphabet
"A".upto("D") { |letter| prints letter, " " } # A B C D
# Downto Iterator, "string" don't work
100.downto(95) { |num| print num, " " } # 100 99 98 97 96 95
```
### java
```java
// While loop
// declare_initial_conditional_value
int i = 0;
// Set condition
while (i<5) { // Start from 0 to 4
doThis;
// Include condition_increment_or_decrement;
i++;
// Can use break or continue to add additional functionality, or not use any
break; // Breaks out of the current closest enclosing loop
continue; // Goes to the top of the closest enclosing loop
}
// Do while loop: execute first before setting conditions
// declare_initial_conditional_value
int i = 0;
do { // Start from 0 to 4
doThis;
// Include condition_increment_or_decrement;
i++;
// Set condition
} while (i<5);
// For loop
for (int i=0; i<5; i++) { // Start from 0 to 4
doThis;
// Can use break or continue to add additional functionality, or not use any
break; // Breaks out of the current closest enclosing loop
continue; // Goes to the top of the closest enclosing loop
}
// Reverse loop
for (int i=4; i>=0; i--) { // Start from 4 to 0
doThis;
}
// for each loop, can also loop collections with iterators
char[] chars = {'H', 'e', 'l', 'l', 'o'}; // an array can only have a single data type
for (char c : chars) { // for each element in the array
doThis;
}
// some more methods of implementing loops in java while dealing with arrays
int [] arr={1,2,3,4,5};
for(int num:arr)
{
System.out.println(num);
}
```
### c#
```c#
// While loop
// declare_initial_conditional_value
int i = 0;
// Set condition
while (i<5) { // Start from 0 to 4
do_this;
// Include condition_increment_or_decrement;
i++;
// Can use break or continue to add additional functionality, or not use any
break; // Breaks out of the current closest enclosing loop
continue; // Goes to the top of the closest enclosing loop
}
// Do while loop: execute first before setting conditions
// declare_initial_conditional_value
int i = 0;
do { // Start from 0 to 4
do_this;
// Include condition_increment_or_decrement;
i++;
// Set condition
} while (i<5);
// For loop
for (int i=0; i<5; i++) { // Start from 0 to 4
do_this;
// Can use break or continue to add additional functionality, or not use any
break; // Breaks out of the current closest enclosing loop
continue; // Goes to the top of the closest enclosing loop
}
// Reverse loop
for (int i=4; i>=0; i--) { // Start from 4 to 0
do_this;
}
// For each loop: cycles through every item in an array or collection (List)
// Modifications of an array or collection is no