All posts by Fátima Ramírez

Estudiante de bachillerato en la Universidad de Guadalajara, apasionada por las artes, la ciencia y la tecnología.

Quiz week 14: Autoevaluation

I have made my Autoevaluation for the class and this is the result.

Autoevaluation – TC1017 Mastery – Sheet1

After a depp reflection, I realize that I need to learn how to use Scilab, make some recursions, and investigate what was the meaning of the las row of the document. I feel satisfied with my performance about coding during the semester, however, I still have very much to learn in the future.

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;
}

 

Quiz week 11: Partial #2 Review

The teacher gave us a document with 10 problems to solve. This with the objective of practicing the topics that we have seen during the semester.

 

Exercise 1:

Write a function that calculates the distance between two points in a coordinate plane. I used the Pythagoras theorem.

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

float distancia(float x1,float y1,float x2,float y2)
{
  float D;
  D = sqrt(pow((x2-x1),2)+pow((y2-y1),2));
  return D;
}

int main()
{
  float x1, x2, y1, y2;
  cout << "X1= ";
  cin >> x1;
  cout << "Y1= ";
  cin >> y1;
  cout << "X2= ";
  cin >> x2;
  cout << "Y2= ";
  cin >> y2;

  cout << distancia(x1,y1,x2,y2) << endl;
  return 0;
}

 

Exercise 2:

A program that prints a triangle with a given size. I utilized nested for’s to print each character line by line.

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

void triangle(int S)
{
  for (int c=1 ; c<=S ; c++)
  {
      for(int i=c ; i>0; i--)
      {
        printf("T");
      }
      printf("\n");
  }
  for (int c=S-1 ; c>0 ; c--)
  {
    for(int i=c ; i>0 ; i--)
    {
      printf("T");
    }
    printf("\n");
  }
}

int main()
{
  int S;
  cout << "\n\nSize: ";
  cin >> S;
  cout << "\n\n\n\n";
  triangle(S);
  cout << "\n\n\n\n";

  return 0;
}

 

Exercise 3:

A program that calculates factorial numbers. I used unsigned long int as the type of the result because the factorial operation only gives integer and positive numbers. I used conditionals to mark errors and a for to multiply numbers, and then substract an unit.

#include <iostream>
using namespace std;

unsigned long int factorial(int N)
{
  unsigned long int F=1;
  if (N<0)
    cout << "Math error!" << endl;

  else if (N==0)
    F=1;

  else
  {
    for (int c=N; c>0; c--)
      F*=c;
  }

  return F;
}

int main()
{
  int N;
  cin >> N;
  cout << N <<"! = " << factorial(N) << endl;

  return 0;
}

 

Exercise 4:

A function that receives a list of numbers and calculates their average. I ask for the quantity of number that will be introduced, to declare the vector. Then I read each one and introduce the vecor in a function called promedio_lista. Then I just sum the numbers with a for and divide them by the quantity of them.

#include <iostream>
using namespace std;

float promedio_lista(float calf[], int N)
{
  float P=0;
  for (int c=0; c<N; c++)
    P+=calf[c];
  P/=N;

  return P;
}

int main()
{
  int N;
  cout << "\n\n\n¿Cuantas calificaciones vas a introducir? ";
  cin >> N;
  float calf[N];
  cout << "\n\n";

  for (int c=0; c<N; c++)
  {
    cout << "Calificación " << c+1 << ": ";
    cin >> calf[c];
  }

  cout << "\nPromedio= " << promedio_lista(calf, N) << "\n\n";

  return 0;
}

 

Exercise 5:

A function that detect the smallest number in a list of four numbers. To make this, I established that one of them were the smallest and then make comparisons with conditionals.

#include <iostream>
using namespace std;

float smallest_of_four(float a, float b, float c, float d)
{
  float m=a;
  if (b<m)
    m=b;
  else if (c<m)
    m=c;
  else if (d<m)
    m=d;

  return m;
}

int main()
{
  float a, b, c, d;
  cin >> a;
  cin >> b;
  cin >> c;
  cin >> d;

  cout << endl << smallest_of_four(a,b,c,d)<< endl;

  return 0;
}

 

Exercise 6:

