Home > OS >  Return an array composed of the string representation of the numbers from 1 to n, In C#
Return an array composed of the string representation of the numbers from 1 to n, In C#

Time:09-25

This is the rest of the Question. Return an array composed of the string representation of the numbers from 1 to n.But there is a twist!! For Multiples of 3 , return the string "Darude" instand of the number, For Multiple of 5 return the string "Sandstorm"; and for multiple of both 3 and 5 ,return the string "Darude StandStorm"

This is my code

static string [] stringarray(int n)
 {
 string [] results= { } ;
 for (int i = 1; i <= n; i  ) 
{
  if (i % 3 == 0) results = new[] { "Deude" };`enter code here`
  if (i % 5 == 0) results = new[] { "Sandstome" }; 
  if (i % 3 == 0 & i % 5 == 0) results = new[] { "Darude Sandstome" }; 
    else Console.WriteLine(i);
 } 
 return results; 
}

CodePudding user response:

Check this out. You are creating instance of array in loop so it clear the value.

public static string[] stringarray(int n)
        {
            string[] results = new string[n];
            for (int i = 1; i <= n; i  )
            {
                if (i % 3 == 0 && i % 5 == 0)
                {
                    results[i - 1] = "Darude Sandstome";
                }
                else if (i % 3 == 0)
                {
                    results[i - 1] = "Deude";
                }
                else if (i % 5 == 0)
                {
                    results[i - 1] = "Sandstome";
                }
                else
                {
                    results[i - 1] = i.ToString();
                }
            }
            return results;
        }

Read the value as Below

string[] strResult = stringarray(16);
foreach (var item in strResult)
{
   Console.WriteLine(item);
}
Console.Read();

CodePudding user response:

I would suggest a slightly better option :

    public static string[] stringarray(int n)
    {
        bool isMultipleOf3 =  i % 3 == 0;
        bool isMultipleOf5 = i % 5 == 0;
        string[] results = new string[n];
        
        for ( int i = 1; i <= n; i   )
        {
            if ( isMultipleOf3 && isMultipleOf5 ) 
            {
                 results[i - 1] = "Darude Sandstome";
                 continue;
            }
            
            if (isMultipleOf3 )
            {
                 results[i - 1] = "Deude";
                 continue;
             }
             if ( isMultipleOf5 ) 
             {
                 results[i - 1] = "Sandstome";
                 continue;
             }
             
             results[i - 1] = i.ToString(); //Console.WriteLine(i);
         }
         return results;
     }

It is better because you only compute i%3 and i%5 once. And, it is clearer what you are testing since the bool variables avec clear names.

  • Related