Hola a todos, hoy os dejo una serie de ejercicios propuestos y resueltos de funciones y métodos 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 método que nos salude, pasándole un nombre por parámetro.
Spoiler Inside | SelectShow> |
---|---|
using System; namespace ejercicio_funciones_1 { class MainClass { public static void Main(string[] args) { saludar("Fernando"); //Llamada del método Console.ReadLine(); } //Método que saluda public static void saludar(string nombre) { Console.WriteLine("¡Hola " + nombre + " !"); // Otra forma de hacerlo (Comenta lña anterior linea) //Console.WriteLine("¡Hola {0} !", nombre); } } } |
2. Crea una función que sume dos números pasados por parámetros, devolverá el resultado.
Spoiler Inside | SelectShow> |
---|---|
using System; namespace ejercicio_funciones_2 { class MainClass { public static void Main(string[] args) { int resultado = suma(5,7); //Llamada de la función, lo guardo en una variable Console.WriteLine(resultado); Console.ReadLine(); } //Función que nos devuelve la suma de dos números public static int suma(int num1, int num2) { int resultado = num1 + num2; return resultado; } } } |
Spoiler Inside | SelectShow> |
---|---|
using System; namespace ejercicio_funciones_3 { class MainClass { public static void Main(string[] args) { Console.WriteLine(factorial(5)); //Llamo a la función Console.ReadLine(); } //Función que devuelve el factorial de un número public static int factorial(int num) { int resultado = num; //empiezo en el numero for (int i = num-1; i>1 ;i--) //empiezo en num-1 y acabo en 1 (no llega a 1) { resultado *= i; } return resultado; //devuelvo el resultado } } } |
4. Crea una función que muestre un array.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ejercicio_funciones_DDR_4 { class Program { static void Main(string[] args) { int[] valores = { 1,2,3,4,5,6,7,8,9,10 }; mostrarArray(valores); Console.ReadLine(); } public static void mostrarArray(int[] array) { for (int i=0; i</pre> |
Spoiler Inside | SelectShow> |
---|---|
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_funciones_DDR_5
{
class Program
{
static void Main(string[] args)
{
int[] valores = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int suma = sumaArray(valores);
Console.WriteLine(suma);
Console.ReadLine();
}
public static int sumaArray(int[] array)
{
int suma = 0;
for (int i=0; i</pre>
|
Spoiler Inside | SelectShow> |
---|---|
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio_funciones_DDR_6
{
class Program
{
static void Main(string[] args)
{
int[] valores = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
double media = mediaArray(valores);
Console.WriteLine(media);
Console.ReadLine();
}
public static int sumaArray(int[] array)
{
int suma = 0;
for (int i = 0; i < array.Length; i++)
{
suma += array[i];
}
return suma;
}
public static double mediaArray(int[] array)
{
int suma = sumaArray(array);
double media = (double) suma / array.Length;
return media;
}
}
}
|
7. Rellenar una matriz pasada por parámetro con un valor dado.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ejercicio_funciones_DDR_7 { class Program { static void Main(string[] args) { // Creamos las matrices int[,] matrizNumeros = new int[3, 3]; string[,] matrizString = new string[3, 3]; // Llamamos a la funciones rellenarMatriz(matrizNumeros, 3); rellenarMatriz(matrizString, "x"); Console.ReadLine(); } // Rellena una matriz dado un numero public static void rellenarMatriz(int[,] matriz, int numero) { for (int i = 0; i < matriz.GetLength(0); i++) { for (int j = 0; j < matriz.GetLength(1); j++) { matriz[i, j] = numero; } } } // Rellena una matriz dado una cadena public static void rellenarMatriz(string[,] matriz, string cadena) { for (int i = 0; i < matriz.GetLength(0); i++) { for (int j = 0; j < matriz.GetLength(1); j++) { matriz[i, j] = cadena; } } } } } |
8. Mostrar una matriz pasada por parámetro.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_8 { class Program { static void Main(string[] args) { // Creamos las matrices int[,] matrizNumeros = new int[3, 3]; string[,] matrizString = new string[3, 3]; // Rellenamos las matrices rellenarMatriz(matrizNumeros, 3); rellenarMatriz(matrizString, "x"); // Mostramos la matrices mostrarMatriz(matrizNumeros); Console.WriteLine(""); mostrarMatriz(matrizString); Console.ReadLine(); } // Rellena la matriz dado un numero public static void rellenarMatriz(int[,] matriz, int numero) { for (int i = 0; i < matriz.GetLength(0); i++) { for (int j = 0; j < matriz.GetLength(1); j++) { matriz[i, j] = numero; } } } // Rellena la matriz con una cadena dada public static void rellenarMatriz(string[,] matriz, string cadena) { for (int i = 0; i < matriz.GetLength(0); i++) { for (int j = 0; j < matriz.GetLength(1); j++) { matriz[i, j] = cadena; } } } // Muestra una matriz public static void mostrarMatriz(int[,] matriz) { for (int i = 0; i < matriz.GetLength(0); i++) { for (int j = 0; j < matriz.GetLength(1); j++) { Console.Write(matriz[i,j] + " "); } Console.WriteLine(""); } } // Muestra una matriz public static void mostrarMatriz(string[,] matriz) { for (int i = 0; i < matriz.GetLength(0); i++) { for (int j = 0; j < matriz.GetLength(1); j++) { Console.Write(matriz[i, j] + " "); } Console.WriteLine(""); } } } } |
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_9 { class Program { static void Main(string[] args) { int[,] matriz = new int[4,3]; Console.WriteLine(dentroMatriz(5, 0, matriz)); Console.ReadLine(); } // Indica si una posicion esta dentro de una matriz public static Boolean dentroMatriz(int posI, int posJ, int[,] matriz) { return posI >= 0 && posI < matriz.GetLength(0) && posJ >= 0 && posJ < matriz.GetLength(1) ; } } } |
10. Dado un numero decimal, pásalo a binario. Haz otra función que dado un binario, nos devuelva su numero decimal.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_10 { class Program { static void Main(string[] args) { Console.WriteLine("Escribe un numero decimal"); int numero = Convert.ToInt32(Console.ReadLine()); long binario = decimalBinario(numero); Console.WriteLine("El numero decimal " + numero + " en binario es: " + binario); long decimalB = binarioDecimal(binario); Console.WriteLine("El numero binario " + binario + " en decimal es: " + decimalB); Console.ReadLine(); } public static long decimalBinario(int numDecimal) { if (numDecimal < 0) { return -1; } long binario = 0; long digito; const int DIVISOR = 2; for (int i = numDecimal, j = 0; i > 0; i /= DIVISOR, j++) { digito = i % DIVISOR; Console.WriteLine(Convert.ToInt64(Math.Pow(10, j))); binario += digito * Convert.ToInt64(Math.Pow(10, j)); } return binario; } public static long binarioDecimal(long binario) { if (binario < 0) { return -1; } long numDecimal = 0; long digito; const long DIVISOR = 10; for (long i = binario, j = 0; i > 0; i /= DIVISOR, j++) { digito = (int)(i % DIVISOR); if (digito != 0 && digito != 1) { return -1; } numDecimal += digito * Convert.ToInt64(Math.Pow(2, j)); } return numDecimal; } } } |
11. Dado un numero decimal, pásalo a octal y viceversa.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_11 { class Program { static void Main(string[] args) { Console.WriteLine("Escribe un numero decimal"); int numero = Convert.ToInt32(Console.ReadLine()); long octal = decimalOctal(numero); Console.WriteLine("El numero decimal " + numero + " en octal es " + octal); int decimalO = octalDecimal(octal); Console.WriteLine("El numero octal " + octal + " en decimal es " + decimalO); Console.ReadLine(); } public static long decimalOctal(int numero) { long octal = 0; const int DIVISOR = 8; long digito = 0; for (int i = numero % DIVISOR, j = 0; numero > 0; numero /= DIVISOR, i = numero % DIVISOR, j++) { digito = i % DIVISOR; octal += digito * (long)Math.Pow(10, j); } return octal; } public static int octalDecimal(long octal) { int numero = 0; int digito = 0; const int DIVISOR = 10; for (long i = octal, j = 0; i > 0; i /= DIVISOR, j++) { digito = (int)i % DIVISOR; if (!(digito >= 0 && digito <= 7)) { return -1; } numero += digito * (int)Math.Pow(8, j); } return numero; } } } |
12. Dado un numero decimal, pásalo a hexadecimal y viceversa.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_12 { class Program { static void Main(string[] args) { Console.WriteLine("Escribe un numero decimal"); int numero = Convert.ToInt32(Console.ReadLine()); String hexadecimal = decimalHexadecimal(numero); Console.WriteLine("El numero decimal " + numero + " en hexadecimal es " + hexadecimal); int decimalH = hexadecimalDecimal(hexadecimal); Console.WriteLine("El numero hexadecimal " + hexadecimal + " en decimal es " + decimalH); Console.ReadLine(); } public static String decimalHexadecimal(int numero) { char[] letras = { 'A', 'B', 'C', 'D', 'E', 'F' }; String hexadecimal = ""; const int DIVISOR = 16; long resto = 0; for (int i = numero % DIVISOR, j = 0; numero > 0; numero /= DIVISOR, i = numero % DIVISOR, j++) { resto = i % DIVISOR; if (resto >= 10) { hexadecimal = letras[resto - 10] + hexadecimal; } else { hexadecimal = resto + hexadecimal; } } return hexadecimal; } public static int hexadecimalDecimal(String hexadecimal) { int numero = 0; const int DIVISOR = 16; for (int i = 0, j = hexadecimal.Length - 1; i < hexadecimal.Length; i++, j--) { if (hexadecimal[i] >= '0' && hexadecimal[i] <= '9') { numero += (int)Math.Pow(DIVISOR, j) * Convert.ToInt32(hexadecimal[i] + ""); } else if (hexadecimal[i] >= 'A' && hexadecimal[i] <= 'F') { numero += (int)Math.Pow(DIVISOR, j) * Convert.ToInt32((hexadecimal[i] - 'A' + 10) + ""); } else { return -1; } } return numero; } } } |
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_13 { class Program { static void Main(string[] args) { Console.WriteLine(ConvertirBaseXbaseY(10, 10, 2)); // 1010 Console.WriteLine(ConvertirBaseXbaseY(60, 10, 8)); // 74 Console.WriteLine(ConvertirBaseXbaseY(100000, 2, 10)); // 32 Console.WriteLine(ConvertirBaseXbaseY(12, 3, 2)); // 101 Console.WriteLine(ConvertirBaseXbaseY(10, 2, 8)); // 1010 Console.ReadLine(); } public static long ConvertirBaseXbaseY(long numero, int basex, int basey) { if (basex >= 2 && basex <= 10 && basey >= 2 && basey <= 10) { long numeroConvertir = 0; if (basex == 10 || basey == 10) { long digito = 0; int divisor = basey; for (long i = numero, j = 0; i > 0; i /= divisor, j++) { digito = i % divisor; numeroConvertir += digito * (int)Math.Pow(basex, j); } } else { long numeroConvertirDec = ConvertirBaseXbaseY(numero, basex, 10); numeroConvertir = ConvertirBaseXbaseY(numeroConvertirDec, 10, basey); } return numeroConvertir; } else { return -1; } } } } |
14. Crea una función que devuelva el número mayor de un array.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_14 { class Program { static void Main(string[] args) { int[] array = { 7, 4, 3, 10, 9, 3, 2, 1, 2 }; Console.WriteLine(numMayorArray(array)); Console.ReadLine(); } public static int numMayorArray(int[] array) { if (array != null && array.Length > 0) { int mayor = array[0]; for (int i = 1; i < array.Length; i++) { if (array[i] > mayor) { mayor = array[i]; } } return mayor; } return -1; } } } |
15. Crea una función que devuelva el número menor de un array.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_12 { class Program { static void Main(string[] args) { int[] array = { 7, 4, 3, 10, 9, 3, 2, 1, -2 }; Console.WriteLine(numMenorArray(array)); Console.ReadLine(); } public static int numMenorArray(int[] array) { if (array != null && array.Length > 0) { int menor = array[0]; for (int i = 1; i < array.Length; i++) { if (array[i] < menor) { menor = array[i]; } } return menor; } return -1; } } } |
16. Crea una función que devuelva la posición del número mayor de un array.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_16 { class Program { static void Main(string[] args) { int[] array = { 7, 4, 3, -10, 9, 3, 2, 1, 2 }; Console.WriteLine(posicionMayorArray(null)); Console.ReadLine(); } public static int posicionMayorArray(int[] array) { if (array != null && array.Length > 0) { int mayor = array[0]; int indice = 0; for (int i = 1; i < array.Length; i++) { if (array[i] > mayor) { mayor = array[i]; indice = i; } } return indice; } return -1; } } } |
17. Crea una función que devuelva la posición del número menor de un array.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_17 { class Program { static void Main(string[] args) { int[] array = { 7, 4, 3, 10, 9, 3, 2, 1, 1 }; Console.WriteLine(posicionMenorArray(array)); Console.ReadLine(); } public static int posicionMenorArray(int[] array) { if (array != null && array.Length > 0) { int menor = array[0]; int indice = 0; for (int i = 1; i < array.Length; i++) { if (array[i] < menor) { menor = array[i]; indice = i; } } return indice; } return -1; } } } |
18. Crea una función que devuelva el factorial de un número.
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_15 { class Program { static void Main(string[] args) { int num = 5; Console.WriteLine(Factorial(num)); Console.ReadLine(); } public static int Factorial(int numero) { if (numero > 0) { int factorial = 1; for (int i = 1; i <= numero; i++) { factorial *= i; // factorial = factorial * i; } return factorial; } return -1; } } } |
Spoiler Inside | SelectShow> |
---|---|
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_funciones_DDR_16 { class Program { static void Main(string[] args) { int pos = 3; Console.WriteLine(NumeroFibonacci(pos)); Console.ReadLine(); } // 1 1 2 3 5 8 13 21 ... public static int NumeroFibonacci(int posicion) { if (posicion > 0) { int num1 = 0, num2 = 1, suma = 1; for (int i = 1; i < posicion; i++) { suma = num1 + num2; num1 = num2; num2 = suma; } return suma; } return -1; } } } |
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Hola , quería saber para que se usa el return -1 en el ejercicio 14?
Hola, podrias ayudarme con este : – Crear un programa que pida al usuario su nombre, y le diga «Hola» si se llama «Alejandro», o bien le diga «No te conozco» si teclea otro nombre. tener en cuenta, que el la validación no es case sensitive, es decir que si escriben «alejandro» ,»Alejandro», «aleJANdrO» serán valores validos.