A function that returns a value belonging to a given position of the Fibonacci serie. The challenge is to calculate the values, but I only needed a vector whose size is equal to the position that were given. Then I asigned the first two values, which are 0 and 1 respectively, and with a for, I added the two past numbers related with the number now being calculated, until the counter is equal to the requested position.

#include <iostream>
using namespace std;

unsigned long int fibonacci(int n)
{
  unsigned long int F[n];
  F[0]=0;
  F[1]=1;
  for (int c=2; c<=n; c++)
  {
    F[c]=F[c-1]+F[c-2];
  }
  return F[n];
}

int main()
{
  int n;
  cin >> n;
  cout << fibonacci(n) << endl;

  return 0;
}

 

Exercise 7:

A function that receives a list of numbers and returns the sum of their squares. I used a for and the function pow of the library <math.h>

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

double sumsquares_list(double list[], int N)
{
  double Sum=0;
  for (int c=0; c<N; c++)
    Sum+=pow(list[c],2);

  return Sum;
}

int main()
{
  int N;
  cout << "Cantidad de valores: ";
  cin >> N;
  double list[N];
  for (int c=0; c<N; c++)
  {
    cout << "Valor " << c+1 <<": ";
    cin >> list[c];
  }

  cout << "\n\nLa suma de los cuadrados de esos números es igual a " << sumsquares_list(list,N) << endl;

  return 0;
}

 

Exercise 8:

A program that calculates the square root through the Babylonian Method.

#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;
}

 

Exercise 9:

A function that find the number of times that the word “banana” appears in a text file.

#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() ){
             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;
}

 

Exercise 10:

A function that receives two positive integers and returns the greatest
common divisor of them. I determined which of the two values is the biggest and then I substract unit per unit until I find a value that can divide both numbers and give as a result integers. I made this with some conditionals and a while loop.
#include <iostream>
using namespace std;

int gcd(int X, int Y)
{
  int D;

  if(X>=Y)
    D=X;
  else
    D=Y;

  while ((X%D)!=0 || (Y%D)!=0)
    {D--;}

  return D;
}

int main()
{
  int X,Y;
  cin >> X;
  cin >> Y;
  cout << gcd(X,Y) << endl;
  return 0;
}

Quiz Week 9: The distance between coordinates

The task for today was only creating a function that could calculate the distance between two pair of coordinates on the cartesian coordinates plane that were given for the user. In the quiz was not necessary to create the entire program, but the function cause it was the only part required.

To make this part of the code, I utilized the Pythagoras Theorem cause if we conect the points given, we form a right triangle, of which we know its opposite and adjacent sides, and therefore we can calculate its hypotenuse. But for doing this we have to make a substraction between “x” points and then “y” points, so we have the exactly mesures. Then we apply the Pythagoras Theorem. And that’s all.

This is my resulting function:

float distance(float x1, float y1, float x2, float y2)
{
  float D;
  D= sqrt(pow((x2-x1),2) + pow((y2-y1),2));

  return D;
}

 

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;
}

Quiz Week 8

This class we were oredered to write a code that generates the Fibonacci series. I was a really challenging task, ’cause my logic didn’t adapted to the situation righly.

Finally I used some loops, vectors and a function to make it work. This is what I wrote.

#include <iostream>
using namespace std;

int fibonacci(int n)
{
  int sum[n];
  sum [0]=0;
  sum [1]=1;
  for(int c=2 ; c<=n ; c++)
    {
      sum[c]=sum[c-1]+sum[c-2];
    }
  return sum[n];
}

int main()
{
  int n;
  cout << "Introduce the last number position of the series: ";
  cin >> n;
  int sum[n];
  for(int c=0 ; c<=n ; c++)
  {
    sum[c] = fibonacci(c);
  }

  for(int c=0 ; c<=n ; c++)
  {
    if (sum[c]==sum[n])
      cout << sum[c];
    else
      cout << sum[c] << ", ";
  }
  cout << endl;
  return 0;
}

Actually, this code is not so complicated to do, you just need to see it in a different way, thinking how to explain to a computer that it is required to sum the two numbers before to obatain the third value.

Now, I have to change loops for recursions, but since I need to do other things, I will let it for the weekend. Meanwhile, do you want to try it?

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;
}

 

 

 

 

Quiz Week 6: Multiple exercises in an only quiz

The quiz for today consited in five exercises that we had to do during the class, which came from a page called C/C++ PROGRAMMING EXERCISES (they were the first five ones).

