Visual Studio c# Array Loop - c#

I'm not sure if this has been asked before but I couldn't see it anywhere.
Can you loop an array? For example:
string[] = array1;
int num1 = 1;
do
{
lbl1.Text = array1[0]
}while(num1 = 1);
How can I make it so it adds one to the element every loop.

I agree that you need to better explain what you're trying to accomplish. If you hardcode num1 then perform a while num1 is equal to its initial value without ever modifying it, you're going to have an indefinite loop. In your example, it will just keep overwriting lbl1 to display the first item in your array.
By "add one to the element every loop", do you mean add each item in the array to your label? Try something like...
foreach (string item in array1)
{
lbl1.Text += array1[item];
}
Otherwise, please provide further details on what you're looking for.

It is really not clear what You want to achieve, but maybe this will get You nearer to the goal:
int[] array1 = new [] {0};
int num1 = 1;
do {
lbl1.Text = (array1[0]++).ToString();
num1++;
} while (num1 < 9);
or
int[] array1 = new [] {0};
for (int i = 0; i < 9; i++) {
lbl1.Text = (array1[0]++).ToString();
}

Not sure what you are trying to accomplish but the following is a stab at a solution
private static void foo(string[] array1)
{
if (array1 != null && array1.Length > 0)
{
for (int num1 = 0; num1 < array1.Length; num1++)
{
string doSomethingWithArrayElement = array1[num1];
}
}
}

Related

C# Array Length Update

I am solving the problem from this link: https://www.hackerrank.com/challenges/cut-the-sticks (I added the link for more details if my explanation wasn't enough or wasn't quite clear.)
The point here from the exercise that I in the first I give a (int) number of sticks that I will use in the operation. the second line I enter the sticks length. So I must find the smallest stick(k), then subtract it from the rest of the sticks, then make the program print the number of total sticks that I have cut. So if the stick was cut before or its original value is 0 I have to remove it and don't count it. Then this should repeat over to redefine the value of the k because the min array value will be changed because all the sticks are cutted.
Here is my code that I used:
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = new int[n];
arr = Array.ConvertAll(userinput, Int32.Parse);
for (int i = 0; i < n - 1; i++)
{
arr = arr.Where(s => s != '0').ToArray();
int k = arr.Min();
arr[i] -= k;
Console.WriteLine(arr.Length);
}
Console.ReadKey();
The problem is it keeps printing the n value, which is the array's original size, it doesn't modify after the removing of the 0. So how can I fix it to just print the number of cutted sticks and when the all sticks is 0 so break?
I'm sorry for my English and if my explanation is a bit hard, but I am just new to C#.
This is the working code as you expected and tested.
Note: I just reused all the variable names and naming conventions as you did which can be refactored further.
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = new int[n];
arr = Array.ConvertAll(userinput, Int32.Parse);
CutTheStick(arr);
Console.ReadKey();
}
private static void CutTheStick(int[] arr)
{
arr = arr.Where(s => s != 0).ToArray();
if (arr.Length > 0)
{
Console.WriteLine(arr.Length);
int k = arr.Min();
for (int i = 0; i < arr.Length; i++)
{
arr[i] -= k;
}
CutTheStick(arr);
}
}
}
If you had web/winForm based application, remove the static keyword accordingly.
There is an evident error in your code. The char '0' is not the integer 0. The automatic conversion between char and int allows this code to compile and run but you are not testing correctly your inputs
For example
int[] arr = new int[] {0,1,2,3,4};
if(arr[0] == '0')
Console.WriteLine("Is Zero");
will never print "Is Zero", while
int[] arr = new int[] {48,1,2,3,4};
if(arr[0] == '0')
Console.WriteLine("Is Zero");
will print "Is Zero" because the integer value of the char '0' is 48.
Now to give a solution to your problem I could post this code
int cutCount = 1;
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(userinput, Int32.Parse);
// Loop until we finish to empty the array
while (true)
{
// remove any zero present in the array
arr = arr.Where(s => s != 0).ToArray();
// If we don't have any more elements we have finished
if(arr.Length == 0)
break;
// find the lowest value
int k = arr.Min();
// Start a loop to subtract the lowest value to all elements
for (int i = 0; i < arr.Length; i++)
arr[i] -= k;
// Just some print to let us follow the evolution of the array elements
Console.WriteLine($"After cut {cutCount} the array length is {arr.Length}");
Console.Write("Array is composed of: ");
foreach(int x in arr)
Console.Write(x + " ");
Console.WriteLine();
}
Console.ReadLine();
But please study it carefully because otherwise my solution is no help for you in future programming tasks

