Category Archives: Homework

Homework 12: Estimating e

This program will be capable of estimate the value of “Euler’s number” (e) and the user will give the accuracy expressed as a number of decimals.

To calculate e, I declared three variables. One of them saves tha value of e, another counts each executation of the loop, and the last one (x), in each ocassion is multiplied by the counter, an then divides the number one (1) to be added to e.

This process is into a loop that is executed a big number of times, I made it to be repeated 999,999,999,999,999,999 times. And obviously, all this is a function.

Finally, in the main funtion, I ask the user for the accuracy of e, and I interpret it as the number of decimals. I show that quantity of decimals using printf(“%.*Lf\n\n\n”,a,calculate_e()),  where the asterisk allows to specify the the decimal is a variable called “a”. The letters “Lf” indicates that the type of the value (long double) and the period after “%” indicates that we are modifying the number of printed decimals.

Having said that, I’ll show you my code…

#include <iostream>
#include <cmath>
#include <stdio.h>
using namespace std;

long double calculate_e(void)
{
  long double e=1, x=1 , i=1;
  while(x<999999999999999999)
  {
    x*=i;
    e+=1/x;
    i++;
  }
  return e;
}

int main() {
  int a;
  cout << "\n\nLet's to calculate 'e'...\n";
  cout << "ACCURACY (Number of decimals between 1 and 50): ";
  cin >> a;
  printf("%.*Lf\n\n\n",a,calculate_e() );
  return 0;
}

 

 

Homework 11: Go Bananas

Now we are going to make a program that can find the quantity of BANANAS present in a text file. The word “banana” can be writen in any way, that’s why I opted for converting all letter in the document to lower case.

I set a vector called BANANA with a size of 6, where each position represent a letter of “banana” in the correct order. This is be very useful to find the wished words.

I also created a bool function, which counts the number of bananas . This function receives two parameters, one is a vector that contains charactesrs taken from the text file and another is its size.

I made the program to read character by character, convert them to lowercase, and if a character was a “b”, then we aply the function compare.

Of course, we have to open the text file, and then close it. I also implement that the program ask for a file to read.

This is my final code.

#include <iostream>
#include <ctype.h>
using namespace std;
#include <fstream>

bool compare(char vector_prueba[], int N=6)
{
  char BANANA[6]={'b','a','n','a','n','a'};
  bool result=true;
  int c=0;
  while(c<6)
  {
    if (BANANA[c]==vector_prueba[c]) c++;
    else return false;
  }
  return true;
}

int find_Bananas(string nombre)
{
    fstream ficheroEntrada;
    int Ban=0;
    char letra;

    ficheroEntrada.open ( nombre.c_str() , ios::in);
    if (ficheroEntrada.is_open()) {

        while (! ficheroEntrada.eof() ) {
          ficheroEntrada >> letra;
          letra = tolower(letra);
          if (letra == 'b')
          {
            char bananatest[6]={'b'};
            for(int i=1; i<6; i++)
            {
              ficheroEntrada >> letra;
              bananatest[i] = letra;
              bananatest[i] = tolower(bananatest[i]);
            }
          if (! ficheroEntrada.eof() ){ // evaluates if the file have finished (if there is no more to read)
             if (compare(bananatest,6)) Ban++;
           }
         }
        }

        ficheroEntrada.close();
    }
    else cout << "Fichero inexistente o faltan permisos para abrirlo" << endl;
    return Ban;
}
int main()
{
    string nombre;
    cout << "\n\nDime el nombre del fichero: ";
    getline(cin,nombre);
    cout << "\nThere is/are " << find_Bananas(nombre) << " banana's in the file.\n\n" << endl;

    return 0;
}

Homework 10: Babylonian Method

This function will calculate a square root through the Babylonian Method.

First of all, I would like to explain how the method works. You have to establish a first number that is “aproximate” to the real squareroot, doesn’t matter if that number is equal to one, because we are going to make some mathematical operations. Shown below the steps.

  1. Divide the number, which we want to calculate its square root (N), between the before established number (y).
  2. The result of the past step will be added to the first established number (y).
  3. We repeat this steps until we obtain the aproximation as exactly as we want it.

Having said that, we only have to create a function that execute this algorithm, and ask the user for the number that he/she wants to calculate its square root.

This is my code.

#include <iostream>
using namespace std;

long double square_root(long double N)
{
  long double y=1, c;
  for(int i=0; i<1000; i++)
  {
    c=N/y;
    y=(y+c)/2;
  }
  return y;
}

