You are on page 1of 16

Programación en C Page 1 of 16

Programa que convierte de metros a pies y pulgadas.


#include stdio.h

main(){
float metros,resul,pulg;
int resul2,pulg2;
clrscr();

printf("\nValor en metros: ");


scanf("%f",&metros);
resul=metros*(1/.3048);
resul2=resul;
pulg=resul-resul2;
pulg=pulg*12;
pulg2=pulg;
printf("El resultado es: %d pies %d pulgadas",resul2,pulg2);

getch();
}

Volver

Programa que realiza las cuatro operaciones aritméticas fundamentales (+,-,*,/).


#include stdio.h
#include conio.h

void main(){
int prim,seg,resul;
char oper;

clrscr();

printf("\nPrimer numero: ");


scanf("%d",&prim);
printf("\nOperacion a realizar (+,-,*,/): ");
oper=getche();
printf("\nSegundo numero: ");
scanf("%d",&seg);

if(oper=='+')
resul=prim+seg;
if(oper=='-')
resul=prim-seg;
if(oper=='*')
resul=prim*seg;
if(oper=='/')
resul=prim/seg;

printf("\nEl resultado de la operacion %d %c %d es %d",prim,oper,seg,resul);


getch();
}

Volver

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 2 of 16

Programa que lee los tres lados de un triángulo y detecta el tipo.


#include stdio.h

main(){

float uno,dos,tres;
clrscr();

printf("\nValor del primer lado: ");


scanf("%f",&uno);

printf("\nValor del segundo lado: ");


scanf("%f",&dos);

printf("\nValor del tercer lado: ");


scanf("%f",&tres);

if((uno==dos) && (dos==tres) && (uno==tres))


printf("\nEl triangulo es equilatero");

else if((uno!=dos) && (dos!=tres) && (uno!=tres))


printf("\nEl triangulo es escaleno");

else
printf("\nEl triangulo es isoceles");

getch();
}

Volver

Programa que lee las edades de un grupo de alumnos y encuentra el promedio.


#include stdio.h

main(){
int alumnos,edad,counter=1;
float promedio,sumaedad=0;
clrscr();

printf("\nNumero de alumnos: ");


scanf("%d",&alumnos);

while(1){

printf("\nEdad alumno %d: ",counter);


scanf("%d",&edad);

sumaedad=sumaedad+edad;
if(counter==alumnos){
break;
}
counter++;
}
promedio=sumaedad/counter;

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 3 of 16

printf("\nLa edad promedio de %d alumno(s) es %.1f años",counter,promedio);

getch();
}

Volver

Función que lee calificaciones (0-10) de alumnos y cuente el número de alumnos


reprobados, (calif<7) de un conjunto de notas. La función recibe como parámetro el
número de notas a leer y deberá regresar el número de alumnos reprobados. Crear
un programa que llame a la función anterior y que despliegue el número de alumnos
reprobados.
#include stdio.h

int numreprob(int not);

void main(void){
int notas,reprobados;
clrscr();

printf("\nNumero de notas a leer: ");


scanf("%d",& notas);
reprobados=numreprob(notas);
printf("\nExiste un total de %d alumnos reprobados",reprobados);
getch();
}

int numreprob(int not){

int c=1,calif,rep=0;

while(c<=not){

printf("\nCalificacion de la nota %d: ",c);


scanf("%d",&calif);

if(calif<7){
rep++;}

c++;
}
return(rep);
}

Volver

Función que lee las matrículas (números enteros) y las calificaciones (tipo char) de
los alumnos de un grupo y las almacene en dos arreglos unidimensionales. La
función deberá leer los datos hasta que se de una matrícula cero la cual indica el fin
de captura. La función regresa el número de alumnos por el mecanismo de return.
Después debe de imprimir el contenido de los arreglos.

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 4 of 16

#include stdio.h

void despliega(int *mats,char *califs,int numcap);


int leedato(int *mats,char *califs,int maximo);

void main(void){
int max=30,matr[29],numalumn;
char calif[29];

clrscr();

numalumn=leedato(matr,calif,max);
printf("\nEl numero de alumnos capturados es %d",numalumn);
despliega(matr,calif,numalumn);

}
int leedato(int *mats,char *califs,int maximo){

int n=0;

printf("\n *** Introduce la matricula y su calificacion. ***");


printf("\n *** Para terminar dale un cero a la matricula. ***");

while(1){

if(n>=maximo){
printf("\nEl arreglo se encuentra lleno");
getch();
break;
}
printf("\n\nMatricula del alumno %d: ",n+1);
scanf("%d",mats);

if(*mats==0){
break;
}
printf("\nCalificacion del alumno %d: ",n+1);
scanf("%d",califs);

mats++;
califs++;
n++;
}
return n;
}

void despliega(int *mats,char *califs,int numcap){

int i=1;

while(1){

if(i>numcap){
break;
}
printf("\nLa calificacion del alumno %d es %d",*mats,*califs);
i++;
mats++;
califs++;
}
getch();
}

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 5 of 16

Volver

Programa que despliega una tabla de conversión de ºC a ºF y viceversa. El programa


debe tener una función que pregunte el tipo de conversión deseada. El usuario
tecleará "c" o "C" si la conversión va a ser de ºC a ºF y "f" o "F" si la conversión es
de ºF a ºC, regresando el caracter leído por medio de return. Otra función
preguntará el rango de valores de la tabla y el incremento, recibiendo como
parámetros las direcciones de las variables donde se almacenarán esos datos. Otras
dos funciones serán para desplegar cada tipo de tabla de conversión.
#include stdio.h
#include ctype.h

void despliegaFC(int *ran1,int *ran2,int *inc);


void despliegaCF(int *ran1,int *ran2,int *inc);
void leeDatos(int *ran1,int *ran2,int *inc);
char tipoConv(void);

void main(void){

int rango1,rango2,incremento;
char tipo;
clrscr();
tipo=tipoConv();
leeDatos(&rango1,&rango2,&incremento);

if(tipo=='C'){
despliegaCF(&rango1,&rango2,&incremento);
}
else{
despliegaFC(&rango1,&rango2,&incremento);
}
}
char tipoConv(void){
char caract;

printf(" TABLA DE CONVERSION DE GRADOS CENTIGRADOS A GRADOS FARENHEIT");


printf("\n Y DE GRADOS FARENHEIT A GRADOS CENTIGRADOS");
printf("\n\nPara convertir de Centigrados a Farenheit oprime 'C'");
printf("\npara convertir de Farenheit a Centigrados oprime 'F'");

printf("\n\nTipo de Conversion (C o F): ");


caract=toupper(getch());

return caract;
}

