Mostrando entradas con la etiqueta C. Mostrar todas las entradas
Mostrando entradas con la etiqueta C. Mostrar todas las entradas

viernes, 31 de agosto de 2012

Algoritmo:Calcular la raiz cuadradada en C/C++

Aqui les comparto un codigo que calcula la raiz cuadrada de un numero ingresado por el usuario. En este ejemplo utilizamos la libreria para llamar a la funcion sqrt
Codigo Fuente en C

#include<math.h>
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
float num,sq;
printf("Ingrese un numero para calcular la raiz cuadrada: ");
scanf("%f", &num);
while(getchar() != '\n');
sq=sqrt(num);
printf("\n\nLa raiz cuadrada de %.1f es %.2f", num, sq);
getch();
return 0;
}
Codigo Fuente en C++

#include <iostream>
#include <cstdlib>
#include <conio.h>
#include <math.h>
using namespace std;

int main()
{
    float num, sq;
    cout<<"Ingrese un numero: ";
    cin>>num;
    sq=sqrt(num);
    cout<<endl<<endl<<"La raiz cuadrada de "<<num<<" es "<<sq<<endl;    
    system("Pause");    
    return 0;           
}
Resultado

jueves, 30 de agosto de 2012

Algoritmo en C:Calcular el perimetro de un cuadrilatero con punteros

Este ejercicio calcula elperimetro de un cuadrilatero indicando sus coordenadas en x y y. Como ven en el codigo utilize la liibreria math.h para las funciones sqrt y pow y utilize punteros para hacer referencias a memoria y asi evitar implementar 4 procedimientos. El codigo lo tiene abajo espero les sirva =D

#include <stdio.h>
#include <conio.h>
#include <math.h>
typedef float Coordenada;
typedef struct{
 Coordenada x;
 Coordenada y;
 } Punto;
Punto p1, p2, p3, p4;
Punto po, pd;
float dist, perimetro;
void Distancia()
{
dist=sqrt(pow(pd.x-po.x,2)+pow(pd.y-po.y,2));
}
void LeerPunto(float *x, float *y,short int n)
{
printf("Coordenada x del punto %d: ", n);
scanf("%f", x);
while(getchar() != '\n');
printf("Coordenada y del punto %d: ", n);
scanf("%f", y);
while(getchar() != '\n');
printf("\n");
}
int main()
{
clrscr();
printf("\n");
printf("****\n");
printf("Calcular el perimetro de un \n");
printf("cuadrilatero irregular");
printf("****\n");
printf("\n");
printf("Introduzca los puntos del cuadrilatero (en orden de adyacencia): \n\n");
LeerPunto(&p1.x, &p1.y, 1);
LeerPunto(&p2.x, &p2.y, 2);
LeerPunto(&p3.x, &p3.y, 3);
LeerPunto(&p4.x, &p4.y, 4);
perimetro=0.0;
po=p1;
pd=p2;
Distancia();
perimetro=dist;
//E1: perimetro=Distancia(p1, p2)
po=p2;
pd=p3;
Distancia();
perimetro=perimetro+dist;
//E2:perimetro=E1 + Distancia(p2,p3)
po=p3;
pd=p4;
Distancia();
perimetro=perimetro+dist;
//E3:perimetro=E2 + Distancia(p3, p4)
po=p4;
pd=p1;
Distancia();
perimetro=perimetro+dist;
//E4:perimetro=E3 + Distancia(p4, p1)
printf("El perimetro del cuadrilatero irregular es: %.2f\n", perimetro);
printf("\nPulse enter para continuar");
getchar();
return 0;
}

miércoles, 29 de agosto de 2012

Algoritmo en C:Comprobar si una fecha es correcta