Detecting an empty array without looping

How can i find out an array is empty or not, without looping?!
is there any method or anything else?
I mean, in some code like this:
string[] names = new string[5];
names[0] = "Scott";
names[1] = "jack";
names[2] = null;
names[3] = "Jones";
names[4] = "Mesut";
// or
int[] nums = new int[4];
nums[0] = 1;
// nums[1] = 2;
nums[2] = 3;
nums[3] = 4;
or some code like this:
using System;
class Example
{
static void Main()
{
int size = 10;
int counter;
string[] str = new string[size];
for (counter = 0; counter < size; counter++)
{
str[counter] = "A" + counter;
}
str[3] = null;
if (counter == size)
Console.WriteLine("Our array is full!");
if(counter < size)
Console.WriteLine("Our array is not full");
for (int i = 0; i < size; i++)
{
Console.WriteLine(str[i]);
}
}
}
is there anything else for detecting an empty array without looping?
An array just contains a number of elements. There's no concept of an array being "empty" just because each element happens to contain the default value (0, null, or whatever).
If you want a dynamically sized collection, you should use something like List<T> instead of an array.
If you want to detect whether any element of a collection (whether that's a list, an array or anything else) is a non-default value, you have to do that via looping. (You don't have to loop in your source code, but there'll be looping involved somewhere...)
There is no other way than looping through, even LINQ also does the looping automatically.
Instead, use a list<> and check if (listName!=null && listName.Length!=0)
Hope it helps :)
You can use LINQ for that, to check if any element is empty in the array you just can do:
var hasNulls = myArray.Any( a => a == null );
Or if you want to select the ones with values:
var notNulls = myArray.Where( a => a != null );

Shifting A single element in an array

