Program for n-th odd number

Given a number n, print the nth odd number. The 1st odd number is 1, 2nd is 3 and so on.

Examples:

Input : 3
Output : 5
First three odd numbers are 1, 3, 5, ..

Input : 5
Output : 9
First 5 odd numbers are 1, 3, 5, 7, 9, ..

The nth odd number is given by the formula 2*n-1.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to find the nth odd number
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the nth odd number
int nthOdd(int n)
{
    return (2 * n - 1);
}
  
// Driver code
int main()
{
    int n = 10;
    cout << nthOdd(n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// JAVA program to find the nth odd number
  
class GFG
{
    // Function to find the nth odd number
    static int nthOdd(int n)
    {
        return (2 * n - 1);
    }
      
    // Driver code
    public static void main(String [] args)
    {
        int n = 10;
        System.out.println(nthOdd(n));
          
    }
}
  
// This code is contributed
// by ihritik

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to find the 
# nth odd number
  
# Function to find the nth odd number
def nthOdd(n):
  
    return (2 * n - 1)
      
      
# Driver code
if __name__=='__main__':
    n = 10
    print(nthOdd(n))
  
# This code is contributed
# by ihritik

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the nth odd number
using System;
  
class GFG
{
      
// Function to find the nth odd number
static int nthOdd(int n)
{
    return (2 * n - 1);
}
  
// Driver code
public static void Main()
{
    int n = 10;
    Console.WriteLine(nthOdd(n));
}
}
  
// This code is contributed
// by inder_verma

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to find the 
// Nth odd number
  
// Function to find the 
// Nth odd number
function nthOdd($n)
{
    return (2 * $n - 1);
}
  
// Driver code
$n = 10;
echo nthOdd($n);
  
// This code is contributed
// by inder_verma
?>

chevron_right



Output:

19


My Personal Notes arrow_drop_up

Coder Machine Learner Social Activist Vocalist

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : ihritik, inderDuMCA