APUNTES DE C++
Estructura básicas:
#include <iostream>: biblioteca estándar de C++ (iostream), que proporciona las
funciones de entrada y salida estándar (por ejemplo, std::cout para la salida y
std::cin para la entrada).
int main() { ... }: Esta es la función principal del programa. indica que main devuelve
un valor entero. {} encierra el cuerpo de la función, donde se colocan las
instrucciones que el programa ejecutará.
cout << "Hola, mundo!" << std::endl;: es el objeto estándar de salida. << se utiliza
para enviar datos al flujo de salida. std::endl es un manipulador de flujo que
representa un salto de línea, similar a \n.
return 0;: Esto indica que la función main ha terminado con éxito y devuelve el valor
0 al sistema operativo.
Más comandos:
cin: es un objeto de flujo de entrada estándar en C++, que se utiliza para leer datos
desde la entrada estándar. Se utiliza junto con(cin >> dato;) >> para leer valores de
diferentes tipos de datos desde la entrada estándar y almacenarlos en variables.
int representa números enteros sin parte fraccionaria.
double representa números en punto flotante, lo que significa que pueden contener
una parte fraccionaria y un exponente.
bool para representar valores de verdad o booleanos. Toma uno de dos valores: true
(verdadero) o false (falso).Es útil para representar condiciones lógicas.
APUNTES DE C++
char : para representar caracteres individuales. Un char puede almacenar un solo
carácter, como una letra, un dígito o un símbolo. (Ej. char letra = 'A';)
OPERADORES:
aritméticos:
● + Suma
● - Resta
● * Multiplicación
● / División
● % Módulo (resto de la división entera)
de asignación:
● = Asignación
● += Asignación con suma
● -= Asignación con resta
● *= Asignación con multiplicación
● /= Asignación con división
● %= Asignación con módulo
de incremento/decremento:
● ++ Incremento
● -- Decremento
relacionales:
● == Igualdad
● != Desigualdad
● < Menor que
● > Mayor que
● <= Menor o igual que
● >= Mayor o igual que
lógicos:
● && → AND lógico
● || → OR lógico
● ! → NOT lógico
Entrada/salida: >>, <<
APUNTES DE C++
ESTRUCTURAS DE CONTROL:
Sentencia de selección: Condicionales
if: Permite ejecutar un bloque de código si se cumple una condición
Else if: Permite evaluar múltiples condiciones después de una primera condición.
Sentencia de Iteración: para repetir una acción x veces
for: Ejecuta un bloque de código un número específico de veces. (cuando se
conoce el número de vueltas exactas que queremos utilizar)
APUNTES DE C++
while: Ejecuta un bloque de código mientras se cumpla una condición.(condición
antes de ejecutar el cuerpo)
do-while: Similar a while, pero garantiza que el bloque de código se ejecute al
menos una vez antes de verificar la condición.(se planta la condición al final)
Anotaciones:
So before you understand loops in C++ you have to understand the algorithme behind it since you can use them
in all programming languages and the syntax is not really the more importznt part of it
For loop:
I think its easier to explain in python even if you never did python before Imagine you want the screen to write "hi"
5 times nstead of coding
"Print("hi") Print("hi" Print("hi") Print("hi") Print("hi")"
You'll use a for loop, its like when you factorize a mathematical expression
You'll, literally, tell the computer "hey i want you to print hi 5 times" But what is "5 times" ?
The computer wouldnt understand that so you give him a list made with 5 items, and you ask him For each item
in this list, you should print hi Print hi as many times as there are items in the list. In python it's smth like
For i in range(0, 5): Print("hi")
i is like an index or a counter. You use for loops also to iterate over a list
Like when I have a bag filled with books and I want the computer to print me the titles of these books. It will smth
like, For each book in the bag: Print title of the book
While loop:
It's exactly the same as for loop but this time the counter or the index is increasing (sometimes decreasing)
Sigma in math will help understand these loops more
APUNTES DE C++
For example: I want the computer to print me the titles for the book in the bag, as long as the bag is not empty,
cuz ofc he wouldn't find a book then. So the while loop becomes:
While the number of books in the bag is not 0, here is what you should do:
Print the title
And decrease the number of books by one cuz you already printed its title
But the index is not always increasing or decreasing
It's just a simple example
The computer just keeps doing a task as long as a condition is satisfied
In our case it's that the number of books in the bags ( from the pov of the computer) is not zero
Here:
For (int i = 0; i < 5; i++)
It means
For every integer between 0 and strictly inferior to 5
Which means each iteration, each time i want the i to take the value in that range
The i++ is the step, each time the i increases by one
So in the 1st iteration i will be 1
Second 2
Third 3 etc
Then what's inside the loop is what i want the computer to do each time
Same with the while, You initialize your counter. And inside each iteration you modify it ( in the case you add one
to it) until it no longer satisfies the condition
While, for, and do while are inherently the same, they express the same idea, so not really you only use what
seems the easier to implement in your case.
¿Cuando usar while y cuando uso do while?
APUNTES DE C++