int main()
{
  int N;
  cout << "Square Root... \n\nNumber: ";
  cin >> N;
  cout << "The square root of "<< N << " is equal to "<<square_root(N) << endl << endl;
  return 0;
}

 

Homework 9: Multipart data and files

In this asingment we are going to read a text file and count the number of both lines and characters present on the document.

We need to use the libraries #include and #include to be able to use the functions that open and read text documents.

This is my code.

#include 
#include 
using namespace std;

int main()
{
  fstream text1;
  int lines=0, chars=0; // we initialize two variables for lines and characters, to count them
  string line; //we declare and string variable to read a line
  char letter; // this is gonna let us read each character

  text1.open("Archivo.txt", ios::in); // the file is open
  while(! text1.eof()) // reads each line and counts it
  {
    getline(text1,line);
    lines++;
  }
  text1.close();
  fstream text2;
  text2.open("Archivo.txt", ios::in); // the file is open
  while (! text2.eof() ) { // reads each character and counts it. 
    text2 >> letter;
    chars++;
  }
  text2.close(); // close the file
  lines-=1;
  chars-=1;

  cout << "\nThe file contains ... \n" << endl;
  cout <<"Amount of lines: " << lines << endl;
  cout <<"Amount of characters: "<< chars << endl << endl;



  return 0;
}

Homework 8: Yo soy 196

We are going to calculate the quantity of Lychrel numbers (natural numbers that doesn’t convert on palindromes after a serie of aditions, for example, 196 is a Lychrel number), natural and made palindromes that are present in a range of integer numbers given by the user.

If we want to convert a non-natural palindrome to a palindrome we have to sum its reverse until we obtain the palindrome.

Using this logic, we can declare some variables that acumulate the reverse and suspect numbers, and evaluate a significant number of times until either do we find the palindrome or do we determine that the given number is Lychrel.

To make all this process I utilized some while loops where I flip the numer and then compare the resulting number with the original one.

You can see my code here…

// El programa usa Big Integer para almacenar más datos. Esta es una librería creada por el maestro.
#include <iostream>
//#include <math.h>
#include <string>
#include "BigIntegerLibrary.hh"
using namespace std;

BigInteger reverse(BigInteger N)
{
  BigInteger M=0, n=N;
  int d=0;

  while(n!=0)
  {
    d++;
    n/=10;
  }

  for (;d>0; d--)
  {
    BigInteger D=1;
    for(int c=0; c<d-1; c++)
      {D*=10;}
    M+=(N%10)*D;
    N/=10;
  }
  return M;
}

int main()
{
  BigInteger n, N, NatPal=0, MadePal=0, Lych=0, m, l;
  string s, S;

cout << "\nLower bound of the sequence: ";
  cin >> s;
  cout << "Upper bound of the sequence: ";
  cin >> S;
  n = stringToBigInteger(s);
  l = n;
  N = stringToBigInteger(S);

  for (; n<=N ; n++)
  {
    BigInteger c=0;
    m=n;
    if (n == reverse(n))
    {NatPal++;}
    else
    {
      do {
        m+=reverse(m);
        c++;
      } while(m!=reverse(m) && c!=30);

      if (c==30)
      {Lych++;}
      else
      {MadePal++;}
    }
  }

  cout << "\nWe are calculating how many natural and made palindromes, as well as Lycherel numbers, there are in the range given...\n\n"<< endl;
  cout << "The results for the range "<< l << " to " << N << " are:\n"<< endl;
  cout << "Natural palindromes: " << NatPal << endl;
  cout << "Made palindromes (Non-Lycherel numbers): " << MadePal << endl;
  cout << "Lycherel candidates: " << Lych << "\n\n";
  return 0;
}

 

 

 

 

Homework 7: Lists

This program will ask the user for 10 numbers and will be stored in a vector. Then, the user will be able to see the total of the sum, average and standard deviation of those numbers.

A vector is very easy to use, you have to asign a type to the vector and give it a dimension. Something like this “type Vector[dimension]”. To asign a value inside the vector, you give the number of the row, e.g. “Vector[2] = Example”. You must begin from cero (first row) and end in “dimension-1” (last row). Now with for’s we can access to each row one by one.

