How to initialize int array in C#

5 Answers

0 votes
using System;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        // Generate a range of 10 numbers starting at 0
        var arr = Enumerable.Range(0, 10).ToArray();
 
        foreach (int n in arr) {
            Console.WriteLine(n);
        }
    }
}


 
/*
run:
 
0
1
2
3
4
5
6
7
8
9
 
*/

 



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

public class Program
{
    public static void Main(string[] args)
    {
        int[] arr = new int[10];
 
        for (int i = 0; i < arr.Length; i++) {
            arr[i] = i;
        }
 
        foreach (int n in arr) {
            Console.WriteLine(n);
        }
    }
}


 
/*
run:
 
0
1
2
3
4
5
6
7
8
9
 
*/

 



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

public class Program
{
    public static void Main(string[] args)
    {
        int[] arr = new int[5];
 
        for (int i = 0; i < arr.Length; i++) {
            arr[i] = -1;
        }

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


 
/*
run:
 
-1
-1
-1
-1
-1
 
*/

 



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

public class Program
{
    public static void Main(string[] args)
    {
        int[] arr = Enumerable.Repeat(-1, 5).ToArray();

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


 
/*
run:
 
-1
-1
-1
-1
-1
 
*/

 



answered Mar 3, 2017 by avibootz
edited Apr 17, 2024 by avibootz
0 votes
using System;
 
class Program
{
    static void Main() {
        int[] arr = { 6, 8, 2, 1, 0 };
         
        foreach (int n in arr) {
            Console.WriteLine(n);
        }
    }
}
 
 
 
/*
run:
 
6
8
2
1
0
 
*/

 



answered Apr 17, 2024 by avibootz

Related questions

1 answer 104 views
2 answers 169 views
1 answer 142 views
1 answer 183 views
...