Invertir arreglo en ANSI C https://parzibyte.me/blog/2019/07/23/invertir-arreglo-ansi-c/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Invertir un arreglo en C (ANSI C) | |
https://parzibyte.me/blog | |
*/ | |
#include <stdio.h> | |
int main(void) { | |
int numeros[] = {50, 44, 152, 12, 33}; | |
// Necesitamos la longitud únicamente para hacer | |
// el ciclo. Si ya la conoces desde antes, ponla aquí | |
// directamente. Más info: | |
// https://parzibyte.me/blog/2018/09/21/longitud-de-un-arreglo-en-c/ | |
int longitud = sizeof(numeros) / sizeof(numeros[0]); | |
printf("Imprimiendo arreglo ANTES de invertir\n"); | |
for (int i = 0; i < longitud; i++) { | |
printf("%d,", numeros[i]); | |
} | |
// Para invertir recorremos hasta la mitad del arreglo | |
int temporal; | |
for (int x = 0; x < longitud / 2; x++) { | |
// Guardamos el valor de números en x | |
temporal = numeros[x]; | |
// A números en x le asignamos lo que haya en la | |
// otra mitad, restando 1 porque recuerda que los índices | |
// comienzan en 0 | |
numeros[x] = numeros[longitud - x - 1]; | |
// Y a números en longitud - x - 1 le ponemos el temporal | |
numeros[longitud - x - 1] = temporal; | |
} | |
printf("\nImprimiendo arreglo DESPUÉS de invertir\n"); | |
for (int i = 0; i < longitud; i++) { | |
printf("%d,", numeros[i]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment