Posts Tagged ‘ C ’

Bubble sort en C (arreglos de tamaño fijo)

// BUBBLE SORT
#include

int main(void){
int i, j, largo=100;
int arreglo[largo];

void bubble_sort_az (int arreglo[], int largo){
int i, j, aux;
for ( i = 0 ; i < largo-1 ; i++ ) {
for ( j = 0 ; j arreglo[j+1] ) {
aux = arreglo[j];
arreglo[j] = arreglo[j+1];
arreglo[j+1] = aux;
}
}
}
}

void bubble_sort_za (int arreglo[], int largo){
int i, j, aux;
for ( i = 0 ; i < largo-1 ; i++ ) {
for ( j = 0 ; j < largo-1 ; j++ ) {
if ( arreglo[j] < arreglo[j+1] ) {
aux = arreglo[j];
arreglo[j] = arreglo[j+1];
arreglo[j+1] = aux;
}
}
}
}

for ( i = 0 , j = largo ; i 0 ; i++ , j-- )
arreglo[i] = j;

for ( i = 0 ; i < largo ; i++ )
printf("%d ",arreglo[i]);

printf("\n");

bubble_sort_az(arreglo, largo);

for ( i = 0 ; i < largo ; i++ )
printf("%d ",arreglo[i]);

printf("\n");

bubble_sort_za(arreglo, largo);

for ( i = 0 ; i < largo ; i++ )
printf("%d ",arreglo[i]);

getchar();getchar();

return 0;
}

Cambiar color de texto en consola (C/C++)

Función que cambia el color del resto de texto que salga a consola (probada en windows):

inline int SetColor(const int foreground, const int background) {

int Color = foreground + (background * 16);
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, Color);

return 0;
}

Ejemplo de uso:

#include
/* include enumeration list & function */

int main() {

printf("Text is grey by default\n");
SetColor(BLACK, WHITE);
printf("This text is white now!\n");
SetColor(BLACK, WHITE);
printf("Now it's black...\n");

SetColor(GREY, WHITE);
printf("Now it's back to normal! :(\n");

cin.get();
return 0;
}

Limpiar consola usando la API (C/C++)

Función (en C) que limpia la consola (API) (probada en Windows)
Vendría siendo equivalente a usar:

System("CLS");

Función:

int ClrScrn(void)
{
// Top left corner coordinates
COORD coord = {0};

// Contains information about screen buffer
CONSOLE_SCREEN_BUFFER_INFO cBufferInfo;

// Characters written in buffer
DWORD dwI;

// Characters to clear ("area" of console, so to speak)
DWORD dwSize;

// Handle to console
HANDLE hI = GetStdHandle(STD_OUTPUT_HANDLE);

// Just a bit error handling
if(hI == INVALID_HANDLE_VALUE) return (EXIT_FAILURE);

// GetConsoleScreenBufferInfo returns 0 on error
if (GetConsoleScreenBufferInfo(hI, &cBufferInfo))
{
// Calculate characters to clear
dwSize = cBufferInfo.dwSize.X * cBufferInfo.dwSize.Y;

// Write space characters to buffer as many times as needed, i.e. dwSize
FillConsoleOutputCharacter(hI, TEXT(' '), dwSize, coord, &dwI );

// Set console cursor to top left coord
SetConsoleCursorPosition(hI, coord);

return (EXIT_SUCCESS);

} else
return (EXIT_FAILURE);
}