How do I insert elements into an array C# - c#

I'm new to programming and for one of my college classes I have to use C#. I'm not super familiar with C# and I am having trouble with my assignment. And unfortunatly I've spent a little over an hour trying to find solutions. And my search has come up empty. No one I know understands or can code anything. Plz Help
Under the Main method, create an array named as n of 10 integers.
Create a for loop to assign the value to the n array from 100 to 109.
Create a foreach loop to output each array element's value.
static void Main(string[] args)
{
int[] n = new int[10];
for (int i= 0; i < 10; i++)
{
n[i] = 100 + i;
}
foreach (int i in n)
{
Console.WriteLine(int[i]);
}
}

This line:
Console.WriteLine(int[i]);
Must be replaced with this:
Console.WriteLine(i);

Your code is almost perfect for the assignment
static void Main(string[] args)
{
// create an array named as n of 10 integers
int[] n = new int[10];
// create a for loop to assign the value to the n array from 100 to 109.
for (int i= 0; i < 10; i++)
{
n[i] = 100 + i;
}
// create a foreach loop to output each array element's value.
foreach (int item in n)
{
Console.WriteLine(item);
}
}
as you can see, in your code i is an integer from the array element, and not the array index. So your int[i] is incorrect syntax.

I implemented a few alternatives as well as a solution to your immediate challenge.
In int[i] you wrote down the data type int instead of the name of the array, which is n. when i is a valid index n[i] gives you the value. in a foreach construct you give the value a name to be used in each iteration. confusingly you named it i as well, so i gives you the value. i is common in for loops as the index so this may be confused with that idiom and you would be better off using a more speaking name like number in your code.
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Implementation1();
Console.WriteLine();
Implementation2();
Console.WriteLine();
Implementation3();
}
static void Implementation1()
{
int[] n = new int[10];
for (int i = 0; i < n.Length; ++i)
n[i] = 100 + i;
for (int i = 0; i < n.Length; ++i)
Console.WriteLine(n[i]);
}
static void Implementation2()
{
int[] n = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < n.Length; ++i)
n[i] = 100 + i;
foreach (var number in n)
Console.WriteLine(number);
}
static void Implementation3()
{
var n = Enumerable.Range(100, 10).ToArray();
string.Join(',', n.Select(val => $"{val}"));
Console.WriteLine(string.Join(',', n.Select(val => $"{val}")));
}
}

Related

Create a new array using loops in C# without built-in methods

I'm studying for my first test in C# (beginner). I have a problem with assingments where I'm supposed to create a new array using loops. For example this task where the task is to write a method that recieves a sentence(string) and a letter(char). The method must then identify at which index positions the letter
occurs at in the sentence and then place these positions in a
array. For example, we have the short sentence "Hello world!"
and the letter 'o' then the array should contain 4 (the index position of the first
instance) and 7 (the index position of the second instance).
I'm not allowed to use built-in methods except for .Length, Console.WriteLine..
You can see my code below. It is not working at all. I want it to print out "4, 7, "
static void Main(string[] args)
{
int[] result = IndexesOfChar("Hello world", 'o');
for(int i = 0; i<result.Length; i++)
{
Console.Write(result[i] + ", ");
}
}
static int[] IndexesOfChar(string sentence, char letter)
{
int count = 0;
int[] newArr = new int[count];
for(int i =0; i < sentence.Length; i++)
{
if(sentence[i] == letter)
{
newArr[count] = i;
count++;
}
}
return newArr;
}
The problem is that you don't know the array Length beforehand. So you have to compute count and
only then create the array:
static int[] IndexesOfChar(string sentence, char letter)
{
// Required array length computation:
int count = 0;
for (int i = 0; i < sentence.Length; i++)
if (sentence[i] == letter)
count++;
// We know count, we are ready to create the array:
int[] newArr = new int[count];
// Finally, we fill in the array
// let do not re-use count, but declare separate index variable
int index = 0;
for (int i = 0; i < sentence.Length; i++)
if (sentence[i] == letter)
newArr[index++] = i;
return newArr;
}
Your task is not a good example for arrays, usually we put List<T> when we don't know size:
using System.Linq;
...
static int[] IndexesOfChar(string sentence, char letter) {
List<int> result = new List<int>();
for (int i = 0; i < sentence.Length; ++i)
if (sentence[i] == letter)
result.Add(i); // <- unlike array we can just Add a new item
// create an array from list with a help of Linq
return result.ToArray();
}
It is not working, because in the method IndexesOfChar, you create an array with a length of count (that is at that point is zero). You can't modify an array's length once you declared it.
If you can't use any built in methods, I suggest you to declare the newArr as a list. This is what you should fill the indexes into, then create an array, and fill the list's values into that array with another for loop.
Unlike type List, you can't change the size of an array, so you can't do newArr[count] = i; because the size of newArr is 0. Instead if you only want to use arrays, you can reassign newArr with its old value + the new integer :
static void Main(string[] args)
{
int[] result = IndexesOfChar("Hello world", 'o');
for(int i = 0; i<result.Length; i++)
{
Console.Write(result[i] + ", ");
}
}
static int[] IndexesOfChar(string sentence, char letter)
{
int count = 0;
int[] newArr = new int[count];
for(int i =0; i < sentence.Length; i++)
{
if(sentence[i] == letter)
{
var updateArr = new int[newArr.Length + 1];
for (int j = 0; j < newArr.Length; j++)
{
updateArr[j] = newArr[j];
}
updateArr[newArr.Length] = i;
newArr = updateArr;
count++;
}
}
return newArr;
}