Knowing this, we can make the program easily. This is my code…

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
  float numbers[10];
  float X;
  float SUM=0, AVG, SD, VAR=0;
  cout << "\n\n";

  for (int c=0; c<10; c++)
  {
    cout << "Number " << c+1 << "= ";
    cin >> X;
    numbers[c] = X;
    SUM += numbers[c];
  }

  AVG = SUM/10;

  for (int c=0; c<10 ; c++)
  {
    VAR+= pow ((numbers[c] - AVG), 2);
  }
  SD = sqrt(VAR/10);

  cout << "\n\nSum = " << SUM << endl;
  cout << "Average = " << AVG << endl;
  cout << "Standard deviation = " << SD << endl;

  return 0;
}

 

 

Homework 6: Factorial Calculator

Let’s make a factorial calculator!

First of all, we have to know what a factorial number is. If you see a number that is accompanied by an exclamation sign, you’re seing a factorial number, that consists in a number multiplied by all the precedent integer numbers until reach one. For example, 6!= 65432*1 = 720.

Knowing that, we can proceed to elaborate the code. We are going to create a function, of type “long double”, which is in charge of calculating factorial numbers.

You can see what I did in the following code.

// Using long double to obtain big values of factorial numbers

#include <iostream>
#include <math.h>
using namespace std;

long double fact (long double n)
{
  long double R=n;
  if (n==0)
    {R=1;}
  for (n--; n>0; n--){
    {R*=n;}
  }
  return R;
}

int main()
{
  long double N;
  long double n;
  char C='Y';

  do
  {
    if (C!='Y' && C!= 'y')
      {cout << "\n\nInvalid choise! \nTry again"<< endl;}
    else
    {
      cout << "\nNon-negative integer: ";
      cin >> N;
      n = floor(N);

      if (N<0)
        {cout << "\nMATH ERROR! \nPlease, introduce a NON-NEGATIVE number\n\n" << endl;}
      else if (N!=0 && (N/n)!=1)
        {cout << "\nMATH ERROR!\nPlease introduce an INTEGER number!\n\n";}
      else
        {cout << "\n" << N << "! = " << fact(N) << "\n\n";}
    }

    cout << "\nDo you want to introduce another number?\n(Yes = Y / No = N)\n\n";
    cin >> C;

  } while (C!='N' && C!='n');

  cout << "\n\nHave a nice day!!\n\n\n";
  return 0;
}

 

 

 

 

Homework 5: Calculator

This program will make some basic operations. It’s just like the program of the first homework, but using functions.

We have to create 5 functions: sum, subtraction, multiplication, division and remainder. Each function must read two integer parameters (the same for each one) given for the user. Also, we have to declare another variable which keep the result of each function. It’s very intuitive to make this program, we only have to use the corresponding mathematical operator (and, of course, we use module ‘%’ for function remainder).

Here is the code that I wrote.

#include <iostream>
#include <math.h>
using namespace std;

int sum (int x, int y)
{
  int R;
  R=x+y;
  return R;
}

int dif (int x,int y)
{
  int R;
  R=fabs(x-y);
  return R;
}

int prod (int x, int y)
{
  int R;
  R=x*y;
  return R;
}

int div (int x, int y)
{
  int R;
  R=x/y;
  return R;
}

int mod (int x, int y)
{
  int R;
  R=x%y;
  return R;
}

int main()
{
  int x, y;
  cout << "\nFirst number: ";
  cin >> x;
  cout << "Second number: ";
  cin >> y;

  cout << "\nSum= " << sum(x,y) << endl << "Difference= " << dif(x,y) << endl << "Product= " << prod(x,y) << endl
  << "Division (first/second)= " << div(x,y) << endl << "Remainder of division= " << mod(x,y) << "\n\n";
  return 0;
}

 

 

Homework 4: Sum of Numbers

This program sums a range of consecutive numbers, between a given range by the user. It’s very simple to make, I will show you step by step how to make it.

  1. As usual, you need to call the necessary libraries and open the main function.
  2. We have to declare two variables for the bounds, one for the sum,  and another one that keeps the value of the lower bound. The variable for sum must be inicialized in zero.
  3. Then, we ask the user for the bounds and validate if the lower bound is less than the upper one. If it is, we proceed to sum number by number, increasing the lower bound value one by one, this with a while loop, that will work until the variable ‘L’ is the same as ‘U’ (upper bound).
  4. Finally, we print on the screen the value of the sum made.

 

Here is the code…

#include <iostream>
using namespace std;

int main()
{
  int L,U,l,S=0;

  cout << "I'll give you the sum of a rage of consecutive integer numbers, you only have to indicate the interval\nWhich is the lower bound? ";
  cin >> L;
  cout << "Which is the upper bound? ";
  cin >> U;
  l=L;

  while (L>U)
  {
    cout << "You entered the numbers in the wrong order.\nPlease do it rightly.\n\nLower bound: ";
    cin >> L;
    cout << "Upper bound: ";
    cin >> U;
  }

  while (L<=U)
  {
    S+=L;
    L++;
  }


  cout << "The sum of the consecutive integer numbers between " << l << " and " << U << " is equal to: " << S << endl;
  return 0;
}

 

 

Homework 3: Pick a number

I have to say that this task is a little more complicated than the previous exercises, because it was necessary to use a special function to generate numbers randomly. This program was thought as a game, where the user have to guess a random number. I decided to give the user only five chances to achieve it.

This is my code:

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
  int X, c=1;

  srand(time(NULL)); // random numbers are activated
  int N = rand()%100+1; // random numbers between 1-100 formula: rand()%(RANGE+1)+MINIMUM

  cout << "Let's play a game! \nYou have to guess the number I have in mind, but you only have 5 chances \nI'll give you a clue: the number is between 1 and 100" << endl;
  cout << "What number am I thinking? ";
  cin >> X;

  while (X!=N && c<5)
  {
    if (X>N)
    {
      cout << "Sorry but " << X << " is too high. \nYou have " << 5-c << " attempts remaining.\nTry again: ";
      cin >> X;
    }
    else if (X<N)
    {
      cout << "Sorry but " << X << " is too low. \nYou have " << 5-c << " attempts remaining.\nTry again: ";
      cin >> X;
    }
    c++;
  }

  if (X==N)
  {
    cout << "Congratulations winner! You have guessed my secret number" << endl;
  }
  else
  {
    cout << "You lost! \nThe number I was thinking about is " << N << " \nGood luck for the next time."<<endl;
  }
  return 0;
}

As you can see, I included a library call stdlib.h and time.h (that are necessary for generating random numbers).

I used conditionals to evaluate if the user entered the right value or have to try again, and a loop (a “while” specifically) with the purpose of repeating the procedure only five times if the user doesn’t guess the number.

Homework 2: Temperature

Now our task was to biuld a program that convert the temperature mesures from Fahrenheit to Celsius degrees, and at the same time indicate if the water boils at the given temperature.

It was necessary a few calculations, cout commands and some conditionals to make it work, being this the result:

#include <iostream>
using namespace std;

double celsius(int F)
{
  int celsius = 5*(F-32)/9;
  return celsius;
}

int main ()
{
  int F;
  cout << "Give me the temperature in degrees Fahrenheit: ";
  cin >> F;

  cout << "The temperature given is equivalent to " << celsius(F) << "°C" << endl;

  if (celsius(F)<100)
    cout << "Water does not boil at this temperature (under 1 atm of pressure)" << endl;

  if (celsius(F)==100)
    cout << "Water will boil at this temperature (under 1 atm of pressure)" << endl;

  else
    cout << "Water will be completely vapor at this temperature (under 1 atm of pressure)" << endl;

  return 0;
}

 

Homework 1: Fun with numbers

Our first assigment was to make a program that asked the user for two numbers and then showed the sum, difference, product, integer quotient and remainder of that numbers.

The code I made is very simple, I just included an additional library (<math.h>) to use the fabs function whe dividing the numbers, because the instructions indicated a difference, and differences are always absolute.

This is my program:

#include <iostream>
#include <math.h>
using namespace std;

int main() {

  int X, Y;

  cout << "Write an integer number: ";
  cin >> X;
  cout << "Give me another integer number: ";
  cin >> Y;

  cout << "Sum = " << X+Y << endl;
  cout << "Difference = " << fabs(X-Y) << endl;
  cout << "Product = " << X*Y << endl;
  cout << "Division (first/second) = " << X/Y << endl;
  cout << "Remainder of division = " << X%Y << endl;

  return 0;
}

 

Hello World!!!

This is the first program I make with C++. It is very simple, and it’s like the “Ritual of Iniciation” in the programming world. You only have to understand simple concepts to make it happen.

For example, to print or read informatio during the execution of the program, you need to write the line #include <iostream> and to avoid write std::comand; (the part of std::) in each line and comand you want to execute, you just have to write using namespace std; .

It’s as simple as that. Now, to write anything you can use the comand cout << //what you want to print into ” “;

This is my Hello World! code:

#include <iostream>
using namespace std;

int main()
{
  cout << "Hello World!";
  std::cout << "/* message */" << '\n';
  return 0;
}

 

What is the yours?