Using foreach to get the even numbers out of array c# - c#

I have this homework assignment where I have array called myArr with values 4, 9, 2, 5, 1, 4, 8, 3, 3 and I have to extract even numbers out of there and place them in myOtherArray and then printing them with foreach. I tried doing the code but I kinda got stuck since I know it won't work.
Here is my attempt:
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int num = 0;
int[] myOtherArr = new int[num];
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
num++;
}
}
Num is the counter to count how many even numbers are there, but right now I don't know how to save them into myOtherArray because I get the error that Index was outside the bounds of the array.
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
myArr[i] = myOtherArr[i];
}
}
Right now I don't know how to do this. Please help I want to be ready for my exam comming soon.
Thank you all in forward for your answers.

you can also try using Array.FindAll() built-in method to achieve this , instead of looping construct. Please try below code.
var myArr = new int[] { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
var myOtherArr = Array.FindAll(myArr, v => v%2 == 0);
Thank you.

I would try something like this
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
var i=0;
foreach (var item in myArr)
if (item % 2 == 0) i++;
var myOtherArr= new int[i];
i=0;
foreach (var item in myArr)
if (item % 2 == 0) { myOtherArr[i] = item; i++; }

I did it this way because you don't have to figure out the length of the array.
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int[] myOtherArr;
List<int> cache = new List<int>();
//goes through each number in this array and stores the ones for that round in "num".
//If the number is "% 2 == 0" then it will be added to a list.
foreach (int num in myArr)
{
if (num % 2 == 0)
{
cache.Add(num);
}
}
//the list is converted and stored in your array
myOtherArr = cache.ToArray();
//all numbers are displayed
foreach (int num in myOtherArr)
{
Console.WriteLine(num);
}
but you can also write it like this (I like to do this, for example).
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int[] myOtherArr;
List<int> cache = new List<int>();
//goes through each number in this array and stores the ones for that round in "num".
//If the number is "% 2 == 0" then it will be added to a list.
foreach (int num in myArr)
if (num % 2 == 0)
cache.Add(num);
//the list is converted and stored in your array
myOtherArr = cache.ToArray();
//all numbers are displayed
foreach (int num in myOtherArr)
Console.WriteLine(num);

The problem is here:
int[] myOtherArr = new int[num]; // you initialize the array to 0 length.
Try this:
int[] myArr = { 4, 9, 2, 5, 1, 4, 8, 3, 3 };
int num = 0;
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
num++;
}
}
int[] myOtherArr = new int[num];
int j = 0;
for (int i = 0; i < myArr.Length; i++)
{
if (myArr[i] % 2 == 0)
{
myOtherArr[j] = myArr[I];
j++;
}
}

Related

How to return an array fibonaci numbers in C #?

I want to make a function that takes an array of integers as input and print an array of int as Fibonaci series like: third element= second element + first element.
Here is my code so far:
static void Result(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < 0)
Console.WriteLine("arr[i]", arr[i], " number to get must be greater or equal than 0");
var n = arr[i] + 1;
var a = new int[n];
arr[0] = 0;
if (arr[i] == 0)
{
a[1] = 1;
}
for ( i = 2; i < n; i++)
{
a[i] = a[i - 2] + a[i - 1];
}
}
}
public static void Main()
{
int[] arr = {7, 8, 3, 9, 11,16,14,91, };
Result(arr);
}
if input is : 1 ,3 ,4 ,6, 7 ,8 10, 11, 15 ,25 output should be: 1, 3, 4, 7, 11 so 1+3=4, 4+3=7 and so on.
I took a look at your code and you were very close.
The biggest issue was you were starting at i = 0 which would cause errors if you attempted to access arr[-1] and arr[-2].
We can solve that by starting with i = 2.
For example:
static int[] Result(int[] arr)
{
int[] result = arr;
for (int i = 2; i < arr.Length; i++)
{
result[i] = result[i-1] + result[i-2];
}
return result;
}
int[] arr = { 1 ,3 ,4 ,6, 7 ,8, 10, 11, 15 ,25 };
arr = Result(arr);
Console.WriteLine(string.Join(", ",arr));
// outputs: 1, 3, 4, 7, 11, 18, 29, 47, 76, 123
Another side note is that unless you're passing the int[] arr as a reference you will need to return a new int[] as the result since Result()'s changes to arr are not reflected on the array.

