Listado de planetas del sistema solar y un... ¿Semáforo? - ¡Practicando con AzulSchool! [ESP-ENG] | C++

avatar
(Edited)

¿Cómo va todo? Por acá vuelvo con más C++, aunque esta vez es más un repaso, pues he estado poniéndome al día con un curso de AzulSchool que había dejado en "stand by" y luego en el completo olvido, por causa de otras ocupaciones. Pero, he aprovechado el tiempo disponible para exprimir al máximo la oportunidad. Esto porque quiero ponerme en forma, mejorar en cuanto a estos temas para traer buen contenido y que de verdad pueda ser de ayuda a otros estudiantes y cazadores de conocimiento.

Este curso es gratuito, doy gracias a don Angel Sánchez por tomarse el tiempo de hacerlo y ponerlo al servicio de quien desee seguir creciendo en la programación. Actualmente el registro de cursantes dice que han habido 17909 personas que optaron al contenido. Definitivamente ha sido de bendición para muchos.

El enunciado pide que se cree un programa en C++ que muestre el listado de los planetas del sistema solar y su distancia media al sol (en millones de km), además que pida el número por teclado, asociado al planeta a consultar y muestre el dato en cuestión. En caso de tocar un caracter errado, mostrar error. Además pide otro programa que haga algo similar, en cuanto a listado, pero con los colores del semáforo y su significado. Este ejercicio está orientado al uso de if-else.

Sin embargo, decidí darle un toque más de dificultad, al incluir también el uso del bucle do-while, de la sentecia switch y de funciones extra para evitar las redundancias en cuanto al uso de código. Optimizando un poco y a la vez practicando varios conceptos al mismo tiempo, de modo que el calentamiento sea más exigente.

How is everything going? I'm back with more C++, although this time it's more of a review, because I've been catching up with a AzulWeb course that I had left on "stand by" and then completely forgotten, because of other occupations. But, I have taken advantage of the time available to make the most of the opportunity. This is because I want to get in shape, improve on these topics to bring good content that can really be of help to other students and knowledge hunters.

This course is free, I thank Mr. Angel Sanchez for taking the time to do it and make it available to anyone who wants to continue growing in programming. Currently the register of students says that there have been 17909 people who opted for the content. It has definitely been a blessing for many.

The statement asks to create a C++ program that shows the list of planets in the solar system and their average distance to the sun (in millions of km), and also asks for the number by keyboard, associated to the planet to be consulted and displays the data in question. In case of touching a wrong character, it will show an error. It also asks another program to do something similar, as for listing, but with the colors of the traffic light and its meaning. This exercise is oriented to the use of if-else.

However, I decided to give it a touch more difficulty by also including the use of the do-while loop, the switch statement and extra functions to avoid redundancies in the use of code. Optimizing a bit and at the same time practicing several concepts at the same time, so that the warm-up is more demanding.

Portada.jpg

Edited with CANVA

Programación c++.png

image.png

image.png

Programación c++.png

En las librerías solo me apoyé en "iostream" para entrada y salida y "conio.h" para el uso del getch. Como siempre, estuvo el "using namespace std" para facilitar el uso del cout.

Las funciones show_C y show_D, al inicio, son de hecho bastante similares pues van asociadas a otro menú y fueron creadas con el fin de no redundar en el código referente a lo que se debe mostrar según la opción escogida por el usuario. Así pues, son como plantillas en la que solo cambia la variable "d" y "planet", para la distancia y el nombre del planeta y en el caso del semáforo, las variables "color" y "description", para el color y su descripción. Estas van junto a la función planets() y a la función traffic_l(), respectivamente. Estas dos funciones antes mencionadas también tienen muchas similitudes, pues los dos programas solicitados tienen una naturaleza muy parecida, cuestión bastante entendible si tenemos en cuenta que están hechos con la intención de ejercitar el uso de una herramienta en común.

La función planets cuenta con una variable char para el selector y un bucle do-while para que el usuario pueda seguir haciendo las consultas que desee respecto a cada planeta sin necesidad de abrir y cerrar el programa, entre cada elección. Son 9 casos más el default que corresponde a la ocasión en la que el usuario no toque una tecla asociada a alguno de los casos, en ese momento se muestra un mensaje de error, tal y como lo pide el enunciado. Pienso que en vez de cout, debí haber usado cerr, fue una pequeña novatada de mi parte.

Cada opción (excepto la novena) llama a la función show_D() con los parámetros de la distancia y el nombre del planeta deseado, de tal modo que se muestra la plantilla antes descrita. Esto sucede luego de una previa limpieza de pantalla e incluye pausas para que el usuario pueda leer sin problemas y avanzar conforme lo desee. La novena opción devuelve al usuario al menú principal. El do-while tiene como condición que la opción no sea igual a 9 de tal manera que se repite siempre y cuando el usuario no desee volver al menú principal.