I want to shift one element in an array to the right each time whilst leaving the original elements in their specific order in C#.
Ok so I've been asked to reword the code I can understand why so here we go:
I might have a number 48390
//the ar elements have been commented out to show that we never know what ar contains but only the that I will always want to shift; ar[4]
int[] ar = new int[5];
//ar[0] = 4
//ar[1] = 8
//ar[2] = 3
//ar[3] = 9
//ar[4] = 0
while(ar != 04839)
{
Shift code
}
I might input 5 numbers 48390 if you notice its the same number but one digit is out. I want a while loop to rotate that 4 ar[1] to shift until the number forms 04839
I hope this makes sense. I am posting this question because most pages posting information about shifting based on shifting all elements to the right and I only really want to shift one specific element.
Thanks for looking.
edit: I should have been more specific. What if you don't know what each of the array elements could be? So I couldn't depend on "0" as an anchor. as another set of numbers might include another number for example "00238."
This method will give you a sequence of arrays made by inserting a single element into (between) each position in a given array:
public static IEnumerable<T[]> InsertElementBetweenAllPositions<T>(
T[] array, T element)
{
int newLength = array.Length + 1;
for (int i = 0; i < newLength; i++)
{
T[] rtn = new T[newLength];
rtn[i] = element;
Array.Copy(array, 0, rtn, 0, i);
Array.Copy(array, i, rtn, i + 1, array.Length - i);
yield return rtn;
}
}
For your example, you might call it as
foreach (int[] arr in InsertElementBetweenAllPositions(new[] { 6, 7, 8, 9 }, 0))
{
foreach (int i in arr)
Console.Write(i + " ");
Console.WriteLine();
}
How about this:
List<int> l = new List<int>(){0,6,7,8,9};
for (int i=1;i<5;i++)
{
l.Remove(0);
l.Insert(i, 0);
}
What's in your example is a swap, which can be implemented like:
private void Swap(ref int[] array, int index1, int index2)
{
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
Calling Swap(ref source, 0, 1) would exchange the first and second element. What you want then is:
for (int i = 0; i < a.Length-1; i++)
{
Swap(ref a, i, i+1);
}
This "bubbles" the first element up to the last position in each iteration.
From the example you need to shift elements around, and the example is a bit confusing over whether you need to loop them around to the start again. I have provided the below example that will loop around to the start - If you do not need to do that, the you can rework the if the statement.
private int[] Shift(int[] a)
{
int zeroPos = Array.IndexOf(a, 0);
int[] rtn = new int[a.Length];
a.CopyTo(rtn, 0);
if (zeroPos + 1 == a.Length)
{
rtn[0] = 0;
for (int i = 0; i < a.Length - 1; i++)
{
rtn[i + 1] = a[i];
}
}
else
{
rtn[zeroPos] = rtn[zeroPos + 1];
rtn[zeroPos + 1] = 0;
}
return rtn;
}
r=ar[0];
for (int i = 0; ar.lenght;i++)
{
ar[i]=ar[i + 1];
}
ar[ar.lenght] = r;
Have you thought about using a LinkedList instead? A linked list data structure is probably more suited to what you are trying to do than an array. The AddFirst, AddLast, AddAfter and AddBefore methods allow you to insert elements into the list in a much more efficient way than re-organizing your array each time.
The disadvantage of linked lists is that you need to read the elements in order. So, it's very efficient for inserting/deleting elements but inefficient for accessing elements randomly.
There is a good overview of LinkedLists here.
Perhaps
int oldLast = ar[ar.Length - 1];
for (int i = ar.Length - 1; i >= 0; i--)
ar[i] = i == 0 ? oldLast : ar[i - 1];
Demo
It is just a permutation of an item , below is the full source code of permutation algorithm.
static List<string> Put(char s1, string list)
{
List<string> str =new List<string>();
for (int i = 0; i < list.Length+1; i++)
{
string s = list.Substring(0, i) + s1.ToString() + list.Substring(i);
str.Add(s);
}
return str;
}
static List<string> Permute(string list,int x)
{
List<string> Result = new List<string>();
if (list.Length == 1)
{
Result.Add(list[0].ToString());
return Result;
}
else
{
char first = list[0];
list = list.Substring(x+1);
List<string> part = Permute(list,0);
foreach (string str in part)
{
List<string> hasBeenPlaced = Put(first, str);
foreach (string str2 in hasBeenPlaced)
{
Result.Add(str2);
}
}
}
return Result;
}
static void Main(string[] args)
{
List<string> per = Permute("abc",0);
for (int i = 0; i < per.Count; i++)
{
Console.WriteLine(per[i]);
}
Console.ReadKey();
}
Now if I add a break after the foreach , your problem has been solved . (it will writes all permuation for just an item which you want , not all of them....)
So change that to :
foreach (string str in part)
{
List<string> hasBeenPlaced = Put(first, str);
foreach (string str2 in hasBeenPlaced)
{
Result.Add(str2);
}
break;
}
Hope to helps you
If you you linq, that's simple :-) But you need a size larger than the array.
ShiftLeft(ar, 1);
private static int[] ShiftLeft(int[] value, int countOfShift = 1)
{
var length = value.Length;
if (countOfShift > length)
{
throw new InvalidOperationException("countOfShift must less then value's length.");
}
var tempList = new List<int>(value);
tempList.RemoveRange(length - countOfShift, countOfShift);
tempList.InsertRange(0, value.Skip(length - countOfShift));
return tempList.ToArray();
}

Adding elements to a C# array

I would like to programmatically add or remove some elements to a string array in C#, but still keeping the items I had before, a bit like the VB function ReDim Preserve.
The obvious suggestion would be to use a List<string> instead, which you will have already read from the other answers. This is definitely the best way in a real development scenario.
Of course, I want to make things more interesting (my day that is), so I will answer your question directly.
Here are a couple of functions that will Add and Remove elements from a string[]...
string[] Add(string[] array, string newValue){
int newLength = array.Length + 1;
string[] result = new string[newLength];
for(int i = 0; i < array.Length; i++)
result[i] = array[i];
result[newLength -1] = newValue;
return result;
}
string[] RemoveAt(string[] array, int index){
int newLength = array.Length - 1;
if(newLength < 1)
{
return array;//probably want to do some better logic for removing the last element
}
//this would also be a good time to check for "index out of bounds" and throw an exception or handle some other way
string[] result = new string[newLength];
int newCounter = 0;
for(int i = 0; i < array.Length; i++)
{
if(i == index)//it is assumed at this point i will match index once only
{
continue;
}
result[newCounter] = array[i];
newCounter++;
}
return result;
}
If you really won't (or can't) use a generic collection instead of your array, Array.Resize is c#'s version of redim preserve:
var oldA = new [] {1,2,3,4};
Array.Resize(ref oldA,10);
foreach(var i in oldA) Console.WriteLine(i); //1 2 3 4 0 0 0 0 0 0
Don't use an array - use a generic List<T> which allows you to add items dynamically.
If this is not an option, you can use Array.Copy or Array.CopyTo to copy the array into a larger array.
Since arrays implement IEnumerable<T> you can use Concat:
string[] strArr = { "foo", "bar" };
strArr = strArr.Concat(new string[] { "something", "new" });
Or what would be more appropriate would be to use a collection type that supports inline manipulation.
Use List<string> instead of string[].
List allows you to add and remove items with good performance.
What's abaut this one:
List<int> tmpList = intArry.ToList();
tmpList.Add(anyInt);
intArry = tmpList.ToArray();
One liner:
string[] items = new string[] { "a", "b" };
// this adds "c" to the string array:
items = new List<string>(items) { "c" }.ToArray();
You should take a look at the List object. Lists tend to be better at changing dynamically like you want. Arrays not so much...
You can use a generic collection, like List<>
List<string> list = new List<string>();
// add
list.Add("element");
// remove
list.Remove("element");
You can use this snippet:
static void Main(string[] args)
{
Console.WriteLine("Enter number:");
int fnum = 0;
bool chek = Int32.TryParse(Console.ReadLine(),out fnum);
Console.WriteLine("Enter number:");
int snum = 0;
chek = Int32.TryParse(Console.ReadLine(),out snum);
Console.WriteLine("Enter number:");
int thnum = 0;
chek = Int32.TryParse(Console.ReadLine(),out thnum);
int[] arr = AddToArr(fnum,snum,thnum);
IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
{
return s;
});
Console.WriteLine("Here your result:");
oarr.ToList().FindAll(delegate(int num) {
Console.WriteLine(num);
return num > 0;
});
}
public static int[] AddToArr(params int[] arr) {
return arr;
}
I hope this will help to you, just change the type

