Program to print first n odd numbers using while loop

Program to print first n odd numbers using while loop

  • Write a program to print first n odd numbers using while loop in C
  • Write a program to print first n odd numbers using while loop in C++
  • Write a program to print first n odd numbers using while loop in Python
  • Write a program to print first n odd numbers using while loop in PHP
  • Write a program to print first n odd numbers using while loop in Java
  • Write a program to print first n odd numbers using while loop in Java Script
  • Write a program to print first n odd numbers using while loop in C#

Explanation:

Logic

  1. Take input for n (number of odd numbers to print).
  2. Use a while loop to iterate from 1 to n.
  3. For each iteration, compute the odd number using the formula 2*i – 1.
  4. Print the computed number.

Program to print first n odd numbers using While loop

#include <stdio.h>

int main() {
    int n, i = 1, count = 0;
    printf("Enter the value of n: ");
    scanf("%d", &n);

    while (count < n) {
        if (i % 2 != 0) {
            printf("%d ", i);
            count++;
        }
        i++;
    }
    printf("\n");
    return 0;
}

#include <iostream>
using namespace std;

int main() {
    int n, i = 1, count = 0;
    cout << "Enter the value of n: ";
    cin >> n;

    while (count < n) {
        if (i % 2 != 0) {
            cout << i << " ";
            count++;
        }
        i++;
    }
    cout << endl;
    return 0;
}

n = int(input("Enter the value of n: "))
i = 1
count = 0

while count < n:
    if i % 2 != 0:
        print(i, end=" ")
        count += 1
    i += 1
print()

<?php
$n = (int)readline("Enter the value of n: ");
$i = 1;
$count = 0;

while ($count < $n) {
    if ($i % 2 != 0) {
        echo $i . " ";
        $count++;
    }
    $i++;
}
echo "\n";
?>

import java.util.Scanner;

public class FirstNOddNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the value of n: ");
        int n = sc.nextInt();
        int i = 1, count = 0;

        while (count < n) {
            if (i % 2 != 0) {
                System.out.print(i + " ");
                count++;
            }
            i++;
        }
        System.out.println();
        sc.close();
    }
}

let n = parseInt(prompt("Enter the value of n: "));
let i = 1, count = 0;

while (count < n) {
    if (i % 2 !== 0) {
        console.log(i);
        count++;
    }
    i++;
}

using System;

class Program {
    static void Main() {
        Console.Write("Enter the value of n: ");
        int n = int.Parse(Console.ReadLine());
        int i = 1, count = 0;

        while (count < n) {
            if (i % 2 != 0) {
                Console.Write(i + " ");
                count++;
            }
            i++;
        }
        Console.WriteLine();
    }
}

List of All Programs