In the libraries I only relied on "iostream" for input and output and "conio.h" for the use of the getch. As always, there was the "using namespace std" to facilitate the use of cout.

The functions show_C and show_D, at the beginning, are in fact quite similar because they are associated with another menu and were created in order not to redundant in the code regarding what should be displayed according to the option chosen by the user. So, they are like templates in which only change the variables "d" and "planet", for the distance and the name of the planet and in the case of the traffic light, the variables "color" and "description", for the color and its description. These go together with the planets() function and the traffic_l() function, respectively. These two aforementioned functions also have many similarities, since the two programs requested have a very similar nature, quite understandable if we take into account that they are made with the intention of exercising the use of a common tool.

The planets function has a char variable for the selector and a do-while loop so that the user can continue making the desired queries for each planet without having to open and close the program between each choice. There are 9 cases plus the default that corresponds to the occasion in which the user does not touch a key associated to one of the cases, at that moment an error message is shown, as requested by the statement. I think that instead of cout, I should have used cerr, it was a little hazing on my part.

Each option (except the ninth) calls the show_D() function with the parameters of the distance and the name of the desired planet, so that the template described above is displayed. This happens after a previous screen cleanup and includes pauses so that the user can read smoothly and advance as desired. The ninth option returns the user to the main menu. The do-while has as a condition that the option is not equal to 9 so that it is repeated as long as the user does not want to return to the main menu.

Programación c++.png

image.png

image.png

image.png

image.png

image.png

Programación c++.png

Para el caso del semáforo, la dinámica no varía mucho respecto al menú de los planetas, solo que al ser tres colores a mostrar, la cantidad de opciones es evidentemente menor. Existen países en los que los colores varían o incluso hay más, pero el enunciado pidió los tres colores que en general, son los más conocidos.

En el main coloqué el menú principal, el que le da la bienvenida al usuario y le permite seleccionar cual de las dos funcionalidades quiere usar. Aunque el enunciado solicita que sean dos programas por separado, decidí unificarlos y así hacer un post un poco más nutrido y hacer la práctica un poco más desafiante.

In the case of the traffic light, the dynamics does not vary much with respect to the menu of the planets, only that since there are three colors to be shown, the number of options is evidently smaller. There are countries in which the colors vary or there are even more, but the statement asked for the three colors that in general, are the most known.

In the main I placed the main menu, the one that welcomes the user and allows him to select which of the two functionalities he wants to use. Although the statement asks for two separate programs, I decided to unify them and thus make a post a little more nourished and make the practice a little more challenging.

Programación c++.png

image.png

image.png

image.png

image.png

Programación c++.png

azulschoolrepaso.gif

Programación c++.png

¡Y bueno... Eso es todo por hoy! La idea es ser diligente y terminar este curso pronto. Hay varios enunciados para proyectos interesantes a los que les veo potencial de hacer un poco más complicados y traerlos por acá explicados, dejando claro los créditos a la página original AzulSchool.

El proyecto "El Almacén de Gab" sigue en proceso, pronto estaré trayendo buenas nuevas al respecto, si tienes consejos, recomendaciones, correcciones o en general algún aporte, no dudes en dejarlo en los comentarios, bendiciones.

And well... That's all for today! The idea is to be diligent and finish this course soon. There are several statements for interesting projects that I see potential to make a little more complicated and bring them here explained, making clear the credits to the original AzulSchool.

The project "Gab's Warehouse" is still in process, soon I will be bringing good news about it, if you have tips, recommendations, corrections or in general any contribution, feel free to leave it in the comments, blessings.

Programación c++.png

Puedes encontrar el curso gratuito en el que aparece el enunciado original en AzulSchool. En el módulo de la sentencia IF-ELSE

You can find the free course in which the original statement appears at AzulSchool. In the module of the IF-ELSE statement


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
11 comments
avatar

Siempre he tenido problemas con conio.h porque como suelo programar en linux, esa es una librería qué no esta dentro del C++ de linux (el compilador gcc) cuando estaba en ma universidad como me dio dolores de cabeza.

Tu programa esta muy interesante y más como lo fuiste desarrollando, aunque siento que parece que le falta algo de orden, sobre todo para que no quede como puro script.

Sigue practicando, eres muy bueno

0
0
0.000
avatar

Gracias don @shadowmyst, con lo de orden te refieres a la forma de plasmar las funciones? He visto que algunos las definen y luego las colocan después del main y así las cosas se ven como más ordenadas, aunque todavía no logro agarrar la costumbre

0
0
0.000
avatar

Exacto, siempre todo lo declarativo en la parte de arriba tanto variables como funciones y luego ya todo el desarrollo abajo

0
0
0.000
avatar

Sí, debo mejorar en ese sentido, ya es por mala costumbre que no lo adopto

0
0
0.000
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000