c# foreach looping even number

I have the following foreach loop in C#:
foreach(var item in mod)
{
int i;
i = i + 1;
if (i % 2 == 0)
{
string y = "even number";
}
}
How come I get the message that local variable is unassigned. I am trying to find the even number here.
To resolve the message you are getting, you simply need to initialize it:
int i = 0;
If your intention is to count every item, then you will also need to change the scope of i to outside of the foreach. Otherwise, as you originally posted, the variable i will have the same value for every iteration of the loop.
See this code snippet for both the initialization and scope change:
int i = 0;
foreach (var item in mod)
{
i = i + 1; // is the first item considered even or odd? that answer changes where this should go
if (i % 2 == 0) {
string y = "even number";
}
}
You need to initialise your i variable:
int i = 0;
You're currently trying + 1 to an unassigned variable.
You get the warning because you are not assigning i before using it in i = i + 1. You want to declare i outside of your foreach loop, so you it isn't bound to the scope of the loop. Then initialize with 0 and use the increment feature. Something like:
int i = 0;
foreach (var item in mod)
{
i++;
if (i % 2 == 0)
{
string y = "even number";
}
}
An alternative to what others have suggested here (although correct) would be to use a for loop, this would take care of i for you, e.g.
for (int i = 0; i < mod.length; i++)
{
if (i % 2 == 0)
{
string y = "even number";
}
}
Change this: int i;
to this: int i = 0;
Values types in C# like int do have default values, but you're still not allowed to use an unassigned value-type variable.
You need to assign an initial value for i before you can do i=i+1
You have to initialize i. Right now the compiler is reading this as i = garbage in memory. So you have garbage in memory = garbage in memory + 1. That i could be equal to a string, a number, or anything.
int i = 0;
In addition, you need to initialize that variable outside of the for...each loop, or it will keep resetting itself to 0.
int i = 0;
foreach(var item in mod){
i = i + 1;
if (i % 2 == 0) {
string y = "even number";
}
}
int i = 0;
foreach(var item in mod)
{
if (i % 2 == 0)
{
string y = "even number";
}
i = i + 1;
}
//what are you doing with y and how are you returning y if you need it..
are you expecting to break out at some point.. ? what if item has zero items..??

Categories