User input array and display frequency of each integer

This is the problem given:
Write a program in C# that prompts the user to enter a number of integer values. The program
stores the integers in an array, counts the frequency of each integer and displays the frequency on the Console.
I am new to C# and don`t know Linq or dictionary yet.
static void Main(string[] args) {
//declare variables
int n,
y,
x;
int[] index;
int[] count;
//prompt user for the number of elements
Console.WriteLine("Please enter the number of element to be stored");
n = int.Parse(Console.ReadLine());
index = new int[n];
count = new int[n];
//Console.WriteLine(index.Length);
Console.WriteLine("input {0} number of element", n);
for (int i = 0; i < index.Length; i++) {
index[i] = int.Parse(Console.ReadLine());
for (y = 0; y < index.Length; y++)
if (index[y] == i) count[i]++;
}
for (int j = 0; j < index.Length; j++)
Console.WriteLine("element - {0} : {1}", j, index[j]);
Console.WriteLine("the frequency of all elements of the array");
for (x = 0; x < index.Length; x++)
Console.WriteLine("{0} occurs {1} times", index[x], x);
}
This the result I get if I select 3 integers of 2, 1, 2. 2 is repeated.
2 occurs 0 times.
1 occurs 1 times.
2 occurs 2 times.
You’re doing in wring way. And perform wise also it’s not efficient solution. You are run for loop inside for loop. You can use dictionary and store the count in it, so it will work in a single for loop.
static void GetFrequency(int[] arr)
{
Dictionary<int, int> mp = new Dictionary<int, int>();
// Traverse through array elements and count frequencies
for (int i = 0; i < arr.Length; i++)
{
if (mp.ContainsKey(arr[i]))
{
var val = mp[arr[i]];
mp.Remove(arr[i]);
mp.Add(arr[i], val + 1);
}
else
{
mp.Add(arr[i], 1);
}
}
}
Usually, when we want to query (i.e. find out frequencies) a collection (array) we use Linq:
using System.Linq;
...
var freqData = index
.GroupBy(item => item)
.Select(group => $"{group.Key} occurs {group.Count()} times.");
Console.WriteLine(string.Join(Environment.NewLine, freqData));
If you want to count frequency manually, you can use Dictionary<int, int> to have Key (item from the array)
and Value (frequency) correspondence:
Dictionary<int, int> freqData = new Dictionary<int, int>();
foreach (int item in index)
if (freqData.TryGetValue(item, out int freq))
freqData[item] = freq + 1;
else
freqData.Add(item, 1);
foreach (var pair in freqData)
Console.WriteLine($"{pair.Key} occurs {pair.Value} times.");

Trying to find Frequency of elements in array

I am trying to count how many times a number appears in an array 1 (a1) and then trying to print out that number by storing it in array 2 (a2) just once and then try to print array 2. But first using for loop and a function, I will check that if a number already exist in array 2 then move to next index in array 1, unfortunateley this code is not working; can someone please help me in trying to fix it, I don't need some complex solutions like dictionaries or lists athe moment, although it might be helpful too. thanks, I am not an expert in programming and I try to practise it in my free time, so please help me.
I just want this code to be fixed for my understanding and knowledge
class Program
{
static void Main(string[] args)
{
int i, j;
int[] a1 = new int[10];
int[] a2 = new int[10];
int[] a3 = new int[10];
//takes an input
for (i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < a1.Length; i++)
{
Cn(a1, a2); //calls in function
i++; //increments is if true
int count = 0;
for (j = 0; j < a1.Length; j++)
{
//if a number matches with a number in second array
if (a1[i] == a1[j])
{
//do count ++
count++;
// store that number into second array
a2[i] = a1[i];
}
}
//store the number of counts in third array
a3[i] = count;
}
for (i = 0; i < a2.Length; i++)
{
if (a2[i] != 0)
{
Console.WriteLine(a2[i]);
}
}
Console.ReadLine();
}
//function to check if element at current index of array 1 exists in array 2 if yes than break
public static void Cn (int[] aa1, int [] aa2)
{
int k, j;
for ( k = 0; k < aa1.Length; k++)
{
for (j = 0; j < aa2.Length; j++)
{
if (aa1[k] == aa2[j])
break;
}
}
}
}
You probably want to do a group by count:
int[] a1 = new int[10];
var rnd = new Random();
//takes an input
for (int i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(rnd.Next(0, 11)); // or Console.ReadLine()
}
var grouped = a1
.GroupBy(x => x)
.Select(g => new
{
Item = g.Key,
Count = g.Count()
}).ToList(); // ToList() is optional, materializes the IEnumerable
foreach (var item in grouped)
{
Console.WriteLine($"number: {item.Item}, count: {item.Count}");
}
This uses a Hash algorithm internally.
You can solve this without a Hash or Dictionary but it wouldn't be very efficient because you need to do lots of linear searches through the arrays.
The advantage of a Hash algorithm is that your lookups or groupings are much faster than if you loop over a complete array to find / increment an item.

