text
stringlengths
0
1.19k
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <memory>
// C++ adds OOP, RAII, and STL containers on top of C
class Person {
public:
Person(std::string name, int age) : name_(std::move(name)), age_(age) {}
void greet() const {
std::cout << "Hello, " << name_ << "! You are " << age_ << " years old.\n";
}
private:
std::string name_;
int age_;
};
int main() {
// vector + smart pointers manage memory automatically (RAII)
std::vector<std::unique_ptr<Person>> people;
people.push_back(std::make_unique<Person>("Alice", 30));
people.push_back(std::make_unique<Person>("Bob", 25));
for (const auto &p : people) {
p->greet();
}
return 0; // memory freed automatically when vector goes out of scope
}
```
## C#
```csharp
using System;
using System.Collections.Generic;
// C# is garbage-collected and runs on a managed runtime (.NET)
class Person {
public string Name { get; }
public int Age { get; }
public Person(string name, int age) {
Name = name;
Age = age;
}
public void Greet() {
Console.WriteLine($"Hello, {Name}! You are {Age} years old.");
}
}
class Program {
static void Main() {
// List<T> is a built-in generic collection
var people = new List<Person> {
new Person("Alice", 30),
new Person("Bob", 25)
};
foreach (var p in people) {
p.Greet();
}
// No manual cleanup needed — garbage collector handles it
}
}
```
### What each example highlights
| Aspect | C | C++ | C# |
|---|---|---|---|
| Paradigm | Procedural | Multi-paradigm (OOP + procedural) | OOP, managed |
| Memory | Manual (`malloc`/`free`) | RAII / smart pointers | Garbage collected |
| Data | `struct` | `class` + STL (`vector`) | `class` + `List<T>` |
| Strings | Fixed-size char arrays | `std::string` | Native `string` type |
| Runtime | Compiles to native machine code | Compiles to native machine code | Compiles to IL, run by .NET runtime |
Want me to expand any of these — e.g., show error handling, inheritance, or a more complex shared example (like a small data structure or algorithm) implemented identically across all three?
Please provide the code for each language: Assembly, Java, Fortran. about the different things you choose-Happy to give you a concrete example. I'll pick a classic — **calculating the factorial of a number** — since it shows nicely how the same logic looks across very different language styles.
## Assembly (x86-64, NASM syntax)
```asm
section .text
global _start
factorial:
; input: rdi = n
; output: rax = n!
mov rax, 1 ; result = 1
.loop:
cmp rdi, 1
jle .done
imul rax, rdi ; result *= n