void leeDatos(int *ran1,int *ran2,int *inc){

printf("\n\nValor inicial de la tabla: ");


scanf("%d",ran1);
printf("\nValor final de la tabla: ");
scanf("%d",ran2);

printf("\n\nIncremento de los valores de la tabla: ");


scanf("%d",inc);

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 6 of 16

void despliegaCF(int *ran1,int *ran2,int *inc){

int suma=*ran1,incremento=*inc,rango2=*ran2;
float conversion;

while(suma<=rango2){

conversion=(((suma)*9)/5)+32;
printf("\n%d §C ----------------------------- %.1f §F",suma,conversion);

suma=suma+incremento;
}
getch();
}

void despliegaFC(int *ran1,int *ran2,int *inc){

int suma=*ran1,incremento=*inc,rango2=*ran2;
int conversion;

while(suma<=rango2){

conversion=((suma-32)*5)/9;
printf("\n%d §F ----------------------------- %d §C",suma,conversion);

suma=suma+incremento;
}
getch();
}

Volver

Ejemplos de cadenas. Función que realiza la misma operación que la función atoi,
que convierte una cadena en un entero. La función regresa el entero representado
por la cadena s si se pudo convertir, en caso contrario regresa 0. Si la función
encuentra caracteres espacio o tabulación, los salta. Si al empezar la secuencia de
dígitos, ésta se interrumpe, el programa termina.
#include stdio.h
#include ctype.h

int myatoi(char *s);

void main(void){

int n;
char cad[50];
clrscr();

printf("Introduce la cadena: ");


gets(cad);
n=myatoi(cad);
printf("\nEl entero extraido de la cadena fue %d",n);
getch();
}

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 7 of 16

int myatoi(char *s){


int signo=1,num=0;

while(1){
if(*s==' ' || *s=='\t'){
s++;
}
else break;
}
if(*s=='+'){
s++;
}
else if(*s=='-'){
signo=-1;
s++;
}
while(1){
if(*s=='\0' || !isdigit(*s)){
break;
}
num=10*num+(*s-'0');
s++;
}
return signo*num;
}

Volver

Ejemplos de cadenas. Función que realiza la misma operación que la función strlen.
Calcula la longitud de la cadena S. Regresa el número de caracteres en S sin contar
el caracter de fin de cadena.
#include stdio.h
#include ctype.h

int mystrlen(char *s);

void main(void){

int n;
char cad[50];
clrscr();

printf("Introduce la cadena: ");


gets(cad);
n=mystrlen(cad);
printf("\nEl numero de caracteres de la cadena s fue %d",n);
getch();
}

int mystrlen(char *s){

int c=0;

while(1){
if(*s=='\0'){
break;
}

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 8 of 16

c++;
s++;
}
return c;
}

Volver

Función que lee una serie de números de la línea de comandos y ejecuta la


instrucción proporcionada después del último número de la serie. Si la instrucción es
GUARDA, los números son guardados en un arreglo de tipo entero. Si la instrucción
es LISTA, los numeros son desplegados como cadenas.
#include stdio.h
#include ctype.h
#include string.h
#include stdlib.h

void main(int np, char *ps[]){


int arreglo[100],j,i;
clrscr();

if(strcmp(ps[np-1],"GUARDA")==0){
for(i=0,j=1;j<(np-1);i++,j++){
arreglo[i]=atoi(ps[j]);
printf("\n%d",arreglo[i]);
}
}

if(strcmp(ps[np-1],"LISTA")==0){
for(i=1;i<(np-1);i++){
puts(ps[i]);
}
}

Volver

Programa que recibe en la línea de comando un número flotante, un caracter que


represente una de las cuatro operaciones fundamentales y un segundo número. El
programa deberá desplegar el resultado de la operación deseada.
#include stdio.h
#include stdlib.h
#include string.h

void main(int narg,char *sarg[]){


float op1,op2,resul;
int i=1;
clrscr();

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 9 of 16

printf("PROGRAMA QUE CALCULA UNA OPERACION ARITMETICA SIMPLE ENTRE DOS OPERANDOS");
printf("\n\nLa sintaxis es: Calcula operando operador operando");
printf("\n");
while(i<=narg){
printf("%s",sarg[i]);
i++;
}

op1=atof(sarg[1]);
op2=atof(sarg[3]);

if(strcmp(sarg[2],"+")==0)
resul=op1+op2;
else if(sarg[2][0]=='-')
resul=op1-op2;
else if(strcmp(sarg[2],"*")==0)
resul=op1*op2;
else if(sarg[2][0]=='/')
resul=op1/op2;
else{
printf("\nOperador invalido: '%s'",sarg[2]);
return;
}
printf("\n\nEl resultado es %.1f",resul);
getch();

Volver

Editor de textos con arreglo de cadenas.


#include string.h
#include stdio.h
#include ctype.h

void inserta(char t[][50],int *ll,int act,int max);


void modif_actual(int *act,int ll);
void reemplaza_linea(char t[][50],int ll,int *act);
void lista(char t[][50],int *ll);
void agrega_linea(char t[][50],int *ll,int max,int *act);

void main(void){

char txt[30][50],opcion;
int llenas=0,max=30,actual;

while(1){
clrscr();
printf(" EDITOR DE TEXTO");
printf("\n SELECCIONA LA PRIMERA LETRA DE LA OPCION DESEADA");
printf("\n\nAgregar Salir Lista Reemplaza Inserta Opcion: ");

opcion=toupper(getch());
if(opcion=='S')
break;
if(opcion=='A')
agrega_linea(txt,&llenas,max,&actual);
if(opcion=='L')

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 10 of 16

lista(txt,&llenas);
if(opcion=='R')
reemplaza_linea(txt,llenas,&actual);
if(opcion=='I')
inserta(txt,&llenas,actual,max);
}
}

/**************************************************************************/
void agrega_linea(char t[][50],int *ll,int max,int *act){
if(*ll==max){
printf("\n\nMemoria insuficiente...");
return;
}
printf("\n\n>");
fflush(stdin);
gets(t[*ll]);
*ll=*ll+1;
*act=*ll;
}

/**************************************************************************/

void lista(char t[][50],int *ll){

int i=0;
printf("\n\n");

while(i<*ll){

puts(t[i]);
i++;
}
getch();
}

/**************************************************************************/

void modif_actual(int *act,int ll){


int v;

printf("\n\nIndica el numero de la linea a posicionar: ");


scanf("%d",&v);

if(v<=ll && v!=0){


*act=v;
}
else{
*act=-1;
}
}

/**************************************************************************/

void reemplaza_linea(char t[][50],int ll,int *act){

if(ll==0){
printf("\n\nNo existe informacion a reemplazar");
getch();
return;
}
modif_actual(act,ll);
if(*act==-1){

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 11 of 16

printf("\n\nLa linea seleccionada no existe...");


getch();
}

else{

printf("\n\nIntroduce la nueva linea: ");


fflush(stdin);
gets(t[*act-1]);
}
}

/*************************************************************************/

void inserta(char t[][50],int *ll,int act,int max){


int j;
if(*ll==max){
printf("\n\nMemoria insuficiente...");
getch();
return;
}
modif_actual(&act,*ll);

if(act==-1){
printf("\n\nLa linea seleccionada no existe...");
getch();
}
else{

j=*ll-1;

while(j>=act-1){
strcpy(t[j+1],t[j]);
j--;
}
printf("\n\nInserta la nueva linea: ");
fflush(stdin);
gets(t[act-1]);
(*ll)++;
}
}

Volver

Directorio telefónico con manejo de archivos.

#include stdio.h
#include conio.h
#include ctype.h
#include string.h
#include stdlib.h

struct DIREC{
char nombre[35];
char tele[20];
} ;

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 12 of 16

FILE *pack(FILE *a);


void ordena(FILE *a);
void consulta2(FILE *a);
long busca_Clave2(FILE *a,char buscado[]);
void lee(FILE *a);
void imprime(FILE *a);

void main(){

char opcion;
FILE *archivo;
archivo=fopen("TELE.DAT","rb+"); /* usar opción "wb+" para crear el archivo .DAT y despu

while(1){
clrscr();
textattr(6+5*5);
clrscr();
textcolor(YELLOW);
cprintf(" DIRECTORIO TELEFONICO");
printf("\n\n");
cprintf(" N");
printf("uevo");
textcolor(YELLOW);
cprintf(" L");
printf("ista");
textcolor(YELLOW);
cprintf(" B");
printf("aja");
textcolor(YELLOW);
cprintf(" C");
printf("onsulta");
textcolor(YELLOW);
cprintf(" O");
printf("rdena");
textcolor(YELLOW);
cprintf(" S");
printf("alir");

gotoxy(1,25);
printf(" *** PRESIONE LA LETRA RESALTADA PARA ESCOGER LA OPCION ***");
gotoxy(1,4);
opcion=toupper(getch());

if(opcion=='S')
break;
switch(opcion){
case 'N':{
lee(archivo);
break;
}
case 'L':{
imprime(archivo);
break;
}
case 'B':{
pack(archivo);
break;
}
case 'C':{
consulta2(archivo);
break;
}
case 'O':{

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 13 of 16

ordena(archivo);
break;
}
}
}
clrscr();
fclose(archivo);
normvideo();
clrscr();
}

/*********************************************************************/

void imprime(FILE *a){


int r,y=0,c=1;
struct DIREC reactivo;
clrscr();
textcolor(YELLOW);
cprintf("NOMBRE TELEFONO");
normvideo();
rewind(a);
while(1){
r=fread(&reactivo,sizeof(struct DIREC),1,a);
if(r==0)
break;

if((c%2)!=0){
textattr(6+5*5);
/* textcolor(LIGHTGRAY);*/
printf("\n");
cprintf("%d.- %-30s %16s",c,reactivo.nombre,reactivo.tele);
normvideo();
}
else{
textattr(6+5*4);
/* textcolor(WHITE);*/
printf("\n");
cprintf("%d.- %-30s %16s",c,reactivo.nombre,reactivo.tele);
normvideo();
}

if(y==23){
getch();
y=0;
}
y++;
c++;
}
getch();
}

/*********************************************************************/

void lee(FILE *a){


struct DIREC reactivo;
printf("\n\n");

fflush(stdin);
printf("Nombre : ");strupr(gets(reactivo.nombre));
if(strlen(reactivo.nombre)<30){

if(busca_Clave2(a,reactivo.nombre)==0){

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 14 of 16

printf("Tel‚fono : ");gets(reactivo.tele);
fseek(a,0,SEEK_END);
fwrite(&reactivo,sizeof(struct DIREC),1,a);
}
else{
printf("\n\nYa existen esos datos!!!");
getch();
}
}
else{
printf("\n\nM ximo 25 letras por nombre...");
printf("\n\nEl programa puede da¤arse si repite este error!!!");
getch();
}
}

/*********************************************************************/

long busca_Clave2(FILE *a,char buscado[]){


long p;
struct DIREC r;
rewind(a);
while(1){
if(fread(&r,sizeof(struct DIREC),1,a)==0)
break;
if(strcmp(r.nombre,buscado)==0){
p=ftell(a)/sizeof(struct DIREC);
return(p);
}
}
return 0;
}

/*********************************************************************/

void consulta2(FILE *a){


char nombre[30];
long p;
struct DIREC r;
printf("\n\nDame el nombre a buscar: ");
strupr(gets(nombre));

p=busca_Clave2(a,nombre);

if(p!=0){

fseek(a,(p-1)*sizeof(struct DIREC),SEEK_SET);
fread(&r,sizeof(struct DIREC),1,a);
printf("\n\n\n");
textcolor(LIGHTGRAY);
cprintf("NOMBRE TELEFONO");
normvideo();
printf("\n%-20s %30s",r.nombre,r.tele);
getch();

}
else{
printf("\n\nLa informaci¢n solicitada no existe ...");
getch();
}
}

/*********************************************************************/

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 15 of 16

void ordena(FILE *a){


int i=0,j=0,s,t;
struct DIREC r;
struct DIREC temp[100];
struct DIREC temporal;
while(1){
fseek(a,i*sizeof(struct DIREC),SEEK_SET);
if(fread(&r,sizeof(struct DIREC),1,a)==0)
break;
temp[j]=r;
i++;
j++;
}
for(s=0;s0){
temporal=temp[s];
temp[s]=temp[t];
temp[t]=temporal;
}

s=0;
i=0;
while(1){
if(s>=j)
break;
r=temp[s];
fseek(a,i*sizeof(struct DIREC),SEEK_SET);
fwrite(&r,sizeof(struct DIREC),1,a);
s++;
i++;
}
printf("\n\nSus archivos han sido ordenados alfab‚ticamente...");
getch();

/*********************************************************************/

FILE *pack(FILE *a){


int i=0;
long p;
char clave[30];
struct DIREC r;
FILE *t;
t=fopen("TMP.DAT","wb");

printf("\n\nDame el nombre a dar de baja: ");


strupr(gets(clave));
p=busca_Clave2(a,clave);

if(p!=0){
while(1){
fseek(a,i*sizeof(struct DIREC),SEEK_SET);
if(fread(&r,sizeof(struct DIREC),1,a)==0)
break;
if(strcmp(r.nombre,clave)!=0){
fseek(a,i*sizeof(struct DIREC),SEEK_SET);
fwrite(&r,sizeof(struct DIREC),1,t);
}
i++;
}
fclose(t);

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com
Programación en C Page 16 of 16

fclose(a);
remove("TELE.DAT");
rename("TMP.DAT","TELE.DAT");
t=fopen("TELE.DAT","rb+");
printf("\n\nLa informaci¢n solicitada ha sido dada de baja...");
getch();
return(t);
}
else{
printf("\n\nNo existe el nombre...");
getch();
}
return 0;
}

/*********************************************************************/

http://www.geocities.com/SiliconValley/8195/cprog.html 6/2/04
PDF created with pdfFactory trial version www.pdffactory.com

You might also like