Programming Examples & Algorithms
Browse foundational and interview-ready code templates across all 14 runtimes. Click any example to launch and test it live in the online compiler IDE.
Hello World
Basic standard output in C
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Factorial & Recursion
Recursive computation of factorial numbers in C
#include <stdio.h>
long long factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
int numbers[] = {3, 5, 7, 10};
int count = sizeof(numbers) / sizeof(numbers[0]);
printf("Factorial Computations in C:\n");
for (int i = 0; i < count; i++) {
printf("%d! = %lld\n", numbers[i], factorial(numbers[i]));
}
return 0;
}
Fibonacci Sequence
Compute Fibonacci numbers iteratively
#include <stdio.h>
void printFibonacci(int n) {
long long t1 = 0, t2 = 1, nextTerm;
printf("Fibonacci Series (%d terms): ", n);
for (int i = 1; i <= n; ++i) {
printf("%lld ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
printf("\n");
}
int main() {
int terms = 10;
printFibonacci(terms);
return 0;
}
Bubble Sort
Sort an array of integers in ascending order
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int data[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(data) / sizeof(data[0]);
printf("Unsorted array: ");
for (int i = 0; i < n; i++) printf("%d ", data[i]);
printf("\n");
bubbleSort(data, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) printf("%d ", data[i]);
printf("\n");
return 0;
}
Hello World
Basic C++ console output
#include <iostream>
int main() {
std::cout << "Hello, World! C++" << std::endl;
return 0;
}
Binary Search Algorithm
O(log n) search on a sorted std::vector in C++
#include <iostream>
#include <vector>
#include <algorithm>
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int main() {
std::vector<int> data = {3, 9, 14, 19, 27, 33, 42, 55, 68, 77, 91};
int target = 42;
int idx = binarySearch(data, target);
std::cout << "Target " << target << " found at index: " << idx << std::endl;
return 0;
}
Vector & Algorithms
Using modern std::vector and std::sort
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {45, 12, 89, 7, 23, 64};
std::sort(numbers.begin(), numbers.end());
std::cout << "Sorted numbers: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
OOP Class & Encapsulation
Class with private fields, constructor, and methods
#include <iostream>
#include <string>
class BankAccount {
private:
std::string owner;
double balance;
public:
BankAccount(std::string name, double initialBalance) : owner(name), balance(initialBalance) {}
void deposit(double amount) {
if (amount > 0) balance += amount;
}
void display() const {
std::cout << "Account Owner: " << owner << " | Balance: $" << balance << std::endl;
}
};
int main() {
BankAccount myAccount("Alex Developer", 1250.75);
myAccount.deposit(500.0);
myAccount.display();
return 0;
}
Hello World
Standard print output
print("Hello, World from Python!")
Palindrome Checker & Word Stats
String reversal, cleaning, and palindrome detection
def is_palindrome(s: str) -> bool:
clean = "".join(c.lower() for c in s if c.isalnum())
return clean == clean[::-1]
test_phrases = [
"A man, a plan, a canal: Panama",
"race a car",
"Was it a car or a cat I saw?",
"Online GDB Python Compiler"
]
print("Palindrome Analysis:")
for phrase in test_phrases:
result = "✓ PALINDROME" if is_palindrome(phrase) else "✗ NOT palindrome"
print(f"- "{phrase}" -> {result}")
Data Analysis & Dicts
Dictionary manipulation and list comprehensions
scores = {"Alice": 95, "Bob": 82, "Charlie": 88, "Diana": 98}
top_students = [name for name, score in scores.items() if score > 85]
avg_score = sum(scores.values()) / len(scores)
print(f"Top students: {top_students}")
print(f"Class average: {avg_score:.2f}")
Prime Number Sieve
Check primality using square-root threshold
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
primes = [x for x in range(2, 50) if is_prime(x)]
print(f"Primes under 50: {primes}")
Hello World
Basic Java class and main method
class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Matrix Transpose & 2D Array
Transpose a 3x3 matrix in Java
class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Original Matrix:");
printMatrix(matrix);
int[][] transpose = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("\nTransposed Matrix:");
printMatrix(transpose);
}
private static void printMatrix(int[][] mat) {
for (int[] row : mat) {
for (int val : row) {
System.out.printf("%3d", val);
}
System.out.println();
}
}
}
Binary Search Algorithm
Search an integer in a sorted array in O(log n)
class Main {
public static int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] sorted = {2, 4, 8, 16, 32, 64, 128, 256, 512};
int target = 64;
int result = binarySearch(sorted, target);
System.out.println("Element " + target + " found at index: " + result);
}
}
ArrayList & Stream Filter
Filter, map, and print collections with Java 8+ Streams
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> names = Arrays.asList("Anna", "Bob", "Alexander", "David", "Andrew");
System.out.println("Names starting with 'A':");
names.stream()
.filter(n -> n.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Hello World
Console greeting in Node.js
console.log("Hello, World from JavaScript!");
Array Reduce & Frequency Map
Count and aggregate array items using reduce
const languages = ['C', 'Python', 'JavaScript', 'Go', 'Python', 'Rust', 'JavaScript', 'Python'];
const frequency = languages.reduce((acc, lang) => {
acc[lang] = (acc[lang] || 0) + 1;
return acc;
}, {});
console.log("Programming Language Frequency:");
Object.entries(frequency)
.sort(([, a], [, b]) => b - a)
.forEach(([lang, count]) => {
console.log(`• ${lang.padEnd(12)}: ${count} occurrence(s)`);
});
Two Sum Hash Map
Find two numbers adding up to target in O(n) time
function twoSum(nums, target) {
const map = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (map.has(complement)) {
return [map.get(complement), i];
}
map.set(nums[i], i);
}
return [];
}
const nums = [2, 7, 11, 15];
const target = 9;
const result = twoSum(nums, target);
console.log(`Indices for target ${target}: [${result.join(', ')}]`);
console.log(`Values: ${nums[result[0]]} + ${nums[result[1]]} = ${target}`);
Async/Await & Promises
Asynchronous concurrency using Promises
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function fetchUserData() {
console.log("Fetching user profile...");
await sleep(200);
return { id: 101, username: "dev_expert", status: "online" };
}
(async () => {
const user = await fetchUserData();
console.log("Data resolved:", JSON.stringify(user, null, 2));
})();
Hello World
Basic C# Program and Main method
using System;
public class Program {
public static void Main() {
Console.WriteLine("Hello, World from C#!");
}
}
Dictionary & Word Frequency
Count and rank word occurrences with Dictionary in C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public static void Main() {
string text = "the quick brown fox jumps over the lazy dog and the clever fox";
var words = text.Split(' ');
var frequencies = new Dictionary<string, int>();
foreach (var word in words) {
frequencies[word] = frequencies.GetValueOrDefault(word, 0) + 1;
}
Console.WriteLine("Word Frequencies in C#:");
foreach (var pair in frequencies.OrderByDescending(p => p.Value)) {
Console.WriteLine($"{pair.Key,-10} -> {pair.Value}");
}
}
}
LINQ Query & Filtering
Declarative data manipulation using C# LINQ
using System;
using System.Linq;
using System.Collections.Generic;
public class Program {
public static void Main() {
var numbers = new List<int> { 12, 5, 8, 23, 44, 17, 30, 2 };
var evenSorted = numbers
.Where(n => n % 2 == 0)
.OrderBy(n => n)
.ToList();
Console.WriteLine("Even numbers sorted:");
evenSorted.ForEach(n => Console.Write(n + " "));
Console.WriteLine();
Console.WriteLine("Sum of Evens: " + evenSorted.Sum());
}
}
OOP Class & Properties
Classes, auto-properties, and encapsulation in C#
using System;
public class BankAccount {
public string Owner { get; }
public decimal Balance { get; private set; }
public BankAccount(string owner, decimal initialBalance) {
Owner = owner;
Balance = initialBalance;
}
public void Deposit(decimal amount) {
if (amount > 0) Balance += amount;
}
public void Withdraw(decimal amount) {
if (amount > 0 && amount <= Balance) Balance -= amount;
}
}
public class Program {
public static void Main() {
var account = new BankAccount("Sarah", 500m);
account.Deposit(250m);
account.Withdraw(100m);
Console.WriteLine($"Account: {account.Owner} | Final Balance: ${account.Balance}");
}
}
Hello World
Basic Go main package and Println
package main
import "fmt"
func main() {
fmt.Println("Hello, World from Go!")
}
Structs & Methods
Idiomatic Go struct types and method receivers
package main
import (
"fmt"
"math"
)
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c Circle) Circumference() float64 {
return 2 * math.Pi * c.Radius
}
func main() {
circles := []Circle{{Radius: 2.5}, {Radius: 5.0}, {Radius: 10.0}}
fmt.Println("Geometric Computations in Go:")
for _, c := range circles {
fmt.Printf("Radius: %4.1f | Area: %6.2f | Circumference: %6.2f\n",
c.Radius, c.Area(), c.Circumference())
}
}
Slices & Maps
Working with Go dynamic slices and key-value maps
package main
import "fmt"
func main() {
salaries := map[string]int{
"Alice": 95000,
"Bob": 82000,
"Charlie": 105000,
}
fmt.Println("Engineering Salaries:")
for name, salary := range salaries {
fmt.Printf("- %-10s: $%d\n", name, salary)
}
}
Goroutines & Channels
Concurrent pipeline processing with channels in Go
package main
import (
"fmt"
"time"
)
func worker(id int, ch chan string) {
time.Sleep(100 * time.Millisecond)
ch <- fmt.Sprintf("Worker %d completed task", id)
}
func main() {
ch := make(chan string, 3)
for i := 1; i <= 3; i++ {
go worker(i, ch)
}
for i := 1; i <= 3; i++ {
msg := <-ch
fmt.Println(msg)
}
}
Hello World
Standard fn main in Rust
fn main() {
println!("Hello, World from Rust!");
}
Structs & Trait Implementation
Struct methods and method receivers in Rust
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn new(width: u32, height: u32) -> Self {
Rectangle { width, height }
}
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle::new(30, 50);
let rect2 = Rectangle::new(10, 40);
let rect3 = Rectangle::new(60, 45);
println!("Rectangle 1 area: {} sq units", rect1.area());
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
Vectors & Iterators
Functional iterators, filter and map on vectors
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let sum_of_even_squares: i32 = numbers
.iter()
.filter(|&&x| x % 2 == 0)
.map(|&x| x * x)
.sum();
println!("Original numbers: {:?}", numbers);
println!("Sum of even squares: {}", sum_of_even_squares);
}
Pattern Matching & Enums
Rust enum types and match statements
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn process_msg(msg: Message) {
match msg {
Message::Quit => println!("Action: Quitting"),
Message::Move { x, y } => println!("Action: Move to ({}, {})", x, y),
Message::Write(text) => println!("Action: Write -> {}", text),
}
}
fn main() {
process_msg(Message::Move { x: 10, y: 25 });
process_msg(Message::Write(String::from("Safe concurrency in Rust")));
process_msg(Message::Quit);
}
Hello World
Basic PHP script output
<?php
echo "Hello, World from PHP!\n";
?>
Array Map & Pipeline Filtering
Filter in-stock products and calculate total inventory in PHP
<?php
$inventory = [
["name" => "Mechanical Keyboard", "price" => 120, "in_stock" => true],
["name" => "Ergonomic Mouse", "price" => 45, "in_stock" => true],
["name" => "USB-C Hub", "price" => 35, "in_stock" => false],
["name" => "4K Monitor", "price" => 380, "in_stock" => true]
];
$inStock = array_filter($inventory, fn($item) => $item["in_stock"]);
$totalValue = array_sum(array_column($inStock, "price"));
echo "Available Products in PHP:\n";
foreach ($inStock as $item) {
echo "- {$item['name']}: ${$item['price']}\n";
}
echo "Total In-Stock Value: ${$totalValue}\n";
?>
Associative Arrays & JSON
Array filtering, mapping, and JSON encoding
<?php
$students = [
["name" => "Alice", "score" => 94],
["name" => "Bob", "score" => 68],
["name" => "Charlie", "score" => 87],
];
$passed = array_filter($students, fn($s) => $s["score"] >= 70);
echo json_encode(array_values($passed), JSON_PRETTY_PRINT) . "\n";
?>
String & Palindrome Check
String manipulation and palindrome validation
<?php
function isPalindrome(string $str): bool {
$clean = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str));
return $clean === strrev($clean);
}
$words = ["racecar", "hello", "A man a plan a canal Panama"];
foreach ($words as $w) {
$status = isPalindrome($w) ? "is a palindrome" : "is NOT a palindrome";
echo "\"$w\" $status\n";
}
?>
Hello World
Ruby puts greeting
puts "Hello, World from Ruby!"
Array Transformations & Hashes
Group words by length and format in Ruby
cities = ["Tokyo", "New York", "London", "Paris", "Berlin", "Toronto"]
grouped = cities.group_by(&:length)
puts "Cities Grouped by Name Length in Ruby:"
grouped.sort.each do |length, names|
puts "#{length} letters: #{names.join(', ')}"
end
sorted_by_alpha = cities.sort.map(&:upcase)
puts "\nAlphabetical uppercase:"
puts sorted_by_alpha.join(" • ")
Blocks & Enumerables
Select, map, and reduce with Ruby blocks
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = numbers.select { |n| n.even? }
squares = evens.map { |n| n ** 2 }
total = squares.reduce(0, :+)
puts "Evens: #{evens}"
puts "Squares: #{squares}"
puts "Total sum: #{total}"
Class & Object Orientation
OOP with attr_accessor and instance methods in Ruby
class Developer
attr_accessor :name, :skills
def initialize(name, skills = [])
@name = name
@skills = skills
end
def add_skill(skill)
@skills << skill
end
def bio
"#{@name} crafts software with: #{@skills.join(', ')}"
end
end
dev = Developer.new("Elena", ["Ruby", "Rails", "PostgreSQL"])
dev.add_skill("Docker")
puts dev.bio
Hello World
Basic Kotlin entry point
fun main() {
println("Hello, World from Kotlin!")
}
Extension Functions & Lambdas
Kotlin custom extension methods and higher-order functions
fun String.toTitleCase(): String =
split(" ").joinToString(" ") { word ->
word.lowercase().replaceFirstChar { it.uppercase() }
}
fun main() {
val titles = listOf(
"the art of computer programming",
"clean architecture in kotlin",
"design patterns simplified"
)
println("Kotlin Extension Function Demo:")
titles.forEach { raw ->
println("• Raw: $raw")
println(" Title: ${raw.toTitleCase()}")
}
}
Data Class & Collections
Idiomatic Kotlin data classes and collection filtering
data class Book(val title: String, val author: String, val rating: Double)
fun main() {
val library = listOf(
Book("Clean Code", "Robert Martin", 4.7),
Book("Effective Java", "Joshua Bloch", 4.8),
Book("Kotlin in Action", "Dmitry Jemerov", 4.6),
Book("Average Tech", "Unknown", 3.2)
)
val topBooks = library
.filter { it.rating >= 4.5 }
.sortedByDescending { it.rating }
println("Recommended Tech Books:")
topBooks.forEach { println("★ ${it.rating} - ${it.title} by ${it.author}") }
}
Null Safety & When
Safe calls, elvis operator, and when expression
fun describeValue(obj: Any?): String = when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long integer: $obj"
!is String -> "Not a string"
else -> "Unknown object"
}
fun main() {
val inputs: List<Any?> = listOf(1, "Hello", 1000L, 3.14, "Other")
for (item in inputs) {
println("Item: $item -> ${describeValue(item)}")
}
}
Hello World
Standard Swift print output
print("Hello, World from Swift!")
Enums & Pattern Matching
Swift enumeration with associated values and switch pattern matching
enum HTTPStatus {
case ok
case notFound
case serverError(code: Int)
var description: String {
switch self {
case .ok:
return "200: Success - Request fulfilled"
case .notFound:
return "404: Resource Not Found"
case .serverError(let code):
return "\(code): Internal Server Error"
}
}
}
let responses: [HTTPStatus] = [.ok, .notFound, .serverError(code: 503)]
print("Swift Pattern Matching & Enums:")
for res in responses {
print("• \(res.description)")
}
Structs & Computed Properties
Idiomatic Swift struct with methods and computed values
struct Circle {
var radius: Double
var area: Double {
return Double.pi * radius * radius
}
var circumference: Double {
return 2 * Double.pi * radius
}
}
let c = Circle(radius: 5.0)
print(String(format: "Radius: %.1f | Area: %.2f | Circumference: %.2f", c.radius, c.area, c.circumference))
Closures & Array Transformations
Higher-order Swift functions: filter, map, and reduce
let words = ["apple", "banana", "avocado", "cherry", "apricot"]
let aWords = words.filter { $0.hasPrefix("a") }.map { $0.uppercased() }
print("A-Words capitalized: \(aWords)")
let totalLetters = words.reduce(0) { $0 + $1.count }
print("Total letters in word list: \(totalLetters)")
Table & Query
Create table, insert records, and filter with WHERE clause
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT,
department TEXT,
salary INTEGER
);
INSERT INTO employees VALUES (1, 'Alice', 'Engineering', 95000);
INSERT INTO employees VALUES (2, 'Bob', 'Marketing', 68000);
INSERT INTO employees VALUES (3, 'Charlie', 'Engineering', 105000);
SELECT name, salary FROM employees WHERE department = 'Engineering';
INNER JOIN & Relations
Relational join between students and course enrollments
CREATE TABLE courses (id INT, title TEXT);
CREATE TABLE enrollments (student_name TEXT, course_id INT);
INSERT INTO courses VALUES (101, 'Computer Science I'), (102, 'Data Structures');
INSERT INTO enrollments VALUES ('Grace', 101), ('Grace', 102), ('Alan', 101);
SELECT e.student_name, c.title AS course_title
FROM enrollments e
INNER JOIN courses c ON e.course_id = c.id
ORDER BY e.student_name;
Aggregations & GROUP BY
GROUP BY, COUNT, AVG, and HAVING clauses
CREATE TABLE sales (id INT, rep TEXT, amount REAL);
INSERT INTO sales VALUES
(1, 'Sarah', 450.0), (2, 'Sarah', 750.0),
(3, 'James', 300.0), (4, 'James', 150.0),
(5, 'Elena', 1200.0);
SELECT rep, COUNT(*) AS deals, SUM(amount) AS total_sales, AVG(amount) AS avg_deal
FROM sales
GROUP BY rep
ORDER BY total_sales DESC;
Hello World
Basic echo statement and shebang
#!/bin/bash
echo "Hello, World from Bash!"
System Info & Environment Summary
Inspect OS, kernel, date, and user details in Bash
#!/bin/bash
echo "=== System & Runtime Information ==="
echo "Operating System : $(uname -s)"
echo "Kernel Release : $(uname -r)"
echo "Current Shell : $SHELL"
echo "Current User : $(whoami)"
echo "Current Date : $(date '+%Y-%m-%d %H:%M:%S')"
echo "Working Directory: $(pwd)"
echo "=== Execution Complete ==="
Word Counter Pipeline
Unix pipeline with tr, sort, and uniq -c
#!/bin/bash
DATA="apple orange banana apple kiwi banana apple orange banana apple"
echo "--- Word Frequency ---"
echo "$DATA" | tr ' ' '\n' | sort | uniq -c | sort -nr
Functions & Loops
Bash functions, arguments, and loop iteration
#!/bin/bash
log_task() {
local step=$1
echo "[$(date +%T)] Step $step complete."
}
for i in {1..3}; do
log_task "$i"
done
echo "All tasks finished successfully!"