Exercise
Function Return Value For Main
Objective
Write a C# program in which you write a title (using the previous WriteTitle function) which the user will specify in command line. If no text is specified, your program will display an error message and return a value of 1 to the operatiing system.
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces
using System;
class Program
{
// Main method to drive the program
public static void Main(string[] args)
{
// Check if any argument is passed (i.e., a title)
if (args.Length == 0)
{
// If no argument is provided, show an error message and return 1
Console.WriteLine("Error: No title specified.");
Environment.Exit(1); // Return 1 to the operating system
}
else
{
// If an argument is provided, call the WriteTitle function with the user's title
string title = string.Join(" ", args); // Join the arguments if there are multiple words
WriteTitle(title); // Display the title
}
}
// Function to write the title with lines above and below
public static void WriteTitle(string text)
{
// Defining the screen width (80 columns)
int screenWidth = 80;
// Convert the text to uppercase and add extra spaces between each character
string upperText = string.Join(" ", text.ToUpper().ToCharArray());
// Calculate the number of hyphens needed for the lines
int totalLength = upperText.Length + 4; // 2 extra spaces for padding on each side
int hyphenCount = (screenWidth - totalLength) / 2;
// Create the line of hyphens
string hyphens = new string('-', hyphenCount);
// Display the line above the text
Console.WriteLine(hyphens);
// Display the text centered
Console.WriteLine($"{hyphens} {upperText} {hyphens}");
// Display the line below the text
Console.WriteLine(hyphens);
}
}