Exercise
Function Returning A Value V2
Objective
Write a C# program whose Main must be like this:
public static void Main()
{
__Console.WriteLine("\"Hello, how are you\" contains {0} spaces", ____CountSpaces("Hello, how are you") );
}
CountSpaces is a function that you must define and that will be called from inside Main.
As you can see in the example, it must accept an string as a parameter, and it must return an integer number (the amount of spaces in that string).
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Function to count the number of spaces in a given string
public static int CountSpaces(string text)
{
// Initialize a counter for spaces
int count = 0;
// Loop through each character in the string
foreach (char c in text)
{
// If the character is a space, increment the counter
if (c == ' ')
{
count++;
}
}
// Return the total number of spaces found in the string
return count;
}
// Main method to call the CountSpaces function and display the result
public static void Main()
{
// Call the CountSpaces function with a sample string, and display the result
// The string "Hello, how are you" contains 4 spaces, so it will display: "Hello, how are you contains 4 spaces"
Console.WriteLine("\"Hello, how are you\" contains {0} spaces", CountSpaces("Hello, how are you"));
}
}