Tag Archives: #include

Mastery 25

Creation and use of strings in C++

C++ provides following two types of string representations:

  • The C-style character string.

  • The string class type introduced with Standard C++.

The String Class in C++:

The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. We will study this class in C++ Standard Library but for now let us check following example:

At this point, you may not understand this example because so far we have not discussed Classes and Objects. So can have a look and proceed until you have understanding on Object Oriented Concepts.

When the above code is compiled and executed, it produces result something as follows:

Credits:

http://www.tutorialspoint.com/cplusplus/cpp_strings.htm

1017 25

Mastery 23

Creation and use of vectors in C++

Vector

 

Vectors are sequence containers representing arrays that can change in size.

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, vectors do not reallocate each time an element is added to the container.

Example

Output:

Credits:

http://www.cplusplus.com/reference/vector/vector/vector/

http://www.cplusplus.com/reference/vector/vector/

1017 23

Mastery 20

Use of loops with “for”

for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

The syntax of a for loop in C++ is:

Here is the flow of control in a for loop:

  • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

  • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.

  • After the body of the for loop executes, the flow of control jumps back up to theincrement statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

  • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.

Flow Diagram:

Mastery 20

Example:

When the above code is compiled and executed, it produces the following result:

Credits:

http://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

1017 20

Mastery 19

Use of loops with “while”

while loop statement repeatedly executes a target statement as long as a given condition is true.

Syntax:

The syntax of a while loop in C++ is:

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

Flow Diagram:

Mastery 19

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:

When the above code is compiled and executed, it produces the following result:

Credits:

http://www.tutorialspoint.com/cplusplus/cpp_while_loop.htm

1017 18 

Mastery 18

Nesting of conditional statements

It is always legal to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).

Syntax:

The syntax for a nested if statement is as follows:

 

You can nest else if…else in the similar way as you have nested if statement.

Example:

When the above code is compiled and executed, it produces the following result:

Credits:

http://www.tutorialspoint.com/cplusplus/cpp_nested_if.htm

1017 18

Creation and use of arrays in C++ #Mastery24

Arreglos 

Podemos relacionas los arreglos con cajas, estas cajas a la vez pueden tener dentro mas cajas chicas y en cada caja se guarda un dato. 

Esa es la utilidad que tienen los arreglos, supongamos que tenemos cierto numero de estudiantes, por ejemplo 20, y queremos crear una variable para la calificacion de cada uno, tardariamos demasiado en crear 20 variables diferentes para cada uno; por lo que la solucion mas practica seria crear un arreglo para las 20 variables. Como antes explicamos la caja grande seria el arreglo, las cajas mas chicas estan representadas por la variable de la calificacion y dentro de esta  variable podemos ingresar un dato.

Ahora que entendimos que es un arreglo y cuando podemos usarlos, veremos como crear uno:

1- Elegir el tipo de variables a guardar en nuestro arreglo.

2- Definir el numero de datos que necesitamos guardar.

3- Ahora tenemos que comenzar a programar el codigo, esto es sencillo, muy parecido a crear variables.

4- Cuando ya tengamos los datos necesarios de los pasos anteriores debemos tomar en cuenta que el numero de espacios siempre tiene que estar entre corchetes “[ ]”.

5- Hay que tomar en cuenta que a la hora de ingresar el numero de espacios, estos se cuentan desde el 0, por lo que si queremos ingresar los 20 espacios, dentro de los corchetes tenemos que escribir 19.

Ejemplo:


using namespace std
int main ( )
{
int arreglo [19];         // En este arregloe las variables son tipo int y cuenta con 20 espacios

arreglo[0]=80;          // Aqui le estamos asignando a la casilla numero 0 el valor de 80

arreglo[19]=100;        //Finalmente asignamos el valor del espacio 19, ultimo espacio dentro de                                                        nuestro arreglo 

return 0;

 

De esta forma podemos crear arreglos, y para hacer mas eficiente la manera de ingresar los datos se recomienda usar algun loop. Ya que dentro de los corchetes del arreglo se pueden ingresar variables como en el siguiente ejemplo: arreglo[alumnos]

 

1017 24

Mastery 28

28 1017

Como leer o escribir en documentos en 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

//Reference: http://www.cplusplus.com/doc/tutorial/files/

 

usingnamespacestd;

 

int main () {

  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

//Reference: http://www.cplusplus.com/doc/tutorial/files/

usingnamespacestd;

 

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 tenemos que usar la libreria fstream y string,

 

abril archivo con el comando ifstream y leer cada linea con el get line y este guardara cada linea.

Use of loops with “while” – Mastery 19

Como usar un loop con “while”

Antes de empezar tenemos que saber que es un loop; es una serie de acciones que se repiten en este caso, con ayuda del while, las instrucciones dentro del loop van a repetirse mientras algo este pasando, como en el siguiente ejemplo:

 
 
   
  using namespace std;
   
  int main()
  {
  int sec, num, cont =0;
  srand(time(NULL));
  sec = rand()%100+1;
   
  while(num != sec){
  cout
  cin >> num;
   
  if (num > sec){
  cout
  }
  if (num
  cout
  }
  cont++;
  }
   
  cout
  cout
   
  return 0;

 

En el ejempo anterior existe un loop con while, este nos indica que mientras la condicional sea false, todo el loop va a repetirse, pero si el usuario ingresa un numero correcto que para nuestro codigo seria el 42, la variable num seria true, por lo que la condicion del while ya no se cumple y el loop se saldria y el programa continuaria corriendo.

1017 19

#Mastery28 #TC1017

Como leer o escribir en documentos en 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 tenemos que usar la libreria fstream y string, abril archivo con el comando ifstream y leer cada linea con el get line y este guardara cada linea.

Creating C++ functions – Mastery12

*Crear una funcion es facil. El proceso para crear una es el siguiente:

1- Se programa la unción

2- Se define la función

3- Se utiliza la función en el programa principal.

 

*Su estructura es la siguiente:

Creating C++ functions - Mastery12

 

Por ejemplo:

using namespace std;

int factorial(int a){

int cont, act = 1;

for (cont =1; cont

{

fact = fact*cont;

}

return fact;

}

 

int main(){

int num1;

int resultado = factorial (num1);

cout

cin num1;

cout

return 0;

}

 

 

Si tienen dudas pueden consultar el siguiente enlace: http://aprendecpp.com/blog/programacion-en-c-como-crear-funciones-i.html

1017 12