Category Archives: Quiz

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.

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

 

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?

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…

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

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