C++ Code Examples: Basic Operations
Posted on Feb 7, 2025 in Spanish
C++ Code Examples
Generating Random Numbers
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int num, c, aleatorio;
srand(time(NULL));
for (c = 1; c <= 10; c++)
{
aleatorio = rand() % (11 - 1);
num = 1 + aleatorio;
//num = 1 + rand()%(11-1); // Alternative
cout << num << " ";
}
cin.get();
}
Calculating Area and Perimeter of a Circle
#include <iostream>
using namespace std;
int main()
{
int radio;
float area, perimetro;
cout << "Introduce the radius of the circle: ";
cin >> radio;
area = 3.14 * radio * radio;
perimetro = 3.14 * radio * 2;
cout << "The area is: " << area << " and the perimeter is: " << perimetro;
cin.get();
cin.get();
return 0;
}
Capturing and Displaying User Input
#include <iostream>
#include <conio.h>
using namespace std;
void hola(char nombre[50])
{
cout << "Hello " << nombre;
}
int desplegar_edad(int edad)
{
cout << "Your age is: " << edad;
return 0;
}
int main()
{
char nombre[50];
int edad;
cout << "What is your name? ";
cin.getline(nombre, 50);
cout << "What is your age? ";
cin >> edad;
hola(nombre);
desplegar_edad(edad);
getch();
}
Displaying Prime Numbers (While Loop)
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int cnt, i = 0, ii, res, nc = 0, np = 0;
cout << "Enter the number of prime numbers you want to display: ";
cin >> cnt;
while (np != cnt)
{
i++;
for (ii = 1; ii <= i; ii++)
{
res = i % ii;
if (res == 0)
nc = nc + 1;
}
if (nc == 2)
{
cout << i << " ";
np++;
}
nc = 0;
}
getch();
}
Checking for Prime Numbers
#include <iostream>
using namespace std;
int main()
{
int num, c, res, nc = 0;
cout << "Enter a number: ";
cin >> num;
for (c = 1; c <= num; c++)
{
res = num % c;
if (res == 0)
nc++;
//if (nc>2) // Optimization: Could break if nc > 2
// break;
}
if (nc == 2)
cout << "It is prime";
else
cout << "It is not prime";
cin.get();
cin.get();
}
Sum of Two Values
#include <iostream>
#include <conio.h>
using namespace std;
int sumar(int num1, int num2)
{
int r;
r = num1 + num2;
return r;
}
int main()
{
int num1, num2, r;
cout << "Enter the first value for the sum: ";
cin >> num1;
cout << "Enter the second value for the sum: ";
cin >> num2;
r = sumar(num1, num2);
cout << "The total sum is: " << r;
getch();
}
Incrementing Values by 2
#include <iostream>
#include <conio.h>
using namespace std;
int manejo_error(int a, int &r) // Use reference for 'r'
{
if (a < 50)
{
cout << "You entered an invalid value";
r = 1;
return r;
}
else
{
r = 0;
return r;
}
}
int main()
{
int a, i, r;
cout << "Enter a value between 50 and 100: ";
cin >> a;
manejo_error(a, r);
if (r == 0) // Corrected comparison
{
cout << "The values that increase by 2, from 50 up to 100, are: ";
while (a <= 98) // a should be less or equal to 98
{
a = a + 2;
cout << a << " ";
}
}
getch();
}