En este ejemplo ingresaremos el dia, el mes y el año y con switch case analizamos el mes ingresado para validar si el dia es correcto para ese mes ya que algunos meses como Enero, Marzo, Agosto ... son maximo 31 dias y otros meses como Abril, Junio admiten 30 y tenemos el particular caso de febrero 29 en bisiesto y 28 en años no bisiestos. Para el caso de bisiesto cree un procedimiento el cual valida el año y devuelve un valor booleano
#include <stdio.h>
#include <conio.h>
#define Booleano int
#define Verdadero 1
#define Falso 0
unsigned int dia;
unsigned int mes;
long int anio;
Booleano esBisiesto;//indicador de anio bisiesto
Booleano fechaValida;//indicador de fecha valida
void AnioBisiesto()
{
esBisiesto=(anio%4==0)&&(anio%100!=0)||
    (anio%400)&&(anio!=3600);
}
int main()
{
 clrscr();
 printf("\n");
 printf("****\n");
 printf("**** Algoritmo: Comprobar si una fecha es correcta ****\n");
 printf("****\n");
 printf("\n");
 printf("Introduzca el dia: ");
 scanf("%u", &dia);
 while(getchar() != '\n');
 printf("Introduzca el mes: ");
 scanf("%u", &mes);
 while(getchar() != '\n');
 printf("Introduzca el anio: ");
 scanf("%ld",&anio);
 while(getchar() != '\n');
 fechaValida=Verdadero;
 if(dia<1) fechaValida=Falso;
 else
 switch(mes)
 {
 case 1:
 case 3:
 case 5:
 case 7:
 case 8:
 case 10:
 case 12: //meses de 31 dias
      if(dia>31)
      fechaValida=Falso; break;
 case 4:
 case 6:
 case 9:
 case 11://meses de 30 dias
      if(dia>30)
      fechaValida=Falso; break;
 case 2://mes de febrero
      AnioBisiesto();
      if((dia>29)||(!esBisiesto && (dia>28)))
      fechaValida=Falso; break;
 default: fechaValida=Falso; break;
 }
 printf("%u/ %u/ %ld", dia, mes, anio);
 if(fechaValida) printf(" es una fecha valida\n");
 else printf("no es una fecha valida\n");
 printf("\nPulse enter para continuar");
 getchar();
 return 0;
}

Algoritmo en C:Obtener el mayor de 2 numeros

En este ejemplo ingresamos 2 enteros, le damos formato con %d y con if else analizamos los numeros ingresados el cual lo almacenamos en una tercera variable la cual se le muestra al usuario. Aqui tienen el codigo.
#include 
#include 
int x, y;
int mayor;
int main()
{
 clrscr();
 printf("\n");
 printf("****\n");
 printf("**** Algoritmo: Obtener el mayor de 2 enteros ****\n");
 printf("****\n");
 printf("\n");
 printf("Introduzca el primer entero: ");
 scanf("%d", &x);
 while(getchar() != '\n');
 printf("Introduzca el segundo entero: ");
 scanf("%d", &y);
 while(getchar() != '\n');
 if(x>=y) mayor=x;
 else mayor=y;
 printf("El numero mayor es: %d\n", mayor);
 printf("\nPulse enter para continuar");
 getchar();
 return 0;
}

Algoritmo en C:Simulacion de una calculadora simple

En este ejemplo haremos una calculadora simple en C++ utilizando la instruccion switch case para el operador que deseemos ya sea suma,resta,multiplicacion o division. Los numeros que ingresamos seran enteros y les daremos formato con %d el cual lee un entero decimal. El caracter que ingresamos para la operacion(+,-,*,/) le damos formato con %c. Espero les sirva el codigo =)
#include 
#include 
int operando1, operando2;
char operador;
int main()
{
 clrscr();
 printf("\n");
 printf("****\n");
 printf("**** Simulacion de una calculadora simple ****\n");
 printf("****\n");
 printf("\n");
 printf("Introduzca el primer operando: ");
 scanf("%d", &operando1);
 while(getchar() != '\n');
 printf("Introduzca el segundo operando: ");
 scanf("%d", &operando2);
 while(getchar() != '\n');
 printf("Introduzca el operador (+, -, *, /): ");
 scanf("%c", &operador);
 while(getchar() != '\n');
 printf("El resultado es: ");
 switch(operador)
 {
 case '+':printf("%d", operando1+operando2);break;
 case '-':printf("%d", operando1-operando2);break;
 case '*':printf("%d", operando1*operando2);break;
 case '/':printf("%d", operando1/operando2);break;
 default:printf("operador incorrecto");break;
 }
 printf("\n");
 printf("\nPulse enter para continuar");
 getchar();
 return 0;
}

Algoritmo en C:Correspondencia entre calificaciones