In the first problem, we had to modify a determinated code to make it work. The original code was:

#include 
main()
{ /* PROGRAM TO PRINT OUT SPACE RESERVED FOR VARIABLES */
    char c;  
    short s;  
    int i;  
    unsigned int ui;  
    unsigned long int ul; 
    float f;
    double d;  
    long double ld;  
    cout << endl 
         << "The storage space for each variable type is:"
         << endl;
    cout << endl << "char: \t\t\t%d bits",sizeof(c)*8;  //  \t means tab 
    cout << endl << "short: \t\t\t%d bits",sizeof(s)*8;
    cout << endl << "int: \t\t\t%d bits",sizeof(i)*8;
    cout << endl << "unsigned int: \t\t%d bits",sizeof(ui)*8;
    cout << endl << "unsigned long int: \t%d bits",sizeof(ul)*8;
    cout << endl << "float: \t\t\t%d bits",sizeof(f)*8;
    cout << endl << "double: \t\t%d bits",sizeof(d)*8;
    cout << endl << "long double: \t\t%d bits",sizeof(ld)*8;

I opted for changing cout for printf, adding the stdio.h  and iostrem libraries, as well as the line using namespace std; and declaring main as int. I consulted the page that our professor recommended to learn more about printf. It should be mentioned that what this program does is showing the number of bits that a type of value can store. My final code is the following one:

#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{ /* PROGRAM TO PRINT OUT SPACE RESERVED FOR VARIABLES */
    char c;
    short s;
    int i;
    unsigned int ui;
    unsigned long int ul;
    float f;
    double d;
    long double ld;
    cout << endl
           << "The storage space for each variable type is:"
         << endl;

    printf("char \t\t\t%d bits\n",int (sizeof(c)*8));
    printf("short: \t\t\t%d bits\n",int (sizeof(s)*8));
    printf("int: \t\t\t%d bits\n",int (sizeof(i)*8));
    printf("unsigned int: \t\t%d bits\n",int (sizeof(ui)*8));
    printf("unsigned long int: \t%d bits\n",int (sizeof(ul)*8));
    printf("float: \t\t\t%d bits\n",int (sizeof(f)*8));
    printf("double: \t\t%d bits\n",int (sizeof(d)*8));
    printf("double: \t\t%d bits\n",int (sizeof(d)*8));
    printf("long double: \t\t%d bits\n",int (sizeof(ld)*8));
}

The second exercise was about casting types of values to other one, and return taken values. I have to recognize that I didn’t know what to do at the first, but after meditating on it a little, I realized that it wasn’t difficult at all. I just had to use printf again and specify that I wanted to convert a variable to another type different to the one that it was declared at the first. The utilized types were char, int and float. The next code is the one that I made for this problem:

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

int main(){
  char C;
  int I;
  float F;

  cout << "Input a single character, followed by : ";
  cin.get(C);
  cout << "Input an integer, followed by : ";
  cin >> I;
  cout << "Input a float, followed by : ";
  cin >> F;

  printf("The character %c when cast to an int gives value %d\n",C,int(C));
  printf("The character %c when cast to a float gives value %f\n",C,float(C));
  printf("The integer %d when cast to a char gives value %c\n",I,char(I));
  printf("The integer %d when cast to a float gives value %f\n",I,float(I));
  printf("The float %f when cast to a char gives value %c\n",F,int(F));
  printf("The float %f when cast to an int gives value %d\n",F,int(F));
  return 0;
}

The third exercise only required to print a given pattern. This was my code (you will notice that it is very short and simple):

#include <iostream>
using namespace std;

int main(){
  cout << "            C" << endl;
  cout << "          i   I" << endl;
  cout << "        s       s" << endl;
  cout << "      b           b" << endl;
  cout << "    e               e" << endl;
  cout << "  s                   s" << endl;
  cout << "t s e b s i C i s b e s t" << endl;
return 0;
}

The next exercise is a little more complicated, because it’s about ordering three numbers in ascending order so I made three different functions (first, second and last term) and each one contained conditionals, so my program resulted a little long (relatively).

#include <iostream>
using namespace std;

int minor(int x, int y, int z)
{
  int m;
  if (x<=y && x<=z)
    m=x;
  else if (y<=x && y<=z)
    m=y;
  else if (z<=x && z<=y)
    m=z;
  return m;
}

int medium(int x, int y, int z)
{
  int m;
  if ((x>=y && x<=z) || (x>=z && x<=y))
    m=x;
  else if ((y>=x && y<=z) || (y>=z && y<=x))
    m=y;
  else if ((z>=x && z<=y) || (z>=y && z<=x))
    m=z;
  return m;
}

int maximum(int x, int y, int z)
{
  int m;
  if (x>=y && x>=z)
    m=x;
  else if (y>=x && y>=z)
    m=y;
  else if (z>=x && z>=y)
    m=z;
  return m;
}

int main()
{
  int a, b, c, P, S, T;
  cout << "Number 1: ";
  cin >> a;
  cout << "Number 2: ";
  cin >> b;
  cout << "Number 3: ";
  cin >> c;

  P=minor(a,b,c);
  S=medium(a,b,c);
  T=maximum(a,b,c);

  cout << "\n\nThose numbers, in ascending order, are: \n" << P << endl << S << endl << T << endl;
  return 0;
}

Finally, the last problem I had to solve was this one:

“Given the following rules, write a program to read a year (4 digit integer) and tell whether the given year is/was a leap year.

  1. There were no leap years before 1752.
  2. If the year divides by 400 then it is a leap year.
  3. All other years that divide by 100 are not leap years.
  4. All other years that divide by four are leap years.

For example, 1800,1900 were not leap years but 2000 will be; 1904, 1908,…,1996 were/will be leap years.”

I had some problemas with my logic because I wanted to integrate all the “rules” at once, but I couldn’t do it since the program didn’t return the right values. Therefore I added some if’s, else if’s and nested conditionals to make it work. This was the result:

#include <iostream>
#include <string>
using namespace std;

string leap(int Y)
{
  string R;
  if (Y<1752)
    R="That year was/will be NOT a leap year\n";
  else if ((Y%100)==0)
  {
    if ((Y%400)==0)
      R="That year was/will be a leap year\n";
    else
      R="That year was/will be NOT a leap year\n";
  }
  else if ((Y%4)==0)
    R="That year was/will be a leap year\n";
  else
    R="That year was/will be a NOT leap year\n";

  return R;
}

int main()
{
  int Y;
  cout << "Year: ";
  cin >> Y;
  cout << leap (Y);
  return 0;
}

Well, this is all we do during the large quiz of the week six…

See you soon…

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.

Quiz Week 4: The minimum value and sum of squares

I utilized two functions to do this program, one is in charge of comparing two values and then keep the minor of both, to campare it again with any other value. The other function calculate the sum of the square of given values.

After stablish that, I proceeded to ask the user for the quantity of values that they wanted to introduced, and finally for each number, either negative or positive. To do this succesfully, I first made a comparison and the respective sum between the two first numbers and, for the rest, I set a loop that called the previously mentioned functions.

I opted for adding a conditional that didn’t allow to introduce a smaller number than two for the first question. Also, I added a loop that “clean” the screen.

At the final, the program print the minimum value of introduced numbers and the sum of their squares.

quiz4-1quiz4-2

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;
}

 

Quiz Week 3: Challenged with functions

Today the whole classroom were ordered to write a code as a quiz that could calculate square and cube roots in a uncommon way where we used functions.

At the first of the class many of us didn’t know what to do, so we started to search information on the web. Finally, I asked for a classmate help and my wolrd lit up. This i what I learned from both internet and my friend:

  1. I need to call the library math.h to use mathematical operations like square root and cube root.
  2. To write a function you need to declare the type of this one.
  3. Then you have to write its name and, in parentheses, declare all the variables you need to use during the execution of the function.
  4. After that, in curly brackets, you write the type of the function, call the function, and tell it what to do.
  5. At the end of the function, you need to return the resultant value.
  6. Finally, you print as well as ask for data into int main() function. You can add all the conditionals or loops you need.
  7. For using the functions previouly created you only have to utilize a output command, and inside it you call the function with the corresponding variable. The format is something like this: cout << function_name(variable); .

Well, that is what I practically did today during the class, and I have to say that I was joyful when my program could be compiled.

P.D. I made my program to use imaginary numbers for square roots, with the symbol “i” (which means the square root of -1),  when the user entered a negative number, instead of displaying an error, beacuse I think it’s m

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?