How to declare and initialize char array in C#

5 Answers

0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] arr = Enumerable.Repeat('a', 5).ToArray();

            foreach (char ch in arr)
                Console.WriteLine(ch);
        }
    }
}


/*
run:

a
a
a
a
a

*/

 



answered Mar 3, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] arr = new char[5];

            for (int i = 0; i < arr.Length; i++)
                arr[i] = 'a';

            foreach (char ch in arr)
                Console.WriteLine(ch);
        }
    }
}


/*
run:

a
a
a
a
a

*/

 



answered Mar 3, 2017 by avibootz
edited Mar 3, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] arr = new char[5];

            for (int i = 0, j = 97; i < arr.Length; i++, j++)
                arr[i] = Convert.ToChar(j);

            foreach (char ch in arr)
                Console.WriteLine(ch);
        }
    }
}


/*
run:

a
b
c
d
e

*/

 



answered Mar 3, 2017 by avibootz
edited Mar 3, 2017 by avibootz
0 votes
using System;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = Enumerable.Range(3, 7).ToArray();

            foreach (int n in arr)
                Console.WriteLine(n);
        }
    }
}


/*
run:

3
4
5
6
7
8
9

*/

 



answered Mar 4, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            char[] arr = {'a', '+', 'c', 'x'};

            foreach (char ch in arr)
                Console.WriteLine(ch);
        }
    }
}


/*
run:
        
a
+
c
x
   
*/

 



answered Jul 26, 2018 by avibootz

Related questions

3 answers 217 views
217 views asked Jan 10, 2017 by avibootz
1 answer 179 views
1 answer 182 views
182 views asked Aug 23, 2016 by avibootz
1 answer 128 views
128 views asked Jul 29, 2021 by avibootz
1 answer 148 views
2 answers 212 views
...