Programming languages are diverse, each with its syntax, style, and conventions. In this blog post, we’re diving deep into the implementation of a simple factorial program in Python, C, Java & JavaScript. Buckle up and join us on this mind-bending journey as we uncover the striking similarities and glaring differences in expressing the same logic across these languages.
PYTHON / C / JAVA or JAVASCRIPT
Python:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
if __name__ == "__main__":
number = int(input("Enter a number to calculate its factorial: "))
result = factorial(number)
print(f"The factorial of {number} is: {result}")
C
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int number;
printf("Enter a number to calculate its factorial: ");
scanf("%d", &number);
int result = factorial(number);
printf("The factorial of %d is: %d\n", number, result);
return 0;
}
Java
import java.util.Scanner;
public class Factorial {
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to calculate its factorial: ");
int number = scanner.nextInt();
int result = factorial(number);
System.out.println("The factorial of " + number + " is: " + result);
}
}
JavaScript
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
let number = prompt("Enter a number to calculate its factorial:");
let result = factorial(Number(number));
console.log(`The factorial of ${number} is: ${result}`);
In summary, Python, C, Java, and JavaScript each possess unique strengths. Python excels in readability and simplicity, with a vibrant community. C prioritizes efficiency and low-level control for systems programming. Java’s object-oriented design ensures portability and code organization. Lastly, JavaScript’s asynchronous nature is vital in web development. The choice of language depends on project requirements and developer preferences, offering diverse opportunities for innovation and problem-solving in programming.
Leave a comment