This is my code, but clear method is not working, but I can't find the error.
This is the first time that clear method it's not working, anyone can help me?
using System;
using System.Collections.Generic;
public class test{
public static void Main()
{
try {
int[] myArr = {-1, 4, 8, 6};
PrintIndexAndValues(myArr);
Console.WriteLine();
Console.WriteLine("Taking index out of bound:");
Array.clear(myArr, 1, 2);
Console.WriteLine("Array After Operation:");
PrintIndexAndValues(myArr);
}
}
public static void PrintIndexAndValues(int[] myArr)
{
for (int i = 0; i < myArr.Length; i++) {
Console.WriteLine("{0}", myArr[i]);
}
}
}
From Arrays (C# Programming Guide):
The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.
If you want to be able to use Clear() the way you inted to, you should use a List instead:
List<int> myList = new List<int>{-1, 4, 8, 6};
// Do some stuff with your list
myList.Clear();
Edit:
Your PrintIndexAndValues actually only prints the values, here's how you could do it instead:
public static void PrintIndexAndValues(List<int> myList)
for (int i = 0; i < myList.Count; i++)
{
Console.WriteLine("{0}: {1}", i, myList[i]);
}
Edit2: Just realized that you probably wanted to remove the first and last element of the array, not clear the whole array?
This should do the trick:
myList.RemoveAt(3)
myList.RemoveAt(0)
The following is your corrected code
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
int[] myArr = {-1, 4, 8, 6};
PrintIndexAndValues(myArr);
Console.WriteLine();
Console.WriteLine("Taking index out of bound:");
Array.Clear(myArr, 0, myArr.Length);
Console.WriteLine("Array After Operation:");
PrintIndexAndValues(myArr);
}
public static void PrintIndexAndValues(int[] myArr)
{
for (int i = 0; i < myArr.Length; i++)
Console.WriteLine("{0}", myArr[i]);
}
}
This will set ALL values in your array to 0.
Related
so I am trying to take all the numbers from a list that are less than 5 and I try to put them in another list and print that list. I have no idea how to do that in c#. I will be very grateful if you'd help me. Thank you and here is my code:
using System;
namespace exercices
{
class Hello
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5, 6, };
int[] b = { };
for (int i = 0; i < a.Length; i++)
{
if (a[i] < 5)
{
b.Append(a[i]);
}
}
}
}
Method 1. Just check every element
You should use List<T> collection in this method. It's possible to convert it to array later, if you need.
List<int> b = new();
foreach (int element in a)
{
if (element < 5)
{
b.Add(element);
}
}
Method 2. Use Array.FindAll<T> method
int[] b = Array.FindAll(a, element => element < 5);
Method 3. Use LINQ
int[] b = a.Where(element => element < 5).ToArray();
You could do something like this:
using System;
namespace exercices
{
class Hello
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5, 6, };
int[] b = { };
for (int i = 0; i < a.Length;i++)
{
Int number=a[i];
if (number < 5)
b.Insert(i, number);
}
}
}
}
You can avoid explicit for loops using LINQ: the Where() method returns an IEnumerable object; you can then create an array or a list from the IEnumerable with the corresponding ToArray()/ToList() method, as shown below:
int[] a = { 1, 2, 3, 4, 5, 6};
IEnumerable<int> lessThanFiveElements = a.Where(element => element < 5);
int[] lessThanFiveArray = lessThanFiveElements.ToArray();
List<int> lessThanFiveList = lessThanFiveElements.ToList();
In case you have a console application, you can then print the resulting array/list with a Console.WriteLine() command, as shown below
Console.WriteLine(string.Join(",", lessThanFiveElements));
where I used the string.Join() in order to have comma separated elements, which accepts the separator as a first parameter and any IEnumerable as the second one.
I want to convert int array to int so i can add them.
Example
int[] x = {1, 2, 3};
sum=x[0] + x[1] + x[2];
I have a loop for getting an input from user but i have to add all the values of every inputted.
Use the .Sum LINQ method:
var x = new int[] { 1, 2, 3 };
var sum = x.Sum(); // gives 6
Further info
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
https://www.csharp-examples.net/linq-sum/
You can do this in a number of ways.
first by making a loop yourself.
static int Sum(int[] array)
{
int sum = 0;
foreach (var item in array)
{
sum += item;
}
return sum;
}
static void Main()
{
int[] x = new int[] { 1, 2, 3 };
Console.Write(Sum(x).ToString());
}
second, using the Sum() method in the System.Linq library
using System.Linq;
////
int[] x = new int[] { 1, 2, 3 };
Console.Write(x.Sum());
thank you USEFUL for feedback if it worked for you
It is not really clear what the problem is. Your code seems fully functional, so it is difficult to know what you are really trying to achieve and what the underlying issue it.
But certainly a simple loop would work fine.
int sum = 0;
for(int loop=0; loop < x.Length; loop++)
{
sum += x[loop];
}
You can also do this via Linq (I see somebody else posted that example, so I won't repeat it).
Consider I have an Array,
int[] i = {1,2,3,4,5};
Here I have assigned values for it. But in my problem I get these values only at runtime.
How can I assign them to an array.
For example:
I get the max size of array from user and the values to them now how do I assign them to the array int [].
Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?
Well, the easiest is to use List<T>:
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();
Otherwise, you need to allocate an array of suitable size, and set via the indexer.
int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.
You mean?
int[] array = { 1, 2, 3, 4, 5 };
array = new int[] { 1, 3, 5, 7, 9 };
array = new int[] { 100, 53, 25, 787, 39 };
array = new int[] { 100, 53, 25, 787, 39, 500 };
Use List<int> and then call ToArray() on it at the end to create an array. But do you really need an array? It's generally easier to work with the other collection types. As Eric Lippert wrote, "arrays considered somewhat harmful".
You can do it explicitly though, like this:
using System;
public class Test
{
static void Main()
{
int size = ReadInt32FromConsole("Please enter array size");
int[] array = new int[size];
for (int i=0; i < size; i++)
{
array[i] = ReadInt32FromConsole("Please enter element " + i);
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
static int ReadInt32FromConsole(string message)
{
Console.Write(message);
Console.Write(": ");
string line = Console.ReadLine();
// Include error checking in real code!
return int.Parse(line);
}
}
If you want an array, whose size varies during the execution, then you should use another data structure. A generic List will do. Then, you can dynamically add elements to it.
Edit: Marc posted his answer while I was writing mine. This was exactly what I meant.
You could just use the below line instead of calling a separate function:
using System;
public class Test
{
static void Main()
{
Console.WriteLine("Please enter array size");
int size = Convert.ToInt32(Console.ReadLine());
int[] array = new int[size];
for (int i=0; i < size; i++)
{
Console.WriteLine("Please enter element " + i);
array[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Finished:");
foreach (int i in array)
{
Console.WriteLine(i);
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need help with this code. I cant make it work so.. something is unclear for me yet.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
static int[] foo(int[] array)
{
int[] xx = new int[array.Length];
for(int i = 0; i < array.Length; i++)
{
array[i] *= 2;
Console.WriteLine(array[i]);
}
return array;
}
static void Main(string[] args)
{
int[] array = new int[4] {73, 67, 38, 33 };
foo(array);
}
}
How to rebuild foo function to return values from array ?
I saw a lot of help links with void function.. and they werent useful. When it comes to specific type of function I cant make it work.
Thanks
ddr8
class Solution
{
static int[] foo(int[] array)
{
int[] xx = new int[array.Length]; // Building this but not using it
for (int i = 0; i < array.Length; i++)
{
array[i] *= 2; //Altering the input array changes the array in the Main method..
Console.WriteLine(array[i]);
}
return array;
}
static void Main(string[] args)
{
int[] array = new int[4] { 73, 67, 38, 33 };
foo(array); // Not assigning the values to an object.
//After this step look at array it will be 146, 134, 76 , 66
}
}
So you are altering the original array in the foo method. you're passing the array object then overwriting the values.
You declare a new int[] xx but then do nothing to it, I think instead you should be copying the source array to the new xx int[].
Doing this doesn't alter the orignal int in the main method.
You can then assign the return value of the new array in the main method.
Example below:
class Solution
{
static int[] foo(int[] array)
{
int[] xx = new int[array.Length];
//Copy the array into the new array
Array.Copy(array, xx, array.Length);
for (int i = 0; i < xx.Length; i++)
{
xx[i] *= 2;
Console.WriteLine(xx[i]);
}
return xx;
}
static void Main(string[] args)
{
int[] array = new int[4] { 73, 67, 38, 33 };
//Assign the new array to an object
int[] newArray = foo(array);
}
}
Edit:
I also saw you included linq at the top, if you were interested in using linq this would achieve the same result:
static void Main(string[] args)
{
int[] array = new int[4] { 73, 67, 38, 33 };
int[] newarr = array.Select(arrayvalue => arrayvalue * 2).ToArray();
}
Your current code does return an array, but you are:
Updating the value in array and not the new xx array
Not assigning the return value in Main
Here is where you are modifying the existing array and not the new array:
static int[] foo(int[] array)
{
int[] xx = new int[array.Length];
for(int i = 0; i < array.Length; i++)
{
// NOTE: modifying array, not xx
array[i] *= 2;
Console.WriteLine(array[i]);
}
// NOTE: returning array, not xx -- xx is not used
return array;
}
Here is the missing assignment for the returned array:
static void Main(string[] args)
{
int[] array = new int[4] {73, 67, 38, 33 };
// You are not assigning the returned array here
int[] newArray = foo(array);
}
Your other option is to pass the array as a ref parameter, if you need to change the array size:
static int[] foo(ref int[] array)
{
// Modify array as necessary
}
I am trying to make a method to reverse an array, I don't know why it is not working?
When I said int[] arr = array, I want to do this so it will not be affected so I can use the elements for the second for loop and it should have elements {1,2,3,4,5,6} but when I use
for (int i=array.Length-1;i>array.Length/2;i--)
{
array[i] = arr[array.Length - 1 - i];
}
In this case I have 6 elements so array.Length is 6 and since I started from array.Length-1 it must start from the last element and it must be array[5]=arr[6-1-5] which must be array[5]=arr[0] and arr[0] is 1 but I think it is getting it as 6, why?
Here is the complete code:
// ReverseArray method
static int [] ReverseArray(int [] array)
{
int[] arr = array;
for (int i=0; i<array.Length/2;i++)
{
array[i] = array[array.Length-1 - i];
}
for (int i=array.Length-1;i>array.Length/2;i--)
{
array[i] = arr[array.Length - 1 - i];
}
return array;
}
// Method for displaying elements of Array
static void DisplayArray(int [] array)
{
int i;
Console.Write("{");
for (i = 0; i < array.Length-1; i++)
{
Console.Write(array[i] + ",");
}
Console.WriteLine(array[i] + "}");
}
static void Main(string[] args)
{
int[] array = { 1, 2, 3, 4, 5 ,6};
ReverseArray(array);
DisplayArray(array);
Console.ReadKey();
}
Your reversal approach is invalid: rather than swapping elements at indexes i and array.Length-1 - i, your code copies the tail portion of the array onto the initial one, effectively "folding" the array onto itself.
You need to remove the second loop, and replace the assignment with a swap: make a temporary variable, store array[i], copy array[array.Length-1 - i], then write the temporary in its place.
I couldn't help myself but start to write a piece of code trying to solve it.
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
arr = Reverse(arr).ToArray();
Here is the shorter way to achieve that.
public IEnumerable<int> Reverse(int[] arr)
{
for (int i = arr.Length-1; i >= 0; i--)
{
yield return arr[i];
}
}