The Program in C# Program to Reverse Words of a Sentence is given below:
using System;
namespace ReverseWords
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a sentence to reverse the words: ");
string inputString = Console.ReadLine();
string[] words = inputString.Split(' ');
Array.Reverse(words);
string reversedSentence = string.Join(" ", words);
Console.WriteLine("The reversed sentence is: " + reversedSentence);
}
}
}
Output:
Hello Codeauri Family, enter a sentence here to reverse the words:keep programming
Okay, the reversed sentence is: programming keep
Pro-Tips💡
Here are the step by step execution of above program:
- The using System; statement is a directive that imports the System namespace, which contains the Console and Array classes used in the code.
- The namespace ReverseWords is declared, which is a way of organizing code and preventing naming collisions.
- The class Program is declared, which is the main class of the code and contains the entry point of the program, the Main method.
- The Main method is defined, which is the starting point of the program and contains the logic for reversing the words in a sentence.
- The Console.WriteLine(“Enter a sentence to reverse the words: “) statement outputs a prompt to the console asking the user to enter a sentence.
- The string inputString = Console.ReadLine() statement reads the input from the user and stores it in the inputString variable.
- The string[] words = inputString.Split(‘ ‘) statement splits the input string into an array of strings, with each string representing a word, using the Split method and the space character as a separator.
- The Array.Reverse(words) statement reverses the order of the elements in the words array.
- The string reversedSentence = string.Join(” “, words) statement concatenates the reversed words into a string, separated by spaces, using the Join method.
- The Console.WriteLine(“The reversed sentence is: ” + reversedSentence) statement outputs the reversed sentence to the console.
- The Main method ends and the program terminates.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.