Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Initialize array in one line / in a single statement

Initialize array in one line / in a single statement

Scheduled Pinned Locked Moved C#
data-structureshelptutorialquestion
22 Posts 8 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • N NetQuestions

    Hi, I want to initialize a string array with "*". I want to know if I can avoid using a for loop to do the same. In the below example I have used a for loop. Can the same done in one line??? The following code will help me generate fibonacci series

    public static int Fibonacci(int n)
    {
    int previous = -1;
    int result = 1;
    for (int i = 0; i <= n; ++i)
    {
    int sum = result + previous;
    previous = result;
    result = sum;
    }

     //
     // declare an array of size 'result'
     // use a for loop and initialize each entry of array with a "\*"
     //
    

    }

    E Offline
    E Offline
    Ennis Ray Lynch Jr
    wrote on last edited by
    #3

    new String('*', 10).ToCharArray();

    Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

    L N 2 Replies Last reply
    0
    • E Ennis Ray Lynch Jr

      new String('*', 10).ToCharArray();

      Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

      L Offline
      L Offline
      Luc Pattyn
      wrote on last edited by
      #4

      Close but no cigar. That results in a char[], not a string[].

      string[] sa=new string('*', n).Replace("*", ".*").Split(".".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);

      is one way of getting it done.

      string[] sa=new string('*', n).Replace("*", ".*").Substring(1).Split('.');

      is an alternative. :)

      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

      Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

      E 1 Reply Last reply
      0
      • N NetQuestions

        Hi, I want to initialize a string array with "*". I want to know if I can avoid using a for loop to do the same. In the below example I have used a for loop. Can the same done in one line??? The following code will help me generate fibonacci series

        public static int Fibonacci(int n)
        {
        int previous = -1;
        int result = 1;
        for (int i = 0; i <= n; ++i)
        {
        int sum = result + previous;
        previous = result;
        result = sum;
        }

         //
         // declare an array of size 'result'
         // use a for loop and initialize each entry of array with a "\*"
         //
        

        }

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #5

        there isn't a straightforward formula that yields Fibonacci numbers without iterations; the closest you can get AFAICT is by using Binet's formula (see here[^]) but for large numbers that will be an approximation as it relies on floating-point arithmetic. :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

        Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

        1 Reply Last reply
        0
        • L Luc Pattyn

          Close but no cigar. That results in a char[], not a string[].

          string[] sa=new string('*', n).Replace("*", ".*").Split(".".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);

          is one way of getting it done.

          string[] sa=new string('*', n).Replace("*", ".*").Substring(1).Split('.');

          is an alternative. :)

          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

          Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

          E Offline
          E Offline
          Ennis Ray Lynch Jr
          wrote on last edited by
          #6

          Happy :p

          string[] arr = new string[0];
          for(int i = 0; i < 10; i++) {
          string[] temp = new string[arr.Length+1];
          Array.Copy(arr, temp, arr.Length);
          temp[arr.Length] = "*";
          arr = temp;
          }

          Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

          1 Reply Last reply
          0
          • E Ennis Ray Lynch Jr

            new String('*', 10).ToCharArray();

            Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

            N Offline
            N Offline
            NetQuestions
            wrote on last edited by
            #7

            That was awesome Stephen. Thanks I never knew that an array can be instantiated with a new kewword. I have incorporated your suggestion in my application. I am now using "char[] str7 = new String('*', result).ToCharArray()" This should handle one part of my application. I have one more question. Is it possible to convert this array of characters to a string? something like reverse of what you showed me. regards, Netquestions

            P S 2 Replies Last reply
            0
            • N NetQuestions

              Hi, I want to initialize a string array with "*". I want to know if I can avoid using a for loop to do the same. In the below example I have used a for loop. Can the same done in one line??? The following code will help me generate fibonacci series

              public static int Fibonacci(int n)
              {
              int previous = -1;
              int result = 1;
              for (int i = 0; i <= n; ++i)
              {
              int sum = result + previous;
              previous = result;
              result = sum;
              }

               //
               // declare an array of size 'result'
               // use a for loop and initialize each entry of array with a "\*"
               //
              

              }

              L Offline
              L Offline
              Luc Pattyn
              wrote on last edited by
              #8

              string[] sa=new string('*', (int)Math.Round((Math.Pow(0.5+Math.Sqrt(1.25), n)-Math.Pow(0.5-Math.Sqrt(1.25), n))/Math.Sqrt(5))).Replace("*", ".*").Substring(1).Split('.');

              works quite well. :)

              Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

              Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

              1 Reply Last reply
              0
              • N NetQuestions

                That was awesome Stephen. Thanks I never knew that an array can be instantiated with a new kewword. I have incorporated your suggestion in my application. I am now using "char[] str7 = new String('*', result).ToCharArray()" This should handle one part of my application. I have one more question. Is it possible to convert this array of characters to a string? something like reverse of what you showed me. regards, Netquestions

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #9

                His name's not Stephen. I can understand the confusion, but the Stephen referred to in his signature relates to the author of the quote.

                "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                My blog | My articles | MoXAML PowerToys | Onyx

                L 1 Reply Last reply
                0
                • P Pete OHanlon

                  His name's not Stephen. I can understand the confusion, but the Stephen referred to in his signature relates to the author of the quote.

                  "WPF has many lovers. It's a veritable porn star!" - Josh Smith

                  As Braveheart once said, "You can take our freedom but you'll never take our Hobnobs!" - Martin Hughes.

                  My blog | My articles | MoXAML PowerToys | Onyx

                  L Offline
                  L Offline
                  Luc Pattyn
                  wrote on last edited by
                  #10

                  I prefer Denny Crane anyway. :)

                  Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                  Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

                  1 Reply Last reply
                  0
                  • N NetQuestions

                    Hi, I want to initialize a string array with "*". I want to know if I can avoid using a for loop to do the same. In the below example I have used a for loop. Can the same done in one line??? The following code will help me generate fibonacci series

                    public static int Fibonacci(int n)
                    {
                    int previous = -1;
                    int result = 1;
                    for (int i = 0; i <= n; ++i)
                    {
                    int sum = result + previous;
                    previous = result;
                    result = sum;
                    }

                     //
                     // declare an array of size 'result'
                     // use a for loop and initialize each entry of array with a "\*"
                     //
                    

                    }

                    A Offline
                    A Offline
                    Andrew Rissing
                    wrote on last edited by
                    #11

                    You know, your teacher is likely just wanting a recursive method[^].

                    L N 2 Replies Last reply
                    0
                    • A Andrew Rissing

                      You know, your teacher is likely just wanting a recursive method[^].

                      L Offline
                      L Offline
                      Luc Pattyn
                      wrote on last edited by
                      #12

                      I suggest you try Fibonacci(100) in a recursive way; you can walk around the world while it computes. Unless you go for a more advanced equation, one that calculates Fib(2x) from Fib(x). :)

                      Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                      Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

                      A E 2 Replies Last reply
                      0
                      • L Luc Pattyn

                        I suggest you try Fibonacci(100) in a recursive way; you can walk around the world while it computes. Unless you go for a more advanced equation, one that calculates Fib(2x) from Fib(x). :)

                        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                        Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

                        A Offline
                        A Offline
                        Andrew Rissing
                        wrote on last edited by
                        #13

                        Oh, I'm not suggesting that it is a better solution what so ever. I'm just stating it sounds like a homework assignment for creating a recursive Fibonacci implementation. ;P

                        N 1 Reply Last reply
                        0
                        • L Luc Pattyn

                          I suggest you try Fibonacci(100) in a recursive way; you can walk around the world while it computes. Unless you go for a more advanced equation, one that calculates Fib(2x) from Fib(x). :)

                          Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                          Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

                          E Offline
                          E Offline
                          Ennis Ray Lynch Jr
                          wrote on last edited by
                          #14

                          I am not an algorithms expert so mine may be wrong and I did cheat for base case but my recursive Fib algorithm is instant. I won't post because it may be the OP's homework but Fib is not hard and does not require any deep recursion. My algorithm needs 98 levels to calculate the Fib numbers from 2 to 100. (Again, I cheated on the base)

                          Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

                          L 1 Reply Last reply
                          0
                          • E Ennis Ray Lynch Jr

                            I am not an algorithms expert so mine may be wrong and I did cheat for base case but my recursive Fib algorithm is instant. I won't post because it may be the OP's homework but Fib is not hard and does not require any deep recursion. My algorithm needs 98 levels to calculate the Fib numbers from 2 to 100. (Again, I cheated on the base)

                            Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

                            L Offline
                            L Offline
                            Luc Pattyn
                            wrote on last edited by
                            #15

                            yes, you can easily avoid the exponential behavior, however I have seen quite a few straightforward recursive implementations that don't. They are extremely good examples against the use of recursion for anything that is not recursive by its very nature (such as a hierarchical file system). :)

                            Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

                            Please use < PRE > tags for code snippets, it preserves indentation, and improves readability.

                            1 Reply Last reply
                            0
                            • N NetQuestions

                              Hi, I want to initialize a string array with "*". I want to know if I can avoid using a for loop to do the same. In the below example I have used a for loop. Can the same done in one line??? The following code will help me generate fibonacci series

                              public static int Fibonacci(int n)
                              {
                              int previous = -1;
                              int result = 1;
                              for (int i = 0; i <= n; ++i)
                              {
                              int sum = result + previous;
                              previous = result;
                              result = sum;
                              }

                               //
                               // declare an array of size 'result'
                               // use a for loop and initialize each entry of array with a "\*"
                               //
                              

                              }

                              P Offline
                              P Offline
                              PIEBALDconsult
                              wrote on last edited by
                              #16

                              NetQuestions wrote:

                              I want to initialize a string array with "*".

                              string[] a = new string[] { "*" } ;

                              N 1 Reply Last reply
                              0
                              • N NetQuestions

                                That was awesome Stephen. Thanks I never knew that an array can be instantiated with a new kewword. I have incorporated your suggestion in my application. I am now using "char[] str7 = new String('*', result).ToCharArray()" This should handle one part of my application. I have one more question. Is it possible to convert this array of characters to a string? something like reverse of what you showed me. regards, Netquestions

                                S Offline
                                S Offline
                                sidbaruah
                                wrote on last edited by
                                #17

                                Something like this - string aaa = new string(str7, 0, str7.Length); would return you a string of "***", if thats What u're looking for. :)

                                I was born dumb!! :laugh:Programming made me laugh:laugh:!!! --sid--

                                1 Reply Last reply
                                0
                                • A Andrew Rissing

                                  You know, your teacher is likely just wanting a recursive method[^].

                                  N Offline
                                  N Offline
                                  NetQuestions
                                  wrote on last edited by
                                  #18

                                  the number of times the method keeps getting called increases exponentially

                                  1 Reply Last reply
                                  0
                                  • P PIEBALDconsult

                                    NetQuestions wrote:

                                    I want to initialize a string array with "*".

                                    string[] a = new string[] { "*" } ;

                                    N Offline
                                    N Offline
                                    NetQuestions
                                    wrote on last edited by
                                    #19

                                    I actually used the following statement

                                    string str = new string('*', 10)

                                    P 1 Reply Last reply
                                    0
                                    • A Andrew Rissing

                                      Oh, I'm not suggesting that it is a better solution what so ever. I'm just stating it sounds like a homework assignment for creating a recursive Fibonacci implementation. ;P

                                      N Offline
                                      N Offline
                                      NetQuestions
                                      wrote on last edited by
                                      #20

                                      Hi, recursion is not always the way.

                                      *
                                      *
                                      *
                                      **
                                      ***
                                      *****
                                      ********

                                      If I were to generate and display the following, you will observe that when n= 50, program hangs. the number of times recursive method gets called grows exponentially. In such a case a non recursive method is required. Regards, NetQuestions

                                      A 1 Reply Last reply
                                      0
                                      • N NetQuestions

                                        I actually used the following statement

                                        string str = new string('*', 10)

                                        P Offline
                                        P Offline
                                        PIEBALDconsult
                                        wrote on last edited by
                                        #21

                                        That doesn't meet the stated criteria.

                                        1 Reply Last reply
                                        0
                                        • N NetQuestions

                                          Hi, recursion is not always the way.

                                          *
                                          *
                                          *
                                          **
                                          ***
                                          *****
                                          ********

                                          If I were to generate and display the following, you will observe that when n= 50, program hangs. the number of times recursive method gets called grows exponentially. In such a case a non recursive method is required. Regards, NetQuestions

                                          A Offline
                                          A Offline
                                          Andrew Rissing
                                          wrote on last edited by
                                          #22

                                          Indeed, I'm well aware of such. I was only basing my suggestion on the fact it seemed like a homework assignment to create a recursive method. :)

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups