1. 4 E J E M P L O S E N C # ( S H A R P ) E N
A P L I C A C I Ó N C O N S O L A +
C O D I G O S
Por kedinn 2013/02/17
1) Un hombre desea saber cuanto dinero se genera por concepto de intereses sobre la
cantidad que tiene en inversión en el banco. El decidirá reinvertir los intereses siempre
y cuando estos excedan a S/.7000, y en ese caso desea saber cuanto dinero tendrá
finalmente en su cuenta.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio01
{
class Hombre
{
private string nombre;
private float dinero;
public void Inicio()
{
Console.WriteLine("---------BANCO COMOPROGRAMAR.ORG--------");
Console.WriteLine("-----------------------------");
Console.WriteLine("INGRESE SU NOMBRE: ");
nombre = Console.ReadLine();
Console.WriteLine("INGRESE SU MONTO DINERO; ");
dinero = float.Parse(Console.ReadLine());
Console.Clear();
}
public void Imprimir()
{
Console.WriteLine("---------BANCO COMOPROGRAMAR.ORG--------");
Console.WriteLine("-----------------------------");
Console.WriteLine("NOMBRE: " + nombre);
if (dinero > 7000)
{
Console.WriteLine("USTED NO PUEDE EXCEDER EL MONTO DE S/ 7000");
}
else
{
Console.WriteLine("INVERSION: " + dinero);
}
Console.ReadLine();
2. }
static void Main(string[] args)
{
Hombre per = new Hombre();
per.Inicio();
per.Imprimir();
}
}
}
2) En un almacén se hace un 20% de descuento a los clientes cuya compra supere los
S/.1000 ¿ Cual será la cantidad que pagara una persona por su compra?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicios02
{
class Cliente
{
private float descuento;
private float precio;
public void Inicio()
{
Console.WriteLine("INGRESE PRECIO: ");
precio = float.Parse(Console.ReadLine());
Console.Clear();
}
public void Descuento()
{
if (precio > 1000)
{
float res = (precio * 20) / 100;
descuento = precio - res;
Console.WriteLine("--------TIENDA KEDINN -------");
Console.WriteLine("DESCUENTO DEL 20% POR SUPERAR S/1000");
Console.WriteLine("PRECIO ES: " + descuento);
Console.ReadLine();
}
else
{
Console.WriteLine("--------TIENDA KEDINN -------");
Console.WriteLine("PRECIO ES: " + precio);
Console.ReadLine();
}
Console.ReadKey();
}
static void Main(string[] args)
3. {
Console.WriteLine("--------TIENDA KEDINN -------");
Cliente clie = new Cliente();
clie.Inicio();
clie.Descuento();
}
}
}
3) Un obrero necesita calcular su salario semanal, el cual se obtiene de la siguiente.
manera:
- Si trabaja 40 horas o menos se le paga S/.16 por hora
- Si trabaja mas de 40 horas se le paga S/.16 por cada una de las primeras 40
horas y S/.20 por cada hora extra.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio3
{
class Camisas
{
int camisas;
float precio;
public void Ingresar()
{
Console.WriteLine("INGRESE NUMERO DE CAMISAS");
camisas = int.Parse(Console.ReadLine());
Console.WriteLine("INGRESE PRECIO DE LAS CAMISAS");
precio = float.Parse(Console.ReadLine());
}
public void Trabajo()
{
if (camisas >= 3)
{
float a = (precio * 20) / 100;
float b = precio - a;
Console.WriteLine("DESCUENTO 20% PRECIO ES: "+ b);
}
else
{
float a = (precio * 01) / 100;
float b = precio - a;
Console.WriteLine("DESCUENTO 20% PRECIO ES: " + b);
}
Console.ReadKey();
}
static void Main(string[] args)
{
Camisas sem = new Camisas();
4. sem.Ingresar();
sem.Trabajo();
}
}
}
4) Hacer un algoritmo que calcule el total a pagar por la compra de camisas. Si se compran
tres camisas o mas se aplica un descuento del 20% sobre el total de la compra y si son
menos de tres camisas un descuento del 10%
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ejercicio3
{
class Camisas
{
float precio;
public void Ingresar()
{
Console.WriteLine("-----EMPRESA FAEMAS-----");
Console.WriteLine("INGRESE PRECIO DE LAS CAMISAS");
precio = float.Parse(Console.ReadLine());
}
public void Trabajo()
{
Console.WriteLine("-----EMPRESA FAEMAS-----");
if (precio >= 500000)
{
Console.WriteLine("la empresa tendrá la capacidad de invertir de su
propio dinero un 55% del monto de la compra, pedir prestado al banco un 30% y el
resto lo pagara solicitando un crédito al fabricante ");
}
else
{
Console.WriteLine("la empresa tendrá capacidad de invertir de su
propio dinero un 70% y el restante 30% lo pagará solicitando crédito al fabricante.
" );
}
Console.ReadKey();
}
static void Main(string[] args)
{
Camisas sem = new Camisas();
sem.Ingresar();
sem.Trabajo();
}
}
}
5. LEER ARCHIVOS DBF EN C#
privatevoid consultar_Click(object sender, EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = @"Provider=vfpoledb;Data Source=C:UsersjoselilloDesktopdb fi;Collating
Sequence=machine;";
con.Open();
OleDbCommand ocmd = con.CreateCommand();
ocmd.CommandText = @"SELECT * FROM Fac.DBF";
DataTable dt = new DataTable();
dt.Load(ocmd.ExecuteReader());
con.Close();
}
catch(OleDbException exp)
{
MessageBox.Show("Error: " + exp.Message);
}
}
CALENDARIO ANUAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CalendarStuff
{
class Program
{
static void Main(string[] args)
{
Console.WindowHeight = 46;
Console.Write(buildMonths(new DateTime(2016, 1, 1)));
Console.Read();
}
private static string buildMonths(DateTime date)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(center("[[ Calendario ]]", 24 * 3));
sb.AppendLine();
sb.AppendLine(center(date.Year.ToString(), 24 * 3));
List<DateTime> dts = new List<DateTime>();
while (true)
{
dts.Add(date);
if (date.Year != ((date = date.AddMonths(1)).Year))
{
break;
}
}
var jd = dts.Select(a =>
buildMonth(a).GetEnumerator()).ToArray();
6. int sCur=0;
while (sCur<dts.Count)
{
sb.AppendLine();
int curMonth=0;
var j = jd.Where(a => curMonth++ >= sCur && curMonth - 1
< sCur + 3).ToArray(); //grab the next 3
sCur += j.Length;
bool breakOut = false;
while (!breakOut)
{
int inj = 1;
foreach (var cd in j)
{
if (cd.MoveNext())
{
sb.Append((cd.Current.Length ==
21 ? cd.Current : cd.Current.PadRight(21, ' ')) + " ");
}
else
{
sb.Append("".PadRight(21, ' ') +
" ");
breakOut = true;
}
if (inj++ % 3 == 0) sb.AppendLine();
}
}
}
return sb.ToString();
}
private static IEnumerable<string> buildMonth(DateTime date)
{
yield return center(date.ToString("MMMM"),7*3);
var j = DateTime.DaysInMonth(date.Year, date.Month);
yield return "Lu Ma Mi Ju Vi Sa Do ";
string cur = "";
int total = 0;
foreach (var day in Enumerable.Range(-((int)date.DayOfWeek)+1,j
+ (int)date.DayOfWeek-1))
{
cur += (day < 0 ? " " : ((day < 9 ? " " : "") + (day +
1))) +" ";
if (total++ > 0 && (total ) % 7 == 0)
{
yield return cur;
cur = "";
}
}
yield return cur;
}
private static string center(string s, int len)
{
return (s.PadLeft((len - s.Length) / 2 + s.Length, '
').PadRight((len), ' '));
}
}
}
7. código para comprender el ciclo Do While
int num, i, suma;
Console.WriteLine(" suma sucesiva ");
Console.WriteLine();
Console.Write(" TECLEEA EL NUMERO ; ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
i = 1;
suma = 0;
do
{
Console.WriteLine(i);
suma = suma + i;
i = i + 1;
} while (i <= num);
Console.WriteLine("la suma es: " + suma);
Console.ReadLine();
------------------------------------------------------------------------------------------------------------
código para comprender el ciclo FOR.
el ciclo for en c# es muy sencillo de utilizar, y sirve de gran ayuda pero también es muy sencillo de
aprender
se inicia con for , dentro de lo que es los parámetros podemos decretar variables, en este caso nuestro
contador seguido de un " ; " (int i=0; , después el parámetro a cumplir por ejemplo queremos que nos
imprima 20 números o que el ciclo de 20 vueltas, entonces seria i<=20; , y por ultimo en caso de que se
cumpla el parámetro pasado, que ara, incrementar o restar nuestro contador, hay 2 formas i++ o i+1.
Y quedaría de la siguiente forma.
for (i=1;i<=20;i=i+1)
he aquí un código para imprimir la tabla del numero que desees utilizando ciclo FOR
int i, num;
Console.WriteLine(" TABLAS DE MULTIPLICAR");
Console.WriteLine();
Console.Write(" INTRODUCE UN NUMERO A MULTIPLICAR; ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
Console.WriteLine();
i = 0;
for(i=1;i<=20;i=i+1)
8. Console.WriteLine(num + "x" + i + "=" + num * i);
Console.ReadLine();
/*
while (i <= 20)
{
Console.WriteLine(num + "x" + i + "=" + num * i);
i = i + 1;
}
Console.ReadLine();
*/
------------------------------------------------------------------------------------------------------------
Con este código calcula el volumen de cualquier cilindro, en este caso una pizza.
double a;
double v;
double z;
Console.Write("teclee el ancho de pizza: ");
v = Convert.ToDouble(Console.ReadLine());
Console.Write("teclee la altura; ");
a = Convert.ToDouble(Console.ReadLine());
z = (3.141615 * v * v * a);
Console.WriteLine( "volunen; {0}", z );
Console.Read();
------------------------------------------------------------------------------------------------------------
Decisión IF
con este sencillo código aprendes fácilmente como funciona If y Else capturando
una calificación y comparándola ya con un parámetro, en este caso "70".
double calificacion;
Console.Write("inroduce la calificación: ");
calificacion = Convert.ToDouble(Console.ReadLine());
if (calificacion >= 70)
{
Console.WriteLine();
Console.WriteLine(" ############");
Console.WriteLine(" # APROBADO #");
Console.WriteLine(" ############");
9. Console.Read();
}
else
{
Console.WriteLine();
Console.WriteLine(" #############");
Console.WriteLine(" # REPROBADO #");
Console.WriteLine(" #############");
Console.Read();
------------------------------------------------------------------------------------------------------------
comprender los operadores de c#
int x;
x = 8;
Console.WriteLine(x++);//operacion suma 8+1
Console.WriteLine(x);//imprecion de resultado 9
Console.WriteLine(++x);//operacion e impresion 9+1 = 10
Console.WriteLine(x--);// operacion resta 10-1
Console.WriteLine(x);//impresion de resultado 9
Console.WriteLine(--x);// operacion e impresion 9-1=8
Console.WriteLine(x);// impresion 8
------------------------------------------------------------------------------------------------------------
Convierte una aplicación de consola en una calculadora que suma aplicando ciclo for
con este código.
Console.Read();
int numero1;
int nuemro2;
int resultado;
Console.WriteLine("BIENVENIDO ");
Console.WriteLine();
Console.WriteLine(" S U M A D E D O S N U M E R O S ");
Console.WriteLine();
/* Console.WriteLine("escribe el primer numero");
numero1 = Convert.ToInt32(Console.ReadLine());
10. Console.Write("escribe el siguiente numero");
Console.WriteLine();
nuemro2 = Convert.ToInt32(Console.ReadLine());
Console.ForegroundColor = ConsoleColor.Yellow;
resultado = numero1 + nuemro2;
Console.Write("la suma es: {0}", resultado);
Console.Read();*/
// con un ciclo for para mejorarlo
int num, sum, sum2 = 0;
Console.WriteLine("cuantos numeros quieres sumar? ");
num = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= num ; i++)
{
Console.WriteLine("teclee el " + i + " numero: ");
sum = Convert.ToInt32(Console.ReadLine());
sum2 = sum + sum2;
}
Console.WriteLine("la suma total es {0} ", sum2);
Console.ReadKey();
------------------------------------------------------------------------------------------------------------
Obtén tu promedio y comprende el comando if con este código que obtiene el
promedio y te imprime si estas reprobado o no.
int numero1;
int numero2;
int numero3 = 0;
int promedio;
Console.Write("cuantos numeros quieren promediar: ");
numero1 = Convert.ToInt32(Console.ReadLine());
for(int i = 1;i <= numero1; i++)
{
Console.Write("Teclee el "+ i +" numero: ");
numero2 = Convert.ToInt32(Console.ReadLine());
numero3 = numero2 + numero3;
}
promedio = numero3 /numero1 ;
Console.WriteLine(" # # ");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(" Promedio: {0}", promedio);
Console.ForegroundColor = ConsoleColor.White;
11. Console.WriteLine(" # # ");
Console.ReadLine();
------------------------------------------------------------------------------------------------------------
Código para obtener el promedio de 3 calificaciones.
double numero1;
double numero2;
double numero3;
double promedio;
Console.Write("Bienvenido, teclee el primer número: ");
numero1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
Console.Write("Teclee el segundo número: ");
numero2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
Console.Write("Teclee el último número a promediar: ");
numero3 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine();
promedio = (numero1 + numero2 + numero3) / 3;
if (promedio >= 70)
{
Console.WriteLine();
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" ############ ");
Console.WriteLine(" # APROBADO # ");
Console.WriteLine(" ############ ");
Console.Read();
}
else
{
Console.WriteLine();
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" ############# ");
Console.WriteLine(" # REPROBADO # ");
Console.WriteLine(" ############# ");
Console.Read();
12. códigos en consola c#.
Pirámide
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string text = "";
for (int i = 1; i < 22; i++)
{
text = "";
for (int j = 1; j < i; j++)
{
text += (Convert.ToString(j)+" ");
}
Console.WriteLine(text);
Console.Write("n");
}
Console.ReadKey();
}
}
}
y quedaría
de la siguiente forma;