Why does array copying in this way not assign digits to the target array?

Why is this copying method not working? The target array should have digits greater than zero, tab2[0] = 3, tab2[1] = 4, etc.
int[] tab1 = { -2, 3, 4, - 5, 1, -7, -3, 4, 8, -10 };
int[] tab2 = new int[tab1.Length];
int a=0;
for (int i = 0; i < tab1.Length; i++)
{
if (tab1[i]>0)
{
tab2[a] = tab1[i];
a++;
}
richTextBox1.AppendText(tab2[i] + " ");
}
but this work
foreach (var item in tab1)
{
if (item>0)
{
tab2[a] = item;
a++;
}
}
Why is this copying method not working?
Actually copying is working but the problem is with the last line within for loop. There you are using wrong index i. There is also the problem that you are initializing destination array with the Length of the source array. It might lead to the trailing zeros in the destination array. I do propose to use List<int> it will simplify your code...and also move last line outside of the loop
int[] tab1 = { -2, 3, 4, - 5, 1, -7, -3, 4, 8, -10 };
List<int> tab2 = new List<int>(tab1.Length);
for (int i = 0; i < tab1.Length; i++)
{
if (tab1[i]>0)
{
tab2.Add(tab1[i]);
}
}
richTextBox1.AppendText(string.Join(" ", tab2);
int[] tab1 = { -2, 3, 4, - 5, 1, -7, -3, 4, 8, -10 };
int[] tab2 = new int[tab1.Length];
int a=0;
for (int i = 0; i < tab1.Length; i++)
{
if (tab1[i]>0)
{
tab2[a] = tab1[i];
richTextBox1.AppendText(tab2[a] + " ");
a++;
}
//I'm not sure why you put this outside the if statement.
//richTextBox1.AppendText(tab2[i] + " ");
}

Find Largest subarray( descending order)in a list of array c#

I need to find the largest subarray. For example: array list { 1, 4, 7, 3, -3, -4, -1, 4, 2, 1 } need to find the largest subarray where the numbers are decreasing.
As from the list { 7, 3, -3, -4 } is one subarray and { 4, 2, 1 }, as the earlier one is biggest need to print that.
Simply
var results = new List<int>();
for (var i = 0; i < input.Length; i++)
{
// how we check
var current = new List<int>();
// just to know if we are are going down
var lastValue = input[i];
// second loop make sure we stop if the numbers aren't going down
for (var j = i; j < input.Length && input[j] <= lastValue; j++)
{
current.Add(input[j]);
lastValue = input[j];
}
// Update the result depending on the criteria
if (current.Count >= results.Count)
{
results = current;
}
}
// print your awesome numbers
foreach (var value in results)
{
Console.Write($"{value}, ");
}
You can test it here
You could try this LINQ approach:
var array = new[] { 1, 4, 7, 3, -3, -4, -1, 4, 2, 1 };
var descending_subarrays =
array
.Skip(1)
.Aggregate(new [] { array.Take(1).ToList() }.ToList(), (a, x) =>
{
if (a.Last().Last() > x)
{
a.Last().Add(x);
}
else
{
a.Add(new [] { x }.ToList());
}
return a;
})
.OrderByDescending(x => x.Count)
.ToList();
That gives:
You can then just pick the find answer with a descending_subarrays.First().

How do I find duplicates in an array and display how many times they occurred?

I'm working on a code that prints out duplicated integers from an array with the number of their occurrence. I'm not allowed to use LINQ, just a simple code. I think I'm so close but confused about how to get a correct output:
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++)
{
if(array[j] == array[j+1])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
Console.ReadKey();
}
}
}
Since you can't use LINQ, you can do this with collections and loops instead:
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var dict = new Dictionary<int, int>();
foreach(var value in array)
{
// When the key is not found, "count" will be initialized to 0
dict.TryGetValue(value, out int count);
dict[value] = count + 1;
}
foreach(var pair in dict)
Console.WriteLine("Value {0} occurred {1} times.", pair.Key, pair.Value);
Console.ReadKey();
}
Use Group by:
int[] values = new []{1,2,3,4,5,4,4,3};
var groups = values.GroupBy(v => v);
foreach(var group in groups)
Console.WriteLine("Value {0} has {1} items", group.Key, group.Count());
Let's take a look at a simpler example. Let's say we have the array {0, 0, 0, 0}.
What will your code do?
It will first look to see how many items after the first item are equal to it. There are three items after the first that are equal to it.
Then it goes to the next item, and looks for all items after it that are equal to it. There are two. So far we're at 5, and we haven't even finished yet (we have one more to add), but there are only four items in the whole array.
Clearly we have an issue here. We need to ensure that when we've searched the array for duplicates of a given item that we don't search through it again for that same item. While there are ways of doing that, this fundamental approach is looking to be quite a lot of work.
Of course, there are different approaches entirely that we can take. Rather that going through each item and searching for others like it, we can loop through the array once, and add to a count of number of times we've found that character. The use of a Dictionary makes this easy:
var dictionary = new Dictionary<int, int>();
foreach (int n in array)
{
if (!dictionary.ContainsKey(n))
dictionary[n] = 0;
dictionary[n]++;
}
Now we can just loop through the dictionary and see which values were found more than once:
foreach(var pair in dictionary)
if(pair.Value > 1)
Console.WriteLine(pair.Key);
This makes the code clear to read, obviously correct, and (as a bonus) quite a lot more efficient than your code, as you can avoid looping through the collection multiple times.
Here is an answer that avoids using Dictionaries. Since the OP said he is not familiar with them, this might give him a little insight into what Dictionaries do.
The downside to this answer is you have to enforce a limit on the max number in the array, and you can't have negative numbers. You'd never actually use this version in real code.
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int[] count = new int[13];
foreach(int number in array) {
// using the index of count same way you'd use a key in a dictionary
count[number]++;
}
foreach(int c in count) {
int numberCount = count[c];
if(numberCount > 0) {
Console.WriteLine(c + " occurs " + numberCount + " times");
}
}
int[] arr = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
var result = arr.GroupBy(x => x).Select(x => new { key = x.Key, val = x.Count() });
foreach (var item in result)
{
if(item.val > 1)
{
Console.WriteLine("Duplicate value : {0}", item.key);
Console.WriteLine("MaxCount : {0}", item.val);
}
}
Console.ReadLine();
Ok I have modified your code. This should do the job:
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length; j++)
{
if (array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + " occurs " + count + " times");
}
Console.ReadKey();
}
}
/This is the answer that helps you to find the duplicate integer values using Forloop and it will return only the repeated values apart from its times of occurences/
public static void Main(string[] args)
{
//Array list to store all the duplicate values
int[] ary = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
ArrayList dup = new ArrayList();
for (int i = 0; i < ary.Length; i++)
{
for (int j = i + 1; j < ary.Length; j++)
{
if (ary[i].Equals(ary[j]))
{
if (!dup.Contains(ary[i]))
{
dup.Add(ary[i]);
}
}
}
}
Console.WriteLine("The numbers which duplicates are");
DisplayArray(dup);
}
public static void DisplayArray(ArrayList ary)
{
//loop through all the elements
for (int i = 0; i < ary.Count; i++)
{
Console.Write(ary[i] + " ");
}
Console.WriteLine();
Console.ReadKey();
}
public static void FindRepeating(int[] input)
{
for (var i = 0; i < input.Length; i++)
{
var abs = Math.Abs(input[i]);
if (input[abs] >= 0)
input[abs] = -input[abs];
else
Console.Write(abs + " ");
}
}
You made a minor mistake of using J instead of i ...
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1;
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++)
{
if(array[i] == array[j+1])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
Console.ReadKey();
}
}
}
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 7, 7, 8, 9, 7, 12, 12 };
Dictionary<int, int> duplicateNumbers = new Dictionary<int, int>();
int count=1;
for (int i = 0; i < array.Length; i++)
{
count=1;
if(!duplicateNumbers.ContainsKey(array[i]))
{
for (int j = i; j < array.Length-1; j++)
{
if (array[i] == array[j+1])
{
count++;
}
}
if (count > 1)
{
duplicateNumbers.Add(array[i], count);
}
}
}
foreach (var num in duplicateNumbers)
{
Console.WriteLine("Duplicate numbers, NUMBER-{0}, OCCURRENCE- {1}",num.Key,num.Value);
}
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
/// <summary>
/// How do you find the duplicate number on a given integer array?
/// </summary>
class Program
{
static void Main(string[] args)
{
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
Dictionary<int, int> duplicates = FindDuplicate(array);
Display(duplicates);
Console.ReadLine();
}
private static Dictionary<T, int> FindDuplicate<T>(IEnumerable<T> source)
{
HashSet<T> set = new HashSet<T>();
Dictionary<T, int> duplicates = new Dictionary<T, int>();
foreach (var item in source)
{
if (!set.Add(item))
{
if (duplicates.ContainsKey(item))
{
duplicates[item]++;
}
else
{
duplicates.Add(item, 2);
}
}
}
return duplicates;
}
private static void Display(Dictionary<int, int> duplicates)
{
foreach (var item in duplicates)
{
Console.WriteLine($"{item.Key}:{item.Value}");
}
}
}
}
int[] arr = { 1, 2, 3, 2, 4, 5, 2, 4 };
var duplicates = arr.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(y => new { Item = y.Key, Count = y.Count() })
.ToList();
Console.WriteLine(String.Join("\n", duplicates));
This approach, fixed up, will give the correct output (it's highly inefficient, but that's not a problem unless you're scaling up dramatically.)
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int count = 0;
for (int j = 0; j < array.Length ; j++)
{
if(array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + " occurs " + count);
Console.ReadKey();
}
I counted 5 errors in the OP code, noted below.
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
int count = 1; // 1. have to put "count" in the inner loop so it gets reset
// 2. have to start count at 0
for (int i = 0; i < array.Length; i++)
{
for (int j = i; j < array.Length - 1 ; j++) // 3. have to cover the entire loop
// for (int j=0 ; j<array.Length ; j++)
{
if(array[j] == array[j+1]) // 4. compare outer to inner loop values
// if (array[i] == array[j])
count = count + 1;
}
Console.WriteLine("\t\n " + array[i] + "occurse" + count);
// 5. It's spelled "occurs" :)
Console.ReadKey();
}
Edit
For a better approach, use a Dictionary to keep track of the counts. This allows you to loop through the array just once, and doesn't print duplicate counts to the console.
var counts = new Dictionary<int, int>();
int[] array = { 10, 5, 10, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12 };
for (int i = 0; i < array.Length; i++)
{
int currentVal = array[i];
if (counts.ContainsKey(currentVal))
counts[currentVal]++;
else
counts[currentVal] = 1;
}
foreach (var kvp in counts)
Console.WriteLine("\t\n " + kvp.Key + " occurs " + kvp.Value);
class Program
{
static void Main(string[] args)
{
int[] arr = { 2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12 };
List<int> nums = new List<int>();
List<int> count = new List<int>();
nums.Add(arr[0]);
count.Add(1);
for (int i = 1; i < arr.Length; i++)
{
if(nums.Contains(arr[i]))
{
count[nums.IndexOf(arr[i])] += 1;
}
else
{
nums.Add(arr[i]);
count.Add(1);
}
}
for(int x =0; x<nums.Count;x++)
{
Console.WriteLine("number:"+nums[x] +"Count :"+ count[x]);
}
Console.Read();
}
}

Using foreach and hashtable to find common element in three arrays

I am trying to find common element in three arrays. I am using Hashtable for this purpose as many people suggested here that it gives O(n) and its better.
Here is the code I have tried..
using System;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class newAttempt
{
static void Main()
{
Hashtable hm = new Hashtable();
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
for (int i = 0; i <= a.Length - 1; i++)
{
hm.Add(i, a[i]);
}
foreach(int k in b)
if (hm.Contains(k))
{
foreach (int j in c)
if (hm.Contains(j))
Console.WriteLine(j);
}
Console.ReadKey();
}
}
}
I am getting ouput as
3
4
3
4
I want my program to stop looking when it finds out that 4 is the only element which is common in this case. Please help.
Use list.Intersect function , this is example .
var list1 = new string[] {"4", "5", "6", "7", "8"};
var list2 = new string[] {"4", "5"};
var commonElement = list1.Intersect(list2);
foreach (string s in commonElement ) Console.WriteLine(s);
Output:
4
5
For more information ,
This is the example of Intersection or array !
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
var result = a.Intersect(b).Intersect(c).ToArray(); // 4
You can use the Extension Method Intersect from linq.
var hm1 = new HashSet<int>(new[] {1, 2, 3, 4, 5});
var hm2 = new HashSet<int>(new[] { 2, 4, 6, 7, 8 });
var hm3 = new HashSet<int>(new[] { 3, 4, 5, 6, 9 });
var intersection = hm1.Intersect(hm2).Intersect(hm3);
foreach (var i in intersection)
{
Console.WriteLine(i);
}
You're not checking if the inner number is the same as the outer loop's number, so essentially you're printing all numbers in b and c that are in hm. Replace your inner loop by:
foreach (int j in c)
if (j==k) // hm.Contains(j) is covered by the previous hm.Contains(k)
Console.WriteLine(j);
Edit: The other answer's intersect method is preferable for C#. Alternately, you can convert the arrays to a Set before performing this operation to improve performance for longer sequences.
Try changing the code to something like
foreach (int k in b)
if (hm.Contains(k))
{
foreach (int j in c)
if (j == k && hm.Contains(j)) //changes here
Console.WriteLine(j);
}
If you wish to exit the for loops once a match has been found you can try something like
bool found = false;
for (int bIndex = 0; !found && bIndex < b.Length; bIndex++)
{
int k = b[bIndex];
if (hm.Contains(k))
{
for (int cIndex = 0; !found && cIndex < c.Length; cIndex++)
{
int j = c[cIndex];
if (j == k && hm.Contains(j))
{
Console.WriteLine(j);
found = true;
}
}
}
}
in your code you are checking the first array with second array.if match then the first array with third array.
but what we need is,if the first to array have a match hen we want to check if that value is present in third array.only that particular value.
but your checking the whole values of first array with the third array
public static void main(String args[])
{
Hashtable hm = new Hashtable();
int[] a = new int[] { 1, 2, 3, 4, 5 };
Integer[] b = new Integer[]{ 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
for (int i = 0; i <= a.length - 1; i++)
{
hm.put(i,a[i]);
}
for(int k:b)
{
if (hm.contains(k))
{
for(int j:c)
{
if (k==j) //here is the change
{
System.out.print(j);
}
}
}
}
}
}
You can use Linq. Intersect method will be good for such purpose.
But, do you want to find out intersections just using loops and Hashtable?
this code should work:
Hashtable hm = new Hashtable();
int[] a = new int[] { 1, 2, 3, 4, 5 };
int[] b = new int[] { 2, 4, 6, 7, 8 };
int[] c = new int[] { 3, 4, 5, 6, 9 };
foreach (var iA in a)
{
foreach (var iB in b)
{
if (iA == iB && !hm.ContainsKey(iA))
{
hm.Add(iA, iA);
}
}
}
foreach (var iC in c)
{
if (hm.ContainsKey(iC))
{
Console.WriteLine(iC);
hm.Remove(iC);
}
}

Categories