w3resource

C#: Take a positive number and return the nth odd number


Nth Odd Number

Write a C# Sharp program that takes a positive number and returns the nth odd number.

Sample Solution:

C# Sharp Code:

using System;
using System.Linq;

namespace exercises
{
    class Program
    {
        // Main method where the program execution begins
        static void Main(string[] args)
        {
            // Display the odd numbers at different positions
            Console.WriteLine("1st odd number: " + test(1));
            Console.WriteLine("2nd odd number: " + test(2));
            Console.WriteLine("4th odd number: " + test(4));
            Console.WriteLine("100th odd number: " + test(100));
        }

        // Function to calculate the nth odd number
        public static int test(int n)
        {
            return n * 2 - 1; // The nth odd number can be calculated using this formula
        }
    }
}

Sample Output:

1st odd number: 1
2nd odd number: 3
4th odd number: 7
100th odd number: 199

Flowchart:

Flowchart: C# Sharp Exercises - Take a positive number and return the nth odd number.

For more Practice: Solve these Related Problems:

  • Write a C# program to return the nth even number starting from 0.
  • Write a C# program to find the sum of the first n odd numbers.
  • Write a C# program to return the nth odd number divisible by 3.
  • Write a C# program to generate the nth odd Fibonacci number.

Go to:


PREV : Odd or Even Length of String.
NEXT : Get ASCII Value of Character.

C# Sharp Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.