Skip to content

Instantly share code, notes, and snippets.

@Suvink
Last active May 16, 2022 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Suvink/5694cb1bf810341e39fba9cf7a01472e to your computer and use it in GitHub Desktop.
Save Suvink/5694cb1bf810341e39fba9cf7a01472e to your computer and use it in GitHub Desktop.
C# Array Operations
//Reverse
public static void Main(string[] args)
{
Console.WriteLine ("Hello Mono World");
int[] arr = {1,3,4,9,8};
//Initialize an identical array
int[] reversed = new int[5];
//Use this to keep the indexes
int j = 0;
//Iterate the initial array from end to the start
for (int i = arr.Length; i > 0; i = i - 1)
{
//Push into the reversed array
reversed[j] = arr[i-1];
//Increment the index
j = j+1;
}
Console.WriteLine(string.Join(",", reversed));
}
//Rotate by 1
public static void Main(string[] args)
{
Console.WriteLine ("Hello Mono World");
int[] arr = {1,3,4,9,8};
//So if you are to rotate this by 1 element clockwise, then push one last element of the array and push it into the front
//In the previous example, take 8 out and push it before 1
// int[] arr = {8,1,3,4,9};
int rotatedElement = arr[arr.Length -1];
for (int i = arr.Length -1; i > 0; i = i - 1)
{
arr[i] = arr[i-1];
}
arr[0]= rotatedElement;
Console.WriteLine(string.Join(",", arr));
}
//Find Max
public static void Main(string[] args)
{
Console.WriteLine ("Hello Mono World");
int[] arr = {1,3,4,9,8};
int max = 0;
for (int i = 0; i < arr.Length -1; i = i + 1)
{
if(arr[i] > max){
max = arr[i];
}
}
Console.WriteLine(max);
}
//Find Min
public static void Main(string[] args)
{
Console.WriteLine ("Hello Mono World");
int[] arr = {1,3,4,9,8};
int min = arr[0];
for (int i = 0; i < arr.Length -1; i = i + 1)
{
if(arr[i] < min){
min = arr[i];
}
}
Console.WriteLine(min);
}
//Reverse an array using a stack
public static void Main(string[] args)
{
Console.WriteLine ("Hello Mono World");
int[] arr = {1,3,4,9,8};
Stack myStack = new Stack();
for (int i = 0; i < arr.Length; i = i + 1)
{
myStack.Push(arr[i]);
}
while(myStack.Count > 0)
{
Console.WriteLine(myStack.Pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment