Warning: The magic method Slickr_Flickr_Plugin::__wakeup() must have public visibility in /home/kenbauer/public_kenscourses/tc101fall2015/wp-content/plugins/slickr-flickr/classes/class-plugin.php on line 152
‘#include’ Articles at TC101 Fall 2015
Introduction to Programming Python and C++

Tag Archives: #include

#mastery18

this Mastery might sound too complicated but in fact it is too easy to regard this mastery is known in Spanish as conditional nested , and no forces have to be an if as it is not the only type of conditional exists, nested conditional m…

Mastery # 28 TC1017

Escribir en documentos C++

Para escribir en un documento primeramente necesitamos la realización de un archivo de texto, en el cual la base para hacerlo es la siguiente
// writing on a text file
 
usingnamespace std;
 
intmain () {
  ofstream myfile ("Write.txt");
  if(myfile.is_open())  {
    myfile "This is a line.\n";
    myfile "Hello world.\n";
    myfile.close();
  }
  else{
    cout "Unable to open file";
  }
  return0;
}
 
en lo cual ahi tenemos el documento en el cual ingresaremos los datos usamos la libreria fstream, se abre el archivo y se ingresa lo que se quiere escribir en el documento
 
 
en cambio para la lectura de los documentos contamos con un procedimiento parecido, que es el siguiente:
// reading a text file
usingnamespace std;
 
intmain () {
  string line;
  ifstream myfile ("CNC.txt");
  if(myfile.is_open()){
    while( getline (myfile,line) ){
      cout '\n';
    }
    myfile.close();
  }
  else{
    cout "Unable to open file";
  }
 
  return0;
}
 
en este, tenemos que abre el archivo y este es leido linea por linea y convertida en strings, para esto t

Mastery #24 TC1017

                  ¿Qué son los arrays o arreglos?
Un arreglo en C++ es un conjunto de datos que se almacenan en memoria de manera contigua con el mismo nombre. Para diferenciar los elementos de un arreglo se utilizan índices detrás del nombre del arreglo y encerrados por []. El elemento 5° (quinto) de un arreglo, es representado por el índice [4], ya que los índices comienzan en 0. Esto significa que un arreglo de 10 elementos tendría los índices del 0 al 9: [0...9].
Después de definir que son y como se pueden usar los arreglos vamos a ver como se programan con los siguientes pasos:
  1. definir que tipos de variables queremos guardar en el arreglo.
  2. ya definida nuestra variable  tenemos que pensar cuantos datos queremos guardar en el arreglo
  3. ya definida la anterior información lo que debemos hacer es empezar a programarlo, la manera para crear un arreglo es casi la misma para crear otras variables
  4. podemos definir el tipo de variable, antes o al momento de ingresar cuantos datos queremos poner
  5. después de definirla nos pondremos a definir cuantos espacios (cajas) queremos que tengan este numero siempre tiene que estar entre “[ ]” 
  6. ya definida cuantos datos queremos lo que debemos hacer es ingresarlos, empezando por el lugar 0, los datos se empiezan a ingresar desde el lugar cero por lo tanto si decidimos que va a tener 10 lugares  el ultimo lugar va a ser el lugar 9.
  7. y as es como se trabaja con arreglos.

Ejemplo:

using namespace std
int main ( )
{
int arreglo [10]; // en este arreglo es un arreglo de enteros llamado “arreglo” y con un numero de espacios de 10
arreglo[0]=5; //en este momento estamos diciendo que el primer arreglo o el 0 ya que empieza desde el cero es 5
arreglo[9]=45; //y en este ultimo arreglo el 9 ya que como se señalaron 10 espacios y empieza en el 0 el 9 es el ultimo
return 0;


Mastery # 23 TC1017

Creación y uso de vectores en C++

Un vector, también llamado array(arreglo) unidimensional, es una estructura de datos que permite agrupar elementos del mismo tipo y almacenarlos en un solo bloque de memoria juntos, uno después de otro. A este grupo de elementos se les identifica por un mismo nombre y la posición en la que se encuentran. La primera posición del array es la posición 0.
Podríamos agrupar en un array una serie de elementos de tipo enteros, flotantes, caracteres, objetos, etc.
Crear un vector en C++ es sencillo, seguimos la siguiente sintaxis: Tipo nombre[tamanyo];
Aqui tenemos varios ejemplos:
inta[5]; // Vector de 5 enteros
floatb[5]; // vector de 5 flotantes
Producto product[5]; // vector de 5 objetos de tipo Producto
Otra manera para inicializar el vector en la declaración es la siguiente:
1
2
3
int a[] = {5, 15, 20, 25, 30};
float b[] = {10.5, 20.5, 30.5, 12.5, 50.5}
Producto product[] = {celular, calculadora, camara, ipod, usb}
Debido a que tenemos 5 elementos en cada array, automáticamente se le asignará 5 espacios de memoria a cada vector, pero si trato de crear el vector de la forma int a[] , el compilador mostrará un error, porque no tiene indicado el tamaño del vector ni tampoco sus elementos.
Tambien podemos asignarle valores a los elementos de un vector indicando su posición:
inta[4] = 30; // le asigno el valor 30 a la posición 4 del vector.
product[2].setPrecio(300) // le asigno un precio de 300 al producto en la posición 2.
Algo muy útil para llenar, recorrer e imprimir un vector es el uso de el bucle for:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using namespace std;
 
int main()
{
  int dim;
  cout "Ingresa la dimension del vector"
  cin >> dim; // Supongamos que ingrese 10
  int vector[dim]; // mi vector es de tamanyo 10
 
  for(int i = 0; i
    vector[i] = i * 10;
    cout
  }
 
  return 0;
}
La salida de este programa nos mostrará: 0 10 20 30 40 50 60 70 80 90.
Enseguida tenemos una función simple para sumar 2 vectores a y b y poner el resultado en un tercer vector c:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using namespace std;
 
void sumar(int a[], int b[], int c[],int dim) {
    for (int i = 0; i
        c[i] = a[i] + b[i];
    }
}
 
void imprimir(int v[], int dim)
{
   for(int i = 0; i
        cout
   }
   cout
}
 
int main()
{
    int dim;
    cout "Ingresa la dimensión"
    cin >> dim;
 
    int a[dim];
    int b[dim];
    int c[dim];
 
    for(int i = 0; i
        a[i] = i * 10;
        b[i] = i * 5;
    }
 
    cout "Vector A "
    imprimir(a, dim);
 
    cout "Vector B "
    imprimir(b, dim);
 
    sumar(a, b, c, dim);
    cout "Vector C "
 
    imprimir(c, dim);
    return 0;
}
En resumen:
  • Todo vector debe tener definido un tipo de dato.
  • Todo vector necesita de una dimensión o tamaño.

#Quiz11

Here´s my quiz 11, it was a little more complicated than I thought, but in the end I receive some help from my friends Marco Patiño and Esaú Preciado, and well they teach me how to do the programms.

so here are my programms

q1.

 <iostream>
<iomanip>
using namespace std;

void newline(){
  cout<<endl;
}

double factor(int a){
double output= 1.0;
for (int i = 1; i <= a; i++){
  if (a == 0)
  return output;
  else
  output = output * i;
  }
return output;
}

double define_e(int exact){
double output1 = 0.0, output2 = 1.0;
for(int i= 1; i<1000 ; i++){
  output1 = output2;
  output2 = output1 + (1/factor(i));
}
cout << fixed << setprecision(exact) << output2 << endl;
return output1;
}
int x = 0;

int main(){
float e;
string z;
cout<<"Hi, I´m a calculator of the e constant "<<endl;
newline();
cout<<"Please insert how precisely you want this mathematical constant "<<endl;
newline();
cin>>e;
newline();
cout<<"The result equals to "<<define_e(e)<<endl;
newline();
}
return 0;
}

 

q2.

 <iostream>
<string>
<fstream>
using namespace std;

int main(){
string Read;
string Banana = "banana";
char archive[50];
int x = 0;
int y = 0;
int counter = 0;
cout << "Write the name of your file: ";
cin >> archive;

ifstream read_file (archive);
if (read_file.is_open()){
while (getline(read_file , Read)){
      x = 0;
      while (x < Read.length()) {
        char character = Read[x];
        if ( character == 'B' || character== 'b'){
          y = x + 1;
          char character = Read[y];

          if (character == 'A' || character== 'a'){
            y++;
            char character = Read[y];

            if (character == 'N' || character== 'n'){
              y++;
              char character = Read[y];

              if (character == 'A' || character== 'a'){
                y++;
                char character = Read[y];

                if (character == 'N' || character== 'n'){
                  y++;
                  char character = Read[y];

                  if (character == 'A' || character== 'a') {
                    counter++;
                  }
                }
              }
            }
          }
        }
        x = x + 1;
}

    }read_file.close();
    }else{
      cout << "Error 404 not found" << endl;
    }
cout << "I found " << counter << " bananas....So eat them all!!!...or not..." << endl;
return 0;
}

Also on github.

Program1.

https://github.com/everibarra/TC101-C-/blob/master/quiz11q1.cpp

Program2

https://github.com/everibarra/TC101-C-/blob/master/quiz11q2.cpp

#Project Advance 3

We finally did the project, we just need to adjust some functions, because we were using functions from theimagemagick library, tomorrow we´re going to change the programm and see if it runs with arrays.

here´s the code:

 <Magick++.h> 
<iostream>
using namespace std;
using namespace Magick;

void newline(){
  cout<<endl;
}

int main(int argc,char **argv)
{
  InitializeMagick(*argv);
  try{
  int x;
  cout<<"Hi, Im a manipulator of images "<<endl;
  newline();
  cout<<"What do you want to do? (press the number in your keyboard) "<<endl;
  newline();
  cout<<"1. Rezise the image to one half of its original size"<<endl;
  cout<<"2. Switch to black and white"<<endl;
  newline();
  cin>>x;
 
  if(x==1){
     newline();
     cout<<"Alright, now introduce the name of the file with its extension; example: new.jpg"<<endl; 
     newline();
     Image image;
     string img;
     cin>>img;
     image.read(img);
     image.minify();
     image.write("resized.jpg");
 }
  if(x==2){
     newline();
     cout<<"Alright, now introduce the name of the file with its extension; example: new.jpg"<<endl; 
     newline();
     Image image2;
     string img2;
     cin>>img2;
     image2.read(img2);
     image2.quantizeColorSpace( GRAYColorspace );
     image2.quantizeColors( 256 );
     image2.quantize( );
     image2.write("blackandwhite.jpg");
 }      
 }
  catch( Exception &error_ )
    {
      cout << "Caught exception: " << error_.what() << endl;
      return 1;
    }
  return 0;
}

Mastery #25 TC1017

Caracter de tipo “String”


La forma más común y fácil de acceder a un caracter en una determinada posición que queramos es mediante el uso de [] (corchetes) cómo se hace con los arrays, de esta forma si tenemos un tipo string de nombre str al cual le asignamos la palabra “programa” y queremos que se nos retorne la letra que está en la posición 3 (contando desde cero, como siempre) entonces el código sería el siguiente.
#include <iostream>
#include <string>
 using namespace std;
 int main(){
//definimos la cadena str
string str;
 //le asignamos el contenido & quot programa&  quot;
str = “programa”;
 //mostramos en consola cual es el caracter
//en la posición 3 (contando desde 0)
cout<<str[3]<<endl<<endl;
 return 0;
}

Un ejemplo sencillo:
 string> 
iostream>
using namespace std
;
main
() {
string mensaje
;
mensaje
= "Hola";
cout
mensaje; }
 Para ver todos los tipos de strings : https://blogdelingeniero1.wordpress.com/2014/07/23/el-tipo-string-y-sus-metodos-mas-importantes-en-c/

#Project Advance 3

This is not the final final project, and It´s not complete.

¡¡¡¡Hi!!!! this is the advance of the project, but we dont know how to change this to pixels or vectors, 

Link to code: 

https://github.com/kenwbauer/TC101F15_Team01/commit/62ff22fecfd823e3d4496eea9a7cdad78116c46d

 <Magick++.h> 

<iostream>

using namespace std; 

using namespace Magick; 

void newline(){

  cout<<endl;

int main(int argc,char **argv) 

  InitializeMagick(*argv);

  try{

  int x;

  cout<<"Hi, Im a manipulator of images "<<endl;

  newline();

  cout<<"What do you want to do? (press the number in your keyboard) "<<endl;

  newline();

  cout<<"1. Rezise the image to one half of its original size"<<endl;

  cout<<"2. Switch to black and white"<<endl;

  newline();

  cin>>x;

  if(x==1){

     newline();   cout<<"Alright, now introduce the name of the file with its extension; example: new.jpg"<<endl;  

     newline();

     Image image;

     string img;

     cin>>img;

     image.read(img);

     image.minify();

     image.write("resized.jpg");

 }

  if(x==2){

     newline();

     cout<<"Alright, now introduce the name of the file with its extension; example: new.jpg"<<endl;  

     newline();

     Image image2;

     string img2;

     cin>>img2;

     image2.read(img2);

     image2.quantizeColorSpace( GRAYColorspace );

     image2.quantizeColors( 256 );

     image2.quantize( );

     image2.write("blackandwhite.jpg");

 }       

 } 

  catch( Exception &error_ ) 

    {  cout << "Caught exception: " << error_.what() << endl;  return 1

    }return 0

}

 

