It turns out that I need to design a program that performs the following actions:
-Request an integer from the user.
The program then asks for as many integers as the previously entered number and stores them in a vector.
The program then asks for two more integers: the first corresponds to a position and the second to a new value to insert the vector.
Finally the program has to insert the new element to the vector in the introduced position. If the entered position is negative, the new element will be inserted at the first position of the vector. If the number entered is greater than the possible positions in the list, the new element will be inserted at the last position in the array.
I would like to resolve the errors keeping the structure of the program. All errors are marked with comments but basically it is based on crashes and not returning the message on the console. I have also made two elses at the end of the code since I don't know if it is the same or which one is better to reach my goal. I know it would probably be easier to do it with lists but I need to do it with vectors.
I attach the code:
using System;
namespace insert
{
class Program
{
static void Main(string[] args)
{
int elements, position, change;
Console.WriteLine("Insert total elements: ");
elements = int.Parse(Console.ReadLine());
int[] numbers = new int[elements];
for(int i = 0; i<elements; i++)
{
Console.WriteLine("Insert integer value: ");
numbers[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Insert position to insert element: ");
position = int.Parse(Console.ReadLine());
Console.WriteLine("Insert integer value to insert: ");
change = int.Parse(Console.ReadLine());
Console.WriteLine("The final values for the array are: ");
int[] result = Insert(numbers, change, position, elements);
for (int i = 0; i <= elements; i++)
{
Console.WriteLine(result[i]);
}
}
static int[] Insert(int[] numbers, int change, int position, int elements)
{
int[] newnumbers = new int[elements + 1];
if(position < 0)
{
newnumbers[0] = change;
for(int i = 1; i <= elements; i++)
{
newnumbers[i] = numbers[i - 1];
}
}
else if (position > elements) //este apartado da error
{
newnumbers = numbers; //no sé si es así o newnumbers[elements + 1] = numbers[elements];
newnumbers[elements] = change;
}
/*else //este apartado no da error pero tampoco resultado :c Manera fácil
{
newnumbers[elements + 1] = numbers[elements];
newnumbers[position - 1] = change;
} */
else //este apartado no da error pero tampoco resultado :c Manera difícil
{
for (int i = 0; i <= elements; i++)
{
if (i + 1 == position)
{
newnumbers[i] = change;
i--;
}
else
{
newnumbers[i] = numbers[i];
}
}
}
return newnumbers;
}
}
}
The rectified code for your insert method would look like this and I'll tell you so you can understand what you've done wrong:
In your main function, just change the way you call the method without passing it the number of elements in the array: