Skip to main content

Processing

Types of operations

The operations to be performed with the data can be:

  • Arithmetic: classic operations of addition, subtraction, multiplication and division or maths operations.
  • Logics: comparisons, negation, AND, OR.
  • Concatenation: union of several elements (strings of characters or variables of different types)
  • Loops: Involves performing actions repeatedly. In this case it will be convenient to distinguish two types:
    • Previously known number of times to repeat the action: we will use the For or Repeat structures.
    • Number of times to repeat depending on values obtained: we will use the structures While (While...do) or Repeat until (Do...while), depending on whether we want to evaluate the condition before or after the first iteration. We will see that these structures are conditional as well as repetitive.
  • Conditional: implies carrying out some actions or others by making decisions. Structures If-then (If-else),  and Switch.

We have already seen the first three types of operations in the previous examples. We will now focus on the last two, although we will introduce various operations in the examples to delve into their use.

Iterations and loops

To practice with these structures, we will create a simple program that will calculate the average of several numbers (marks, for example). First, the program requests the number of marks to average, then it asks that the marks be entered as many times as we have told it (here is the repetition). At the end, it shows the average. In this case, since the number of iterations is known, we will use the FOR statement. Likewise, we will use arithmetic and concatenation operators.

Steps 1 and 2: Analysis and flow chart of the Average of n marks program

The elements involved are:

  • Start and end of algorithm.
  • Outputs: Request number of marks, show average.
  • Inputs: number of marks and marks to be averaged.
  • Storage: number of elements (integer), entered numbers (real number), cumulative sum of numbers (real number), and average (real number)
  • Processing: loop, addition and division.

The flowchart associated with the FOR instruction is as follows:

 

image-1663516782391.pngimagen.png

Flowchart:

image-1662139909769.pngimagen.png

Steps 3, 4 y 5: Coding, compilation and checking of the Average of n marks program with PSeInt

As we saw in the previous section, after renaming the algorithm, we begin by defining the variables involved by writing the expression Definir

image-1662140249122.pngimagen.png

PSeInt allows you to define several variables of the same type on the same line, separated with commas. As you can see, we have defined a single numi variable where we will save the number entered by the user each time.

Next we request the number of numbers to average (Escribir), we read the response and store it in the corresponding variable (leerand we initialize the value of accum to 0, although actually it would not be necessary since it is the value assigned by default.

image-1662141575309.pngimagen.png

With the value of nnum defined by the user comes the time for repetition: we will ask the user to enter a number nnum times. To do this we will use the For (Para) command available in the window on the right.

image-1662141816788.png

When we click on the command, the following instructions are written:

image-1662141863542.png

As variable numérica a local variable (i, j, k...) is usually defined, which acts as a counter. The initial value is 1 and the final value is the number of times we want to repeat the instruction. The step (Paso) specifies the growth of the counter from one iteration to another (in our case one by one)

Finally, in the  secuencia de acciones we have to put what we want to be repeated each time. In our case, request the number, read it and add it to the previous ones, saving the result in the accum variable.


image-1662142157986.pngimagen.png

The value of numi is refreshed and varies in each iteration, since we have already saved the value of the previous number in the accumulated one.

In a program it is very important to use the minimum number of necessary variables so as not to add unnecessary complexity to it. (KISS Principle of Software Design)

We have concatenated the numeric counter variable in the request message. This allows us to show the user what iteration they are on. The Escribir instruction followed by the elements to be concatenated separated by commas places them on the same line and without separation between them. That is why it is necessary to consider the separation spaces in the character strings that we include.

Finally, we assign the average value to the corresponding calculation and display the result again by concatenating two messages.

image-1662142637559.pngimagen.png

Finally we click Ejecutar and verify the process carried out.

image-1662142946677.gifaveragennum.gif

Again in the verification of the program we can experience the robustness of the program against errors, introducing decimal numbers with commas, negatives, etc... We invite you to do it and enter the necessary instructions to prevent errors.

Steps 3, 4 y 5: Coding, compilation and checking of the Average of n marks program with Scratch

In Scratch the blocks related to repetitive structures are found in Control and are Forever, Repeat and Repeat until.

imagen.png

In our cas, as the number of iterations is defined, we will use Repetir.

First of all, in the Variables block we will define the necessary variables.

imagen.png

In an analogous way, using the Sensing, Looks, and Variables blocks explained in the Inputs, Outputs and Storage sections, we build the program. In Operators we will find the blocks necessary to carry out arithmetic, logical and concatenation operations.

imagen.png

The final program with all the elements would look like this:

imagen.png

CondicionalesConditionals

ParaTo practicarpractice conwith estasthese estructuras,structures, realizaremoswe unwill pequeñocarry programa en el que tras solicitar una nota numérica, y verificar en primer lugar si el valor recibido es correcto, nos indicará si la nota correspondeout a unsimple APROBADOprogram oin unwhich SUSPENSO.
after requesting a numerical grade, and first verifying if the value received is correct, it will tell us whether the grade corresponds to a PASS or a FAIL.

PasosSteps 1 yand 2: AnálisisAnalysis yand diagramaflow dechart flujoof del programathe BoletínReport
program

LosInvolved elementoselements implicadosare: serán:

  • InicioStart yand finend deof algoritmo.algorithm. 
  • SalidasOutputs: SolicitarRequest calificaciónnumerical numérica,mark, mostrar calificaciónshow textual omark mensajeor deerror error.
    message.
     
  • EntradasInputs: calificaciónnumerical numérica
    mark
  • AlmacenamientoStorage: calificaciónnumerical numéricamark (númeroreal real,number, puedemay tenerbe decimales)
    decimal)
     
  • ProcesamientoProcessing: lógicaslogical (comparación,Y,O)comparison, yAND, condicionales.
    OR) and conditional

Diagrama de flujo:Flowchart:

image-1662145686642.pngimagen.png

EnIn estethis casocase hemoswe definidohave ladefined condición dethe error mediantecondition elusing operadorthe lógicological operator OOR, indicandoindicating quethat seany consideremark errónealess cualquierthan calificación menor que cerozero oor mayorgreater quethan 10.10 Esteis programaconsidered puedeerroneous. serThis resueltoprogram decan formabe análogasolved utilizandoin elan operadoranalogous way using the operator YAND, indicandoindicating quethat considereit válidaconsiders cualquierany notanumerical numéricamark mayorvalid ogreater igualthan queor ceroequal to zero yand menorless othan igualor queequal to 10. 

PasosSteps 3, 4 y 5: Codificación,Coding, compilacióncompilation yand verificaciónchecking delof programathe Report program Boletínwith con PSeIntPseint

EnFirst, primerwe lugarrename renombramosthe el algoritmoalgorithm (boletinReport enin nuestroour caso)case) yand definimosdefine lasthe variables implicadasinvolved, quewhich solois esonly lathe calificaciónnumerical numéricamark (nota_num)
nummark)
 

ANext continuaciónwe solicitamosrequest lathe calificaciónnumerical numéricamark (Escribir) yand laenter introducimosit enin lathe defined variable definida (Leer)

image-1663089130188.pngimagen.png

AhoraNow vendríait lacomes aplicaciónthe deapplication laof condición.the Loscondition. comandosThe encargadoscommands enin charge of entering the conditions in PSeInt de introducir las condiciones sonare Si-entonces, Según, Mientras yand Repetir. UnAn ejemploexample deof lathe sintaxissyntax deof cadaeach una seone puedecan apreciarbe enseen lain siguientethe figurafollowing figure

image-1663089429905.png

  • Si-entonces: verificaIt queverifies sethat cumplea unacondition condiciónis omet noor ynot enand funciónbased deon ellothis, ejecutait unasexecutes acciones.some Seactions. puedenSome anidarconditionals unascan condicionalesbe dentronested deinside otras.others.
  • SegúnseIt utilizais cuandoused unawhen a variable puedecan adoptaradopt una númerodiscrete discretonumber deof opcionesoptions (tipomenu menú)type) yand sethe definebehavior elis comportamientodefined antein ellasrelation yto antethem eland casoin dethe queevent nothat coincidait condoes ninguna.not match any of them.
  • Mientras: evalúevaluates a unacondition condiciónin ena bucleloop yand mientraswhile esit verdaderais ejecutatrue unaexecutes acción.an Mezclaaction. condicionalConditional yand bucle.loop mix.
  • Repetir-hasta que : ejecutaexecutes unaan acciónaction enin buclea hastaloop queuntil unaa condicióncondition seis cumplemet enat cuyowhich momentopoint seit interrumpe.is Mezclainterrupted. condicionalConditional yand bucle.loop mix.

EnIn nuestroour ejemploexample, lathe condicióncondition is only soloevaluated seonce, evalúaso unawe vezdiscard porthe lolast quetwo, descartamosand lasthe dosnumerical últimas,value yentered elcan valor numérico introducido puede tenerhave infinitosinfinite valoresvalues entrebetween 0 yand 1010, porso lothe quesecond laone segundais tampoconot esvalid válida.either. UsaremosWe entonceswill elthen comandouse the Si-entonces.entonces command.

VamosWe aare aprovechargoing parato introducirtake dosthe nuevosopportunity operadores,to elintroduce operadortwo new operators, the YAND representadooperator porrepresented elby carácterthe character & yand el operadorthe OOR representadooperator porrepresented laby doblethe barradouble slash || quewhich seare utilizanused cuandowhen queremoswe quewant semore evalúethan másone decondition unato condiciónbe simultáneamente.evaluated Ensimultaneously. nuestroIn casoour podemoscase considerarwe doscan opciones:
consider two options:

  • SiIf lathe notamark introducidaentered esis menorless quethan 0 oor mayorgreater quethan 10, noit tienedoes sentido,ynot make haysense, queand daran unerror mensajemessage demust error.be Engiven. casoOtherwise contrarioit habráwill quebe distinguirnecessary to distinguish (condicionalnested anidadaconditional) siif esit menoris queless than 5 yand entoncesthen elthe mensajemessage dictasays suspenso,FAIL, yand siif esit mayoris ogreater igualthan queor equal to 5 queit seráwill aprobado.be approved.

image-1663090532743.pngimagen.png

  • SiIf lathe notamark introducidaentered esis mayorgreater othan igualor queequal to 0 yand menorless othan igualor queequal to 10, esit correctais ycorrect hayand quewe distinguirmust distinguish (condicionalnested anidada)conditional) siif esit menoris queless than 5 oor mayor.greater. EnOtherwise, caso contrariothe sacarerror elmessage mensaje de error.appears.

image-1663090588263.pngimagen.png

Las dos son correctas y elegir una u otra solo dependerá de la persona programadora y si prefiere usar operadores Y u O.

image-1663091091215.pngBoth are right and choosing one or the other will only depend on the programmer and whether they prefer to use AND or OR operators.

FinalmenteFinally sólowe noswould quedaríaonly have to Ejecutarrun elthe programaprogram yand verificarverify suits correctocorrect funcionamiento.operation.

DejamosWe comoleave ejercicioit deas ampliaciónan elexpansion reformularexercise esteto programareformulate parathis queprogram sigaso preguntandothat hastait quecontinues recibaasking unauntil calificaciónit válida.receives Comoa pistavalid sugerimosgrade. explorarAs lasa posibilidadeshint dewe lasuggest instrucciónexploring the possibilities of  Repetir .and Mientras instructions.

PasosSteps 3, 4 y 5: Codificación,Coding, compilacióncompilation yand verificaciónchecking delof programathe Report program Boletín conwith Scratch

EnIn Scratch losthe bloquesblocks relacionadosrelated conto lasconditional estructurasstructures condicionalesare sefound encuentran enin Control,Control, juntonext ato losthe bucles.
loops.

image-1663091520009.pngimagen.png

LosThe operadoreslogical lógicosoperators YAND yand OOR seare encuentranfound enin OperadoresOperators, juntoalong conwith losthe decomparison comparaciónoperators yand losthose yaalready vistosseen anteriormente:previously: aritméticos,arithmetic, de concatenación.concatenation...

image-1663091770998.pngimagen.png

ComoAs enin todosall losprograms, programaswe empezaremoswill definiendostart lasby variablesdefining necesarias,the ennecessary nuestrovariables, casoin sóloour unacase desdeonly losone bloquesfrom dethe Variables. blocks. 

ANext continuaciónwe solicitaremoswill larequest calificaciónthe medianterating elusing bloquethe disponibleblock enavailable in SensoresSensing yand almacenaremoswe suwill respuestastore enits laresponse variablein reciénthe creada.
newly created variable.

Por últimoFinally, evaluaremoswe lawill respuestaevaluate obtenidathe medianteresponse elobtained bloquethrough correspondientethe decorresponding Control yblock utilizandoand losusing operadoresthe lógicoslogical deoperators of OperadoresOperators, segúndepending seaon sutheir valorvalue, ofreceremoswe elwill mensajeoffer dethe error omessage escribiremosor lawrite calificaciónthe final grade conwith elthe bloque correspondiente decorresponding Apariencia.Looks block. 

ElThe códigoresulting resultantecode seríawould elbe siguiente:
the following:

image-1663092570898.pngimagen.png

EnIn estethis casocase hemoswe utilizadouse el operadorthe OOR porqueoperator because Scratch nodoes disponenot dehave losthe operadorescombined combinadosoperators menorless othan igualor yequal mayorand ogreater igual,than yor asíequal, nosand ahorramosthus elwe tenersave queourselves combinarfrom amboshaving operadoresto concombine unboth operadoroperators lógicowith O.a Recordadlogical eloperator principioOR. KISS.
Remember the KISS principle.
 

PorFinally, último,we verificamosverify elthe correctocorrect funcionamientofunctioning delof programathe yprogram suand robustezits frenterobustness aagainst losthe erroresmost máscommon comunes.errors. EnIn Scratch we ejecutamosexecute haciendoby clicclicking sobreon lathe banderagreen verde.flag.

image-1663093519089.gifreport.gif