#Project Advance 2

Hi everyone this is the “report” of the project.

This time we are using Imagemagick, Magick++; we can half size the image yeah, but we can’t change the color, ooooooooo u.u, so with this problem we are in a hurry, but we can do it and we feel positive with it because we are in the half of the way to complete this task 🙂

I feel like I´m not doing my best with this project, but here I am trying.

Some links that we found, (more Ever) and  this can help:

http://www.imagemagick.org/Magick++/Color.html#ColorGray

http://www.imagemagick.org/script/perl-magick.php

 

The code:

 

using namespace std;
using namespace Magick;

void newline(){
  coutendl;
}

int main(int argc,char **argv)
{
  InitializeMagick(*argv);
  try{
  int x;
  cout"Hi, Im a manipulator of images "endl;
  newline();
  cout"What do you want to do? (press the number in your keyboard) "endl;
  newline();
  cout"1. Rezise the image to one half of its original size"endl;
  cout"2. Switch to black and white"endl;
  newline();
  cin>>x;
 
  if(x==1){
     newline();
     cout"Alright, now introduce the name of the file with its extension; example: new.jpg"endl; 
     newline();
     Image image;
     string img;
     cin>>img;
     image.read(img);
     image.minify();
     image.write("resized.jpg");
 }
  if(x==2){
     newline();
     cout"Alright, now introduce the name of the file with its extension; example: new.jpg"endl; 
     newline();
     Image image;
     string img2;
     cin>>img2;
     image.read(img2);
     image.quantize(colorspace.gray);
     image.write("blackandwhite.jpg");
 }      
 }
  catch( Exception &error_ )
    {
      cout "Caught exception: " error_.what() endl;
      return 1;
    }
  return 0;
}

 

 

#Project Advance 2.

So, right now I technically push even forward my programming skills, I mean…using imagemagick is a little bit hard, but today I compile some code and it runs!!!

Marco and I manage to resize the image to one half of its original size, but now we´re struggling with the grayscale functions and stuff, at least we have something to keep working on and we feel positive about the results in our final project.

We find some useful functions in the following pages:

http://www.imagemagick.org/script/perl-magick.php

http://www.imagemagick.org/Magick++/Color.html#ColorGray

 <Magick++.h> 
<iostream>
using namespace std;
using namespace Magick;

void newline(){
  cout<<endl;
}

int main(int argc,char **argv)
{
  InitializeMagick(*argv);
  try{
  int x;
  cout<<"Hi, Im a manipulator of images "<<endl;
  newline();
  cout<<"What do you want to do? (press the number in your keyboard) "<<endl;
  newline();
  cout<<"1. Rezise the image to one half of its original size"<<endl;
  cout<<"2. Switch to black and white"<<endl;
  newline();
  cin>>x;
 
  if(x==1){
     newline();
     cout<<"Alright, now introduce the name of the file with its extension; example: new.jpg"<<endl; 
     newline();
     Image image;
     string img;
     cin>>img;
     image.read(img);
     image.minify();
     image.write("resized.jpg");
 }
  if(x==2){
     newline();
     cout<<"Alright, now introduce the name of the file with its extension; example: new.jpg"<<endl; 
     newline();
     Image image;
     string img2;
     cin>>img2;
     image.read(img2);
     image.quantize(colorspace.gray);
     image.write("blackandwhite.jpg");
 }      
 }
  catch( Exception &error_ )
    {
      cout << "Caught exception: " << error_.what() << endl;
      return 1;
    }
  return 0;
}

The first option is the only one that works, we are going to keep working with the colors.

See you later!

What should you work on?

Week #12 and more partial exams for you.

For this week's readings:
C++ (TC1017) should either be looking at support for your project, ImageMagick C++ libraries are a good start.
Python (TC1014) should be finishing chapter 11 (Dictionaries).