Hola a todos, hoy os dejo una serie de ejercicios propuestos y resueltos de arrays en C#.
Todos los ejercicios que proponemos están resueltos en este mismo post, intenta hacerlo por ti mismo y si te quedas atascado puedes mirar la solución. Recuerda, que no tiene por que estar igual tu solución con la del post, el objetivo es que aprendas no que me copies la solución.
Te recomiendo que uses mensajes de trazas, donde te sean necesarios. Si tienes problemas también puedes usar el depurador.
1) Crea un array de 10 posiciones, con valores puestos por ti y muestra el array.
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_arrays_DDR_1
{
class Program
{
static void Main(string[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10};
for (int i=0; i<array.Length ;i++)
{
Console.WriteLine(array[i]);
}
Console.ReadLine();
}
}
}
|
2) Crea un array de 10 posiciones, pide los valores por consola y muestra el array.
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_arrays_DDR_2
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[10];
for(int i=0; i<array.Length; i++)
{
Console.WriteLine("Escribe un numero en la pos " + i);
int num = Convert.ToInt32(Console.ReadLine());
array[i] = num;
}
Console.WriteLine("Mostrar datos");
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
Console.ReadLine();
}
}
}
|
3) Sumar los valores de un array y mostrar el resultado.
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_arrays_DDR_3
{
class Program
{
static void Main(string[] args)
{
int[] valores = { 1,2,3,4,5 };
int suma = 0;
for (int i=0; i< valores.Length ;i++)
{
suma += valores[i];
}
Console.WriteLine("La suma es "+ suma);
Console.ReadLine();
}
}
}
|
4) Hacer la media de los valores de un array y mostrar el resultado.
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_arrays_DDR_4
{
class Program
{
static void Main(string[] args)
{
int[] valores = { 1, 2, 3, 4, 5, 6 };
int suma = 0;
for (int i = 0; i < valores.Length; i++)
{
suma += valores[i];
}
double media = (double) suma / valores.Length;
Console.WriteLine("La media es " + media);
Console.ReadLine();
}
}
}
|
5) Pedir un numero por teclado y multiplicar todos los valores de un array y mostrar el array.
Spoiler Inside |
SelectShow> |
using System;
namespace ejercicio_basicos_DDR_5
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Escribe un dia de la semana");
String dia = Console.ReadLine ();
switch(dia.ToLower()){
case "lunes":
case "martes":
case "miercoles":
case "jueves":
case "viernes":
Console.WriteLine ("No es fin de semana");
break;
case "sabado":
case "domingo":
Console.WriteLine ("Es fin de semana");
break;
default:
Console.WriteLine ("Ese dia no es correcto");
break;
}
Console.ReadLine ();
}
}
}
|
6) Dado un array de numeros con el metodo Sort, ordenalos y muestra su contenido.
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_arrays_DDR_6
{
class Program
{
static void Main(string[] args)
{
int[] valores = { 4, 3, 7, 10, 1, 5, 7 };
Array.Sort(valores);
for (int i=0; i<valores.Length ;i++)
{
Console.WriteLine(valores[i]);
}
Console.ReadLine();
}
}
}
|
7) Dado un array de números, muestra el mayor y el menor.
Spoiler Inside |
SelectShow> |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_arrays_DDR_7
{
class Program
{
static void Main(string[] args)
{
int[] valores = { 4, 3, 7, 10, 100, 5, 7 };
Array.Sort(valores);
int maximo = valores[valores.Length-1];
int minimo = valores[0];
/*
int maximo = valores[0];
int minimo = valores[0];
for (int i = 1; i<valores.Length; i++) { if (valores[i] > maximo)
{
maximo = valores[i];
}
if (valores[i] < minimo)
{
minimo = valores[i];
}
}*/
Console.WriteLine("El valor minimo es: "+minimo);
Console.WriteLine("El valor maximo es: "+maximo);
Console.ReadLine();
}
}
}
|
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Como funciona esta línea de código?
int maximo = valores[valores.Length-1];
Solo entiendo que maximo es igual al tamaño del arreglo menos 1
Creo que hay menos rollo en el ejercicio 2 de esta manera, pero al final es lo mismo
//2) Crea un array de 10 posiciones, pide los valores por consola y muestra el array.
using System;
namespace Array2
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[10];
Console.WriteLine(«Ingrese valores.»);
for (int i = 0; i < array.Length; i++)
{
string teclado = Console.ReadLine();
array[i] = int.Parse(teclado);
}
Console.WriteLine("Datos ingresados: ");
for (int i = 0; i < array.Length;i++)
{
Console.WriteLine (array[i]);
}
Console.ReadKey();
}
}
}
Permitiendo que el usuario introduzca la cantidad de valores a sumar.
Problema 3
// 3) Sumar los valores de un array y mostrar el resultado
using System;
namespace Array3
{
class Program
{
public static void Main(string[] args)
{
int num;
int suma = 0;
Console.Write(«Cuantos valores a ingresar?: «);
string teclado = Console.ReadLine();
num = int.Parse(teclado);
int[]array = new int[num];
Console.WriteLine(«Ingrese los numeros. «);
for (int i = 0; i < array.Length; i++)
{
teclado = Console.ReadLine();
array[i] = int.Parse(teclado);
suma = suma + array[i];
}
Console.WriteLine("La suma de los valores es = " + suma);
Console.ReadKey();
}
}
}
Hola bro no entiendo la lógica de tu respuesta en el último ejercicio… humildemente te presento mi problema resuelto. Saludos dsd mx
//Dado un array de números, muestra el mayor y el menor.
using System;
namespace array7
{
class Program
{
public static void Main(string[] args)
{
int[]array = new int[] {4,56,76,2,1,23,8};
int mayor = array[0];
for (int i = 0; i mayor)
{
mayor = array[i];
}
}
Console.WriteLine(«El elemento mayor es —-> » + mayor);
Console.ReadKey();
}
}
}
¿Y donde sacas el menor? Además que no sacas el mayor de esa forma.
¿Porque usar un array? No es necesario realmente.
Esta fue mi forma de realizar el ultimo ejercicio… cualquier comentario es bienvenido
using System;
using System.Linq;
namespace Media{
class MediaDatos{
static void Main(string[] args){
int[] cadena = new int[] {4,6,7,3,123,5,63,5,3};
int datoMayor = cadena.Max();
int datoMenor = cadena.Min();
Console.WriteLine(«Dato Mayor : «+datoMayor);
Console.WriteLine(«Dato Menor : «+datoMenor);
}
}
}
en el ejercicio 2 dice que lo pidan los valores lo mas logico es que se pida por consola.
YO lo hice de la siguiente forma:
List lista = new List();
for(int i=0; i < 10; i++)
{
Console.WriteLine($"Intoduzca el valor {i + 1} de su lista");
lista.Add(Console.ReadLine());
}
for(int i = 0; i < lista.Count(); i++)
{
Console.WriteLine(lista[i]);
}
hola bro disculpa tengo duda de como hacer esto Crear una función que reciba un array de enteros y devuelva el MAYOR
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arreglo06
{
internal class Program
{
//6) Dado un array de numeros con el metodo Sort, ordenalos y muestra su contenido.
static void Main(string[] args)
{
foreach (int i in DevolverDatos())
{
Console.WriteLine(«\nLos numeros ordenados son: «+i);
}
Console.ReadKey();
}
static int[] DevolverDatos()
{
Console.WriteLine(«Ingrese el tamaño del array: «);
string tam = Console.ReadLine();
int tamanioarray = int.Parse(tam);
int[] datos = new int[tamanioarray];
Console.WriteLine(«Ingresar datos: «);
for (int i=0;i<tamanioarray;i++)
{
Console.WriteLine("Posición "+i);
string valor = Console.ReadLine();
int valores = int.Parse(valor);
datos[i] = valores;
}
Console.WriteLine("\nValor Máximo: " + datos.Max());
Console.WriteLine("Valor Mínimo: " + datos.Min());
Array.Sort(datos);
return datos;
}
}
}
//Dejo mi granito de arena para los nuevos estudiantes que están en aprendizaje. Haciendo uso del método y siendo llamado en el Main.