Change this nested for loop to recursion [duplicate]

This question already has an answer here:
Creating all possible arrays without nested for loops [closed]
(1 answer)
Closed 6 years ago.
I posted this similar, previous question, but I was not very clear.
I have the following code:
int N=4;
int[] myArray = new int[N];
for (int i1 = 1; i1 < N; i1++)
myArray[0]=i1;
for (int i2 = 1; i2 < N; i2++)
myArray[1]=i2;
for (int i3 = 1; i3 < N; i3++)
myArray[2]=i3;
for (int i4 = 1; i4 < N; i4++)
{
myArray[3]=i4;
foreach (var item in myArray)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
}
This outputs the following:
1111
1112
1113
1121
1122
1123
1131
....
3332
3333
Is there a simple way to change this nested for loop to recursion? I am not very skilled at programming, so the simpler, the better. I am not worried about how efficient the code is.
I, effectively, would like to be able to change the int N in my code to different numbers, without having to add or remove anything from my code.
EDIT
Here is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sandbox
{
class Program
{
static void Main(string[] args)
{
int class_length = 4;
int[] toric_class = Enumerable.Repeat(1, class_length).ToArray();
Recursion(toric_class, class_length, 1, 3);
Console.Read();
}
static void Recursion(int[] toric_class, int length, int number, int spot)
{
if (number < 4)
{
toric_class[spot] = number;
foreach (var item in toric_class)
{
Console.Write(item.ToString());
}
Console.Write(Environment.NewLine);
Recursion(toric_class, length, number + 1, spot);
}
}
}
}
This only outputs
1111
1112
1113
I am unsure of where to go from here.
public static void Set(int[] array, int index, int N)
{
if (index == N)
{
foreach (var item in array)
Console.Write(item.ToString());
Console.Write(Environment.NewLine);
return;
}
for (int i = 1; i < N; i++)
{
array[index] = i;
Set(array, index + 1, N);
}
}
And call it this way:
int N = 4;
int[] myArray = new int[N];
Set(myArray, 0, N);
If you want just to simplify and generalize the solition, you don't want any recursion:
// N - length of the array
// K - kind of radix; items of the array will be in [1..K] range
private static IEnumerable<int[]> Generator(int N = 4, int K = 3) {
int[] items = Enumerable
.Repeat(1, N)
.ToArray();
do {
yield return items.ToArray(); // .ToArray() : let's return a copy of the array
for (int i = N - 1; i >= 0; --i)
if (items[i] < K) {
items[i] += 1;
break;
}
else
items[i] = 1;
}
while (!items.All(item => item == 1));
}
Test
string test = string.Join(Environment.NewLine, Generator(4)
.Select(items => string.Concat(items)));
Console.Write(test);
Outcome:
1111
1112
1113
1121
1122
...
3321
3322
3323
3331
3332
3333

Better way of inserting numbers into an array while sorting it

Let's say I want to insert values into an array while at the same time sorting it.
This was my solution:
int[] arr = new int[5];
int k;
arr[0] = int.Parse(Console.ReadLine());
for (int i = 1; i < arr.Length; i++)
{
int num = int.Parse(Console.ReadLine());
for (k = i; k > 0 && num < arr[k - 1];--k) arr[k] = arr[k - 1];
arr[k] = num;
}
I know I didn't handle exceptions, I'm just talking about the code itself.
Is there a better way of doing this?
You can use a SortedSet<>, that gets automatically sorted as you add items.
var numbers = new SortedSet<int>()
{
4,
9,
6,
3
};
foreach (var number in numbers)
{
Console.WriteLine(number);
}
If it doesn't have to be array you could do this:
static void Main(string[] args)
{
List<int> list = new List<int>
{
1,
2,
7,
10
};
int k = int.Parse(Console.ReadLine());
list.Add(k);
list.Sort();
}
Edit: if you want to sort when inserting you could do this:
int k = int.Parse(Console.ReadLine());
int i = list.Where(x => x > k).Min();
int index = list.IndexOf(i);
list.Insert(index, k);
You can use a List and convert it into an array. When you maintain your list ordered at all time you can use the list's BinarySearch method to get the insert index:
const int length = 5;
List<int> result = new List<int>(length);
for (int i = 0; i < length; i++) {
int num = int.Parse(Console.ReadLine());
int insertIndex = result.BinarySearch(num);
if (insertIndex < 0) {
insertIndex = ~insertIndex;
}
result.Insert(insertIndex, num);
}
int[] arr = result.ToArray();
The binary search is much faster than the linear search you are currently performing. You won't see that with your current 5 values. You would defenitely see it with larger lists (hundrets or thousands of values).

Categories

Resources