Given a number n, print the first n positive even numbers in increasing order in a single line using a for loop.
Examples:
Input: n = 2
Output: 2 4
Explanation: The first 2 positive even numbers are 2 and 4.Input: n = 6
Output: 2 4 6 8 10 12
Explanation: The first 6 positive even numbers are 2, 4, 6, 8, 10 and 12.
- The idea is to use a for loop to iterate from 1 to n.
- In each iteration, multiply the loop variable by 2 to obtain the next positive even number and print it.
- The for loop continues until n even numbers have been printed.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 10;
// cin >> n;
// Print the first n positive even numbers in increasing order.
for (int i = 1; i <= n; i++) {
cout << 2 * i;
// Print a space only if more numbers remain.
if (i < n) {
cout << " ";
}
}
return 0;
}
#include <stdio.h>
int main() {
int n = 10;
// scanf("%d", &n);
// Print the first n positive even numbers in increasing order.
for (int i = 1; i <= n; i++) {
printf("%d", 2 * i);
// Print a space only if more numbers remain.
if (i < n) {
printf(" ");
}
}
return 0;
}
import java.util.Scanner;
class GFG {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// int n = sc.nextInt();
int n = 10;
// Print the first n positive even numbers in increasing order.
for (int i = 1; i <= n; i++) {
System.out.print(2 * i);
// Print a space only if more numbers remain.
if (i < n) {
System.out.print(" ");
}
}
sc.close();
}
}
if __name__ == "__main__":
# n = int(input())
n = 10
# Print the first n positive even numbers in increasing order.
for i in range(1, n + 1):
print(2 * i, end="")
# Print a space only if more numbers remain.
if i < n:
print(" ", end="")
using System;
class GFG {
static void Main(string[] args) {
// int n = Convert.ToInt32(Console.ReadLine());
int n = 10;
// Print the first n positive even numbers in increasing order.
for (int i = 1; i <= n; i++) {
Console.Write(2 * i);
// Print a space only if more numbers remain.
if (i < n) {
Console.Write(" ");
}
}
}
}
// const fs = require('fs');
// const input = fs.readFileSync(0, 'utf8').trim();
// const n = parseInt(input);
let n = 10;
// Print the first n positive even numbers in increasing order.
for (let i = 1; i <= n; i++) {
process.stdout.write((2 * i).toString());
// Print a space only if more numbers remain.
if (i < n) {
process.stdout.write(" ");
}
}
Output
2 4 6 8 10 12 14 16 18 20