En este ejemplo ingresaremos una nota y con una instruccion switch case nos mostrara si esta nota pertenece a una matricula de honor(en este caso solo sera con 20), sobresaliente, notable, aprobado o suspenso.
#include <stdio.h>
#include <conio.h>
int nota;//0..20, nota en la universidad extranjera,0<=nota <=20
int main()
{
 clrscr();
 printf("\n");
 printf("****\n");
 printf("**** Algoritmo: Correspondencia entre calificaciones ****\n");
 printf("****\n");
 printf("\n");
 printf("Introduzca la nota (entre 0 y 20): ");
 scanf("%d", ¬a);
 while(getchar() != '\n');
 printf("La calificacion es: ");
 switch(nota)
 {
 case 20:printf("matricula de honor");break;
 case 19:
 case 18:printf("sobresaliente");break;
 case 17:
 case 16:printf("notable");break;
 case 15:
 case 14:printf("aprobado");break;
 default:if(nota<14)printf("suspenso");break;
 }
 printf("\n");
 printf("\nPulse enter para continuar");
 getchar();
 return 0;

Algoritmo en C:Calcular la nota final de una asignatura


hola aqui les traigo un ejemplo de programacion el cual a partir de 2 notas: una de teoria y una de practica, calcula la nota final por pesos lo probe con notas del a al 10 que es como califican aqui en mi pais, el codigo esta en C++ y utilize el Turbo C++ ya que queria recordar la clasica pantalla color azul =D, les explicare brevemente el codigo para los que recien inician en C++: aqui utilize las librerias stdio.h y conio.h, la libreria stdio.h me permite utilizar la funcion printf y getchar, esta ultima funcion retorna ya sea el caracter ingresado o EOF(), mientras que la libreria conio me permite usar la funcion clrscr() la cual se utiliza para limpiar la pantalla de salida, por ejemplo si ejecutamos un programa, lo modificamos y lo ejecutamos otra vez la salida previa podria seguir en memoria, clrscr() limpia la pantalla previa. Tambien utilize la funcion scanf la cual lee la data ingresada pero dando un formato, dado que ingresamos notas el formato que le daremos sera de tipo float por lo que utilizamos %f. Aqui tienen el codigo espero les sea util =D
#include <stdio.h>
#include <conio.h>
int main()
{
 float notaTeoria;
 float notaPractica;
 float notaFinal;
 clrscr();
 printf("\n");
 printf("****\n");
 printf("**** Algoritmo: Calculo de la nota final de una asignatura ****\n");
 printf("****\n");
 printf("\n");
 printf("Nota de teoria: ");
 scanf("%f", ¬aTeoria);
 while(getchar() != '\n');
 printf("\n");
 printf("Nota de practicas: ");
 scanf("%f", ¬aPractica);
 while(getchar() != '\n');
 printf("\n");
 notaFinal=notaTeoria*0.7+notaPractica*0.3;
 printf("La nota final es: %.2f\n", notaFinal);
 printf("\nPulse enter para continuar");
 getchar();
 return 0;
}

sábado, 9 de junio de 2012

Deshabilitar Puertos USB con C++


En este post voy a mostar como podemos deshabilitar y habilitar puertos USB. Bloqueando el puerto USB nosotros podemos controlar que el usuario extraiga informacion de la PC o no.
Muchas universidades tienen prohibido usar el USB en ciertas PC, asi que tienen que bloquearlo. Con este truco tambien aprenderemos como abrir puertos USB bloqueados.
Este codigo es muy facil simple, una vez que el programa bloquee el puerto USB la PC no reconocera ningun USB insertado, pero podemos revertirlo usando otro codigo de desbloqueo de puertos USB.
Este programa lo probe en mi XP no estoy seguro si funciona en Vista o Windows 7. Tu puedes probar este programa en tu PC, y puedes probar el codigo de desbloqueo tambien.
Logica del programa
La logica del programa es simple. El archivo fuente en 'C' block_usb.c escribe el valor DWORD de 4 (100 en binario) en la configuracion del REGEDIT en KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start" para bloquear los puertos USB.
De forma similar, en el proceso inverso, el archivo fuente en 'C' Unblock_usb.c escribe el valor DWORD a 3 (011 en binario) en la configuracion del Regedit en "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start" para desbloquear los puertos USB.
CODIGO
Para deshabilitar puerto USB
#include
void main()
{
system("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR \/v Start \/t REG_DWORD \/d 4 \/f");
}
Graba este codigo como block_usb.c y abrelo con Turbo C, despues de la compilacion creara un block_usb.exe el cual es un programa simple que deshabilitara (bloqueara) todos los puertos USB de la PC.
Despues de ejecutar block_usb.exe inserta tu USB, la PC no lo detectara. Ahora aqui esta el codigo de desbloqueo.
Para habilitar puertos USB
#include
void main()
{
system("reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\USBSTOR \/v Start \/t REG_DWORD \/d 3 \/f");
}
Guarda este codigo como unblock_usb.c y compilalo con Turbo C para obtener el unblock_usb.exe.
Ejecuta el unblock_usb.exe y ahora la computadora detectara tu USB.

domingo, 25 de diciembre de 2011

Programa para calcular equivalencias en Bytes - Kilobytes - Megabytes - Gigabytes - Terabytes en C

hola, aqui les paso un codigo que encontre navegando por la web, este programa esta en C y como dice en el titulo al ingresar un numero convierte su valor en Kilobytes, Megabytes, Gigabytes y Terabytes.
El codigo de abajo lo ponen dentro del main.
char *unidades[] = {"bytes","kilobytes","megabytes","gigabytes","Terabytes"}; 
// Partimos del supuesto de que lo que nos dan son bytes 
float resultado; 
// Mas abajo van a ver porque float 
printf("Ingresa  una cantidad X de bytes: "); 
scanf("%f" , &resultado); 
printf("Sus equivalencias son:\n"); 
int unidad = 0; //con esta variable hacemos un bucle 
do
{ 
printf("%s: %f\n" , unidades[ unidad ] , resultado); 
resultado /= 1024; //aqui pasamos el valor en bytes a kilo,mega,...
unidad++; 
} 
while ( unidad < 5 ); //aqui recorremos el array hasta el indice 4 
las funciones printfy scanf las he explicado en otros posts que hice sobre C como aqui.

sábado, 5 de noviembre de 2011

Funciones en C

En C, una funcion es equivalente a una subrutina o funcion en Fortran, o un procedimiento en Pascal. Una funcion provee un modo conveniente para encapsular algun calculo, el cual puede ser utilizado sin preocuparse acerca de su implementacion. Con funciones diseñadas apropiadamente, es posible ignorar como un trabajo esta hecho, sabiendo que esta hecho es suficiente. C hace la invocacion de funciones facil y eficiente; a menudo veran una funcion corta definida y callada solo una vez.
Hasta ahora hemos utilizado funciones como printf que han sido proporcionadas por nosotros; ahora es tiempo para hacer una propia. Como C no tiene operador de exponenciacion como el ** de Fortran, vamos a hacer una funcion llamada power(m, n) para elevar un entero m a un entero positivo n. Eso es, el valor de power(2,5) es 32. Esta funcion no es una rutina de exponencacion practica, maneja solo potencias positivas de enteros pequeños, pero es suficiente para este caso.(la libreria estandar contiene una funcion pow(x,y) que calcula xy).
Aqui esta la funcion power y el programa principal para ejecutarlo, asi que aqui puedes ver la estructura completa.
using namespace std;
int power(int m, int n);
int main()
{
    int i;
    for(i=0;i<10;i++)
        printf("%d \t %d \t %d\n",i,power(2,i),power(-3,i));             
    system("Pause");    
    return 0;           
}
int power(int base, int n)
{
    int i, p=1;
    for(i=0; i<=n; i++)
        p=p*base;
    return p/base;     
}
lo que mostrara sera esta tabla
Como vemos, la funcion power es llamada 2 veces por el main en la linea
        printf("%d \t %d \t %d\n",i,power(2,i),power(-3,i));
cada llamada pasa 2 parametros a power, el cual cada vez retorna un entero el cual lo formateamos con %d para ser impreso. En una expresion, power(2,i) es un entero formado de 2 y de i. La primera linea de power:
int power(int m, int n);
declara los tipos de parametros y nombres, y el tipo de resultado que la funcion retorna. Los nombres usados por power para sus parametros son locales para power, y no son visibles para otra funcion: otras rutinas pueden usar los mismos nombres sin conflicto. Esto tambien sucede para las variables i y p: i en power no tiene relacion con el i en el main. El valor que power calcula calcula es returnado al main mediante la declaracion return.
Espero les haya aclarado algunas dudas este pequeño ejemplo :).

