Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to generate the first 100 even Numbers using C#?
To generate the first 100 even numbers in C#, you can use a for loop and check if each number is divisible by 2. An even number has no remainder when divided by 2, which can be tested using the modulo operator (%).
What are Even Numbers?
Even numbers are integers that are divisible by 2 without a remainder. Examples include 2, 4, 6, 8, 10, and so on. The condition number % 2 == 0 identifies even numbers.
Using a For Loop with Modulo Check
The most straightforward approach is to iterate through numbers 1 to 100 and check each number for evenness −
using System;
class Program {
static void Main() {
int val;
Console.WriteLine("First 100 even numbers:");
for(val = 1; val <= 100; val++) {
if(val % 2 == 0) {
Console.WriteLine(val);
}
}
}
}
The output of the above code is −
First 100 even numbers: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Using Direct Even Number Generation
A more efficient approach is to generate even numbers directly by starting with 2 and incrementing by 2 each time −
using System;
class Program {
static void Main() {
Console.WriteLine("First 100 even numbers (optimized):");
for(int i = 2; i <= 200; i += 2) {
Console.WriteLine(i);
}
}
}
The output of the above code is −
First 100 even numbers (optimized): 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 104 106 108 110 112 114 116 118 120 122 124 126 128 130 132 134 136 138 140 142 144 146 148 150 152 154 156 158 160 162 164 166 168 170 172 174 176 178 180 182 184 186 188 190 192 194 196 198 200
Using Counter-Based Approach
Another method uses a counter to generate exactly 100 even numbers regardless of their actual values −
using System;
class Program {
static void Main() {
int count = 0;
int number = 2;
Console.WriteLine("First 100 even numbers (counter-based):");
while(count < 100) {
Console.WriteLine(number);
number += 2;
count++;
}
}
}
The output shows the first 100 even numbers starting from 2.
Comparison of Methods
| Method | Efficiency | Description |
|---|---|---|
| Modulo Check | Lower | Checks every number from 1 to 100 |
| Direct Generation | Higher | Generates only even numbers by incrementing by 2 |
| Counter-Based | Highest | Generates exactly 100 even numbers with precise control |
Conclusion
Generating the first 100 even numbers in C# can be accomplished using multiple approaches. The modulo check method is straightforward but less efficient, while direct generation and counter-based approaches provide better performance by avoiding unnecessary checks.
