TechTorch

Location:HOME > Technology > content

Technology

Program to Print the First 20 Even Numbers in Various Programming Languages

February 02, 2025Technology4908
Program to Print the First 20 Even Numbers in Various Programming Lang

Program to Print the First 20 Even Numbers in Various Programming Languages

Printing the first 20 even numbers is a common programming challenge that can be achieved through various programming languages. This task is a great exercise for beginners to understand loops and basic arithmetic operations. Below, we will look at how to accomplish this in Python, Java, C, and Haskell. Additionally, we will explore a simple C implementation and a random even number generator in C. Each example is designed to be clear and well-commented for easy understanding.

Python Example

In Python, you can use a loop to print the first 20 even numbers. Here is the complete code:

# Print the first 20 even numbers
for i in range(20):
    print(i * 2)

Java Example

Java also offers a straightforward way to print the first 20 even numbers. Here is the Java code:

public class EvenNumbers {
    public static void main(String[] args) {
        // Print the first 20 even numbers
        for (int i  0; i  20; i  ) {
            (i * 2  ");
        }
    }
}

C Example

The C programming language also provides a simple way to achieve this. Here is the C code:

#include iostream
using namespace std;
int main() {
    // Print the first 20 even numbers
    for (int i  0; i  20; i  ) {
        cout  (i * 2)  endl;
    }
    return 0;
}

Haskell Example

Haskell offers a different approach with functional programming. Here is the Haskell code:

pm print . take 20 $ filter even [1..]

Clojure Example

Clojure also has a concise way to achieve this using the `take` and `iterate` functions:

(reduce (fn [x] (conj x (* 2 x))) [] (iterate inc 1) :limit 20)

Random Even Number Generator in C

For a more interesting twist, you can generate 20 random even numbers in C. Here is the code:

#include stdio.h
#include stdlib.h
#include time.h
int main() {
    int x  0;
    srand(time(0));
    for (x  0; x  20; x  ) {
        printf(%d , 2 * rand() % 50);
    }
    return 0;
}

Each of these examples demonstrates how to generate and print even numbers in different programming languages. Python, Java, C, and other languages offer different syntaxes and features, making them useful for understanding the underlying programming concepts.

Conclusion

Whether you are a beginner in programming or a seasoned developer, creating a program to print the first 20 even numbers is a useful exercise. It helps in understanding loops, arithmetic operations, and basic programming constructs. Feel free to try these examples and experiment with them in your preferred environment to deepen your understanding.