viernes, 28 de octubre de 2011

¿Porque 2+2=5928 en C?

este ejemplo lo consegui del libro Practical C Programming y aqui les traigo este curioso ejemplo el cual puede variar dependiendo del compilador que utilicen, yo use el Dev C++ y aunque no me salio 5928 como el libro :( si me salio otro resultado distinto, pueden probar este codigo que ven a continuacion:
using namespace std;
int answer;
int main()
{
    answer=2 + 2;
    printf("The answer is %d\n");
    return 0;           
}
aunque este ejemplo lo pusieron como pregunta prouesta, la explicacion que dieron es que la declaracion printf
printf("The answer is %d\n");
le dice al programa que imprima un un numero decimal, pero como ven la variable answer no esta especificada. C no comprueba si printf recibe el numero correcto de parametros. Y como no hay valor especificado, C crea uno. para que imprima correctamente se debe cambiar asi:
printf("The answer is %d\n");
y tendremos esto:

miércoles, 26 de octubre de 2011

Arrays en C

In constructing our building, we have identified each brick(variable) by name. That process is fine for a small number of brick, but what happens when we want to construct something larger? We would like to point to a stack of bricks and say: "That's for the left wall. That's brick 1,brick 2, brick 3,...".
Arrays allow us to do something similar with variables. An array is a set of consecutive memory locations used to store data. Each item in the array is called an element. The number of elements in an array is called the dimension of the array. A typical array declaration is:
/*List of data to be sorted and averaged.*/
int datalist[3];
The above example declares datalist to be an array of three elements. datalist[0], datalist[1] and datalist[2] are separate variables. To reference an element of an array, you use a number called the index- the number inside the square brackets([]). C is a funny language that likes to start counting. So, our three elements are numbered to 2.
In this example we compute the total and average of five numbers.
using namespace std;
float data[5];/* data to average and total*/
float total;/*the total of the data items*/
float average;/*average of the items*/
int main()
{
    data[0]=34.0;
    data[1]=27.0;
    data[2]=45.0;
    data[3]=82.0;
    data[4]=22.0;
    total=data[0]+data[1]+data[2]+data[3]+data[4];
    average=total/5.0;
    printf("Total %f Average %f \n", total, average);
    return 0;           
}
and the program outputs:

miércoles, 19 de octubre de 2011

Variables and Arithmetic Expressions in C

The next program uses the formula °C=(5/9)(°F-32) to print the folllowing table of Farenheit temperatures and their centigrade or Celsius equivalents:
0 -17
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300 148

The program itself still comnsists of the definition of a single function named main. It is longer than the one that printed "hello world", but not complicated. It introduces several new ideas, including comments, declarations, variables, arithmetic expressions, loops and formatted output.
/*print farenheit-celsius table
for fahr=0,20,....,300*/
using namespace std;
int main()
{
    int fahr, celsius;
    int lower, upper, step;
    lower=0;
    upper=300;
    step=20;
    fahr=lower;
    printf("°C\t°F\n");
    while(fahr<=upper)
    {
        celsius=5*(fahr-32)/9;
        printf("%d\t%d\n",fahr,celsius);
        fahr=fahr+step;              
    }
}
the two lines:
/*print farenheit-celsius table
for fahr=0,20,....,300*/
are a comment,which in this case explains briefly what the program does. Any characters between /* and */ are ignored by the compiler; they may be used freely to make a program easier to understand. Comments may appear anywhere where a blank, tab or newline can. In C, all variables must be declared before they are used, usually at the beginning of the function before any executable statements. A declaration announces the properties of variables; it consists of a name and a list of variables, such as:
int fahr, celsius;
int lower, upper, step;
The type int means that the variables listed are integers; by contrast with float, which means floating point, i.e., numbers that have a fractional part. The range of both int and float depends on the machine you are using; 16-bits ints, which lie between -32768 and +32767, are common, as are 32-bit ints. A float number is typically a 32-bit quantity, with at least six significant digits and magnitude generally between about 10-38and 1038. C provides several other data types besides int and float, including:
char character - a single byte
short short integer
long long integer
double double-precision floating point
The size of these objects is also machine-dependent. There are also arrays, structures and unions of these basic types, pointers to them, and functions that return them. Computation in the temperature conversion program begins with the assignment statements:
lower=0;
upper=300;
step=20;
which set the variables to their initial values. Individual statements are terminated by semicolons. Each line of the tabñe is computed the same way, so we use a loop that repeats one per outputline;this is the purpose of the while loop
while(fahr<=upper)
{
.........
}
The while loop operates as follows: The condition in parentheses is tested. If it is true (fahr is less than or equal to upper), the body of the loop(the three statements enclosed in braces) is executed. Then the condition is re-tested, and if true, the body is executed again. When the test becomes false(fahr exceeds upper) the loop ends, and execution continues at the statement that follows the loop. There are no further statements in this program, so it terminates. The body of a while can be one or more statements enclosed in braces, as in the temperature converter, or a single statement withouth braces, as in
while(i< j)
   i=2*i;
In either case, we will always indent the statements controlled by the while by one tab stop(which we have shown as four spaces)so you can see at a glance which statements are inside the loop. The indentation emphasizes the logical structure of the program. Although C compilers do not care about how a program looks, proper indentation and spacing are critical in making programs easy for people to read. We recommend writing only one statement per line, and using blank around operators to clarify grouping. The position of braces is less important, although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistenly. Most of the work gets done in the body of the loop. The Celsius temperature is computed and assigned to the variable celsius by the statement
celsius=5*(fahr-32)/9
The reason for multiplying by 5 and dividing by 9 instead of just multiplying by 5/9 is that in C, as in many other languages, integer division truncates: any fractional part is discarded. Since 5 and 9 are integers. 5/9 would be truncated to zero and so all the Celsius temperatures would be reported as zero. This example also shows a bit more of how printf works. printf is a general purpose output formatting function.Its first argument is a string of characters to be printed, with each % indicating where one of the other(second,third,....) arguments is to be substituted, and in what form it is to be printed. For instance, %d specifies an integer argument, so the statement:
printf("%d\t%d\n",fahr,celsius);
causes the values of the two integers fahr and celsius to be printed, with a tab(\t) between them. Each % construction in the first argument of printf is paired with the corresponding second argument, third argument, etc.;they must match up properly by number and type, or you will get wrong answers. By the way, printf is not part of the C language; there is no input or output defined in C itself. printf is just a useful from the standar library of functions that are normally accessible to C programs. The behaviour of printf is defined in the ANSI standard, however, so its properties should be the same with any compiler and library that conforms to the standard. There are a couple of problems with the temperature conversion program. The simpler one is that the output isn't very pretty because the numbers are not right-justified. That's easy to fix; if we augment each %d in the printf statement with a width, the numbers printed will be right justified in their fields, For instance, we might say:
printf("%3d %6d\n",fahr,celsius);
to print the first number of each line in a field three digits wide, and the second in a field six digits wide, like this:
The more serious problem is that because we have used integer arithmetic, the Celsius temperatures are not very accurate; for instance, 0°F is actually about -17.8°C, not -17. To get more accurate answers, we should use floating-point arithmetic instead of integer. This requires some changes in the program. Here is the second version:
int main()
{
    int fahr, celsius;
    int lower, upper, step;
    lower=0;
    upper=300;
    step=20;
    fahr=lower;
    printf("°C\t°F\n");
    while(fahr<=upper)
    {
        celsius=5*(fahr-32)/9;
        printf("%3d %6d\n",fahr,celsius);
        fahr=fahr+step;              
    }
}
This is much the same as before, except that fahr and celsius are declared to be float and the formula for conversion is written in a more natural way. We were unable to use 5/9 in the previous versions because integer division would truncate it to zero. A decimal point in a constant indicates that it is floating point, however, so 5.0/9.0 is not truncated because it is the ratio of two floating-point values. If an arithmetic operator has integer operands, an integer operation is performed. If an arithmetic operator has one floating-point operand and one integer operand, however, the integer will be converted to floating point before the operation is done. If we had written(fahr-32), the 32 would be automatically converted to floating point. Nevertheless, writing floating-point constants with explicit decimal points even when they have integral values emphasizes their floating-point nature for human readers. For now, notice that the assignment
fahr=lower;
and the test
while(fahr<=upper)
also work in the natural way the int is converted to float before the operation is done. The printf conversion specification %3.0f says that a floating-point number(here fahr) is to be printed at least three characters wide, with no decimal point and no fraction digits. %6.1f describes another number(celsius) that is to be printed at least six characters wide, with 1 digit after the decimal point. The output looks like this:
With and precision may be omitted from a specification: %6f says that the number is to be at least six characters wide; %.2f specifies two characters after the decimal point, but the width is not constrained; and %f merely says to print the number as floating point:
%d print as decimal integer
%6d print as decimal integer, at least 6 characters wide
%f print as floating point
%6f print as floating point, at least 6 characters wide
%.2f print as floating point, 2 characters after decimal point
%6.2f print as floating point, at least 6 wide and 2 after decimal point
Among others, printf also recognizes %o for octal, %x for hexadecimal, %c for character, %s for character string and %% for itself.

This Sample was taken from The C Programming Language by Brian Kernighan and Dennis Ritchie

viernes, 7 de octubre de 2011

Algoritmo recursivo para convertir numero entero a binario en C

en este codigo vamosa explicar como, mediante recursion, podemos obtener el valor binario de un numero entero, como ven abajo:
para esto vamosa crear una funcion recursiva, la cual mediante divisiones sucesivas va a ir formando el numero binario mientras el cociente sea mayor que 2, caso contrario quiere decir que habremos llegado a 1 o 0 y se puede mostrar el resultado, para esto utilizamos la funcion printf la cual nos pedira ingresar un numero y con scanf salvamos este valor el cual se ingresara a la funcion binario.
using namespace std;
int binario(int p);
int main()
{
    int x;
    printf("Ingrese un numero entero: ");
    scanf("%d",&x);
    printf("su valor del numero en binario es: %d \n",binario(x));
    system("Pause");
    return 0;
}
int binario(int num)
{
    int res;
    if(num<2)
        res=num;
    else
        res=10*binario(num/2)+num%2;
    return res;             
}

viernes, 30 de septiembre de 2011

Algoritmo para invertir palabra en C

hola como estan aqui traigo un codigo el cual pedira que se ingrese una palabra y la invertira para esto utilizaremos la funcion printf y con la funcion scanf especificamos el formato de la variable, en este caso por tratarse de una cadena de caracteres utilizamos %s la cual se usa para string, despues utilizamos la funcion strlen el cual lo almacenamos el una variable la cual la ingresamos en un for y creamos un nuevo array el cual nos devolvera la palabra invertida el programa lucira asi:


using namespace std;
int main()
{
    char input[100];
    printf("ingrese una palabra: \n");
    scanf("%s", &input);
    printf("la longitud es %d \n",strlen(input));
    int len=strlen(input);
    int last=len-1;
    for(int i=0;i< len/2;i++)
    {
       char tmp=input[i];
       input[i]=input[last-i];
       input[last-i]=tmp;     
    }
    printf("la cadena invertida es %s \n",input);          
}

jueves, 29 de septiembre de 2011

Algoritmo recursivo para calcular el n-esimo termino de la serie de Lucas en C

en este programa vamos a calcular la serie de Lucas la cual se debe al matematico frances Edouard Lucas el cual dio a la serie de numeros 0,1,1,2,3,5,8,13,... el nombre de Numeros de Fibonacci, encontro una serie similar que se da al buscar los patrones de los Numeros de Fibonacci. Esta regla consiste en formar el ultimo numero de la serie a partir de sus 2 anteriores, similar a Fibonacci pero en vez de usar 0 y 1, comenzamos con 2 y 1 como se puede ver a continuacion:


2, 1, 3, 4, 7, 11, 18, ...


para encontrar el n-esimo numero de esta serie vamos a hacer un programa el cual nos pida el n esimo numero que queremos encontrar y a partir de ahi utilizamos un algoritmo recursivo el cual ira formando los 2 numeros que deben sumarse para hallar el n esimo termino. Utilizaremos las funciones printf y scanf y para almacenar el valor ingresado como entero utilizaremos el %d:
int lucas(int n);
int main()
{
    int i;
    printf("Algoritmo de Lucas \n");
    printf("Ingrese un numero entero: ");
    scanf("%d", &i);
    printf("El %d-esimo de la serie de Lucas es %d \n",i,lucas(i));
    system("Pause");
    return 0;   
}
int lucas(int n)
{
    int res;
    if(n==1) return 2;
    else if(n==2) return 1;
    else return lucas(n-1)+lucas(n-2);    
}

martes, 27 de septiembre de 2011

Suma de n numeros introducidos por teclado en C

en este pequeño programita vamos a sumar un conjunto de numeros enteros ingresados por teclado los cuales se iran sumando hasta ingresar un numero entero menor a 0 si gustan prueben ingresando decimales y veran la sorpresita que saldra :D, este programa esta para numeros enteros pero puede aceptar decimales definiendo variables tipo double.
int main()
{
    int num=0, suma=0;
    do
    {
        suma=suma+num;
        printf("Ingresa un numero: ");
        scanf("%d",&num);
    }while(num>=0);
    printf("la suma es: %d \n",suma);
    system("Pause");
    return 0;    
}

lunes, 19 de septiembre de 2011

Programa en C:Conversion euros y pesetas con instruccion switch

en este ejemplo se va a ingresar una cantidad y se escogera si queremos convertirla de pesetas a euros o viceversa, para esto utilizaremos la instruccion switch y la directiva #define la cual nos va a servir para definir constantes
#define euro 166.386 
using namespace std;
int main()
{
    float n,x;
    int opcion;
    printf("Ingrese la cantidad: ");
    scanf("%f",&n);
    printf("Elija una opcion \n");
    printf("1-Ptas a Euros 2-Euros a ptas: ");
    scanf("%d",&opcion);
    switch(opcion)
    {
       case 1: x=n/euro;
            printf("%f Pesetas son %f Euros \n",n,x);
            break;
       case 2: x=n*euro;
            printf("%f euros son %f Pesetas \n",n,x);
            break;
       default: printf("incorrecta");                
    }              
    system("Pause");    
    return 0;           
}

Programa en C:instruccion switch

aqui haremos un ejemplo sencillo de como utilizar la instruccion switch en este ejemplo se pedira ingresar una nota con la funcion printf(del 1 al 10 es la calificacion en mi pais :)) y con la funcion scanf capturamos el dato ingresado y reportara el estado en que se encuentra el estudiante como pueden ver en la imagen:
int main()
{
    int nota;
    printf("Inserte una nota: ");
    scanf("%d",¬a);
    switch(nota)
    {
     case 0:    printf("\nSuspenso\n"); break;
     case 1:    printf("\nSuspenso\n"); break;
     case 2:    printf("\nSuspenso\n"); break;
     case 3:    printf("\nSuspenso\n"); break;
     case 4:    printf("\nSuspenso\n"); break;
     case 5:    printf("\nAprobado\n"); break;
     case 6:    printf("\nBien\n"); break;
     case 7:    printf("\nNotable\n"); break;
     case 8:    printf("\nNotable\n"); break;
     case 9:    printf("\nSobresaliente\n"); break;
     case 10:   printf("\nSobresaliente\n"); break;
     default:   printf("\nesa nota es incorrecta\n");
    }           
    system("Pause");    
    return 0;           
}

domingo, 18 de septiembre de 2011

Programa en C:instruccion if-else

en este ejemplo lo que vamos a hacer es mostrar al usuario un menu con opciones y que el al seleccionar una opcion ingresando un caracter muestre la opcion ingresada, en este ejemplo utilizaremos la funcion getchar la cual toma un caracter del teclado
int main()
{
    int c;
    printf(" Menu: \n ");
    printf("A=Agregar a la lista \n");
    printf(" B=Borrar de la lista \n");
    printf(" O=Ordenar la lista \n");
    printf(" I=Imprimir la lista \n");
    printf(" Escriba su seleccion y luego : ");
    if((c=getchar()) != ' ')
    {
        if(c=='A') 
            printf(" Has seleccionado agregar \n");
        else if(c=='B') printf(" Has seleccionado borrar \n");
        else if(c=='O') printf(" Has seleccionado ordenar \n");
        else if(c=='I') printf(" Has seleccionado imprimir \n");             
    }
    else
        printf(" No has seleccionado nada \n");
    system("Pause");    
    return 0;           
}