15
The while statement The while statement has the form: while(condition) Begin // code to execute End * condition is a boolean statement that is checked each time after the final "End" of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the while statement does not execute again. As an example, let's say that we wanted to write all the even numbers between 11 and 23 to the screen. Begin // this variable holds the present number int current_number = 12; // while loop that prints all even numbers between // 11 and 23 to the screen while (current_number < 23) Begin print "current_number" current_number += 2 End print "all done" End

Algoritmia

Embed Size (px)

Citation preview

Page 1: Algoritmia

The while statement

The while statement has the form:

while(condition) Begin // code to execute End

* condition is a boolean statement that is checked each time after the final "End" of the while statement executes. If the condition is true then the while statement executes again. If the condition is false, the while statement does not execute again.

As an example, let's say that we wanted to write all the even numbers between 11 and 23 to the screen.

Begin // this variable holds the present numberint current_number = 12;

// while loop that prints all even numbers between // 11 and 23 to the screen while (current_number < 23) Begin print "current_number" current_number += 2 End print "all done"End

The preceding example prints the value of current_number to the screen and then adds 2 to its value. As soon as the value of the variable current_number goes above 23, the while loop exits and the next line is executed.

The output of the preceding program would be:

121416182022all done

Page 2: Algoritmia

The do-while statement executes a statement repeatedly until the specified termination condition (the expression) evaluates to zero. The test of the termination condition is made after each execution of the loop; therefore, a do-while loop executes one or more times, depending on the value of the termination expression. The do-while statement can also terminate when a break, goto, or return statement is executed within the statement body.

The expression must have arithmetic or pointer type. Execution proceeds as follows:

1. The statement body is executed. 2. Next, expression is evaluated. If expression is false, the do-while statement

terminates and control passes to the next statement in the program. If expression is true (nonzero), the process is repeated, beginning with step 1.

Here is a simple example of the use of while. This program counts from 1 to 100.

begin    int count = 1

    do    Begin        print count        count += 1;                               /* Shorthand for count = count + 1 */    End            while (count <= 100)

C/C++ Language ReferenceThe break Statement

break;

The break statement terminates the execution of the nearest enclosing loop or conditional statement in which it appears. Control passes to the statement that follows the terminated statement, if any.

break is used with the conditional switch statement and with the do, for, and while loop statements.

In a switch statement, break causes the program to execute the next statement after the switch. Without a break statement, every statement from the matched case label to the end of the switch, including the default, is executed.

In loops, break terminates execution of the nearest enclosing do, for, or while statement. Control passes to the statement that follows the terminated statement, if any.

Page 3: Algoritmia

Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control from within more deeply nested structures.

The following example illustrates the use of the break statement in a for loop:

#include <stdio.h>

void main(){

int i;

for (i = 1; i < 10; i++)

{

printf("%d\n", i);

if (i == 4)

break;

}

}  // Loop exits after printing 1 through 4

C/C++ Language ReferenceThe goto Statement

goto label:

...

label: statement

The goto statement performs an unconditional transfer of control to the named label. The label must be in the current function.

A statement label is meaningful only to a goto statement; in any other context, a labeled statement is executed without regard to the label.

A jump-statement must reside in the same function and can appear before only one statement in the same function. The set of identifier names following a goto has its own name space so the names do not interfere with other identifiers. Labels cannot be redeclared.

It is good programming style to use the break, continue, and return statement in preference to goto whenever possible. Since the break statement only exits from

Page 4: Algoritmia

one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop.

This example demonstrates the goto statement:

#include <stdio.h>

void main()

{

int i, j;

for ( i = 0; i < 10; i++ )

{

printf( "Outer loop executing. i = %d\n", i );

for ( j = 0; j < 2; j++ )

{

printf( " Inner loop executing. j = %d\n", j );

if ( i == 3 )

goto stop;

}

}

/* This message does not print: */

printf( "Loop exited. i = %d\n", i );

stop: printf( "Jumped to stop. i = %d\n", i );

}

In this example, a goto statement transfers control to the point labeled stop when i equals 3.

For more information about labels and the goto statement, see Labeled Statements and Using Labels with the goto Statement.

Page 5: Algoritmia

Grammarstatement :

labeled-statement jump-statement

jump-statement : goto identifier ;

labeled-statement : identifier : statement

C/C++ Language ReferenceThe return Statement

return [expression]

The return statement terminates the execution of a function and returns control to the calling function (or, in the case of the main function, transfers control back to the operating system). Execution resumes in the calling function at the point immediately following the call.

The value of expression, if present, is returned to the calling function. If expression is omitted, the return value of the function is undefined. Functions of type void, constructors, and destructors cannot specify expressions in the return statement; functions of all other types must specify an expression in the return statement.

The expression, if specified, is converted to the type specified in the function declaration, as if an initialization were being performed. Conversion from the type of the expression to the return type of the function can cause temporary objects to be created. See Temporary Objects in Chapter 11 for more information about how and when temporaries are created.

When the flow of control exits the block enclosing the function definition, the result is the same as it would be if a return statement with no expression had been executed. This is illegal for functions that are declared as returning a value.

A function can have any number of return statements.

The following example uses an expression with return to obtain the largest of two integers.

#include <stdio.h>

int max ( int a, int b )

{

return ( a > b ? a : b );

Page 6: Algoritmia

}

void main()

{

int nOne = 5;

int nTwo = 7;

printf("\n%d is bigger\n", max( nOne, nTwo ));

}

Page 7: Algoritmia

EJERCICIOS #1

1. Escríba un algortimo que, tomando como entrada un número de 3 cifras (multiplicando) y otro de 2 (multiplicador) muestre el producto de la forma en que se vería si se hiciera a mano. Por ejemplo, dados 739 y 12, debe mostrar en pantalla: 739x 12------ 1478 739------ 8868 2. Escriba un algoritmo que lea tres números e imprima por pantalla el menor de ellos. 3. Escriba un algoritmo que calcule el área de un trapecio. Determine cuales son las entradas que requiere. 4. Escriba un algoritmo que lea tres números positivos y compruebe si son iguales. Por ejemplo: Si entrada es 5 5 5, la salida es "hay tres números iguales a 5''.Si entrada es 4 6 4 o 4 4 6 o 6 4 4, la salida es "hay dos números iguales a 4''. Si entrada es 0 1 2, la salida es "no hay números iguales''. 5. Escriba un algoritmo que lea las coordenadas (x,y), de dos puntos en el plano cartesiano y determine la distancia entre los dos puntos. 6. Escriba un algoritmo que lea tres números y los imprima en pantalla ordenados ascendentemente. 7. Escribir un algoritmo que determine el área y la longitud de un círculo, conociendo el radio del círculo. 8. Mediante un algoritmo, determinar la cantidad de dinero que recibirá un trabajador en una semena por concepto de las horas extras trabajadas en una empresa, sabiendo que cuando las horas de trabajo exceden de 40, el resto se consideran horas extras y que éstas se pagan al doble de una hora normal cuando no exceden de 8; si las horas extras exceden de 8 se pagan las primeras 8 al doble de lo que se paga por una hora normal y el resto al triple. Los datos de entrada son las horas trabajadas en la semana y el sueldo básico devengado en el mes. 9. Escriba un algoritmo que determine si una persona es mayor de edad o menor de edad conociendo su edad.

Page 8: Algoritmia

10. En una playa de estacionamiento cobran $1500 por hora o fracción. Diseñe un algoritmo que determine cuanto debe pagar un cliente por el estacionamiento de su vehículo, conociendo el tiempo de estacionamiento en horas y minutos.

11. Cual es el resultado de las siguientes expresiones?: a. IVA * IVA - 4 * TASA *PVP con IVA=7, TASA=3,PVP=2b. a + 7 * c / b + 2 * a + 2 * b con a=3,b=6,c=4c. 15 % 3 * 8 / 2 + 4 % 2d. 21 % 6 / 4 * 5 + 6 - 8e. (20 / 4) * 4 + (6 + (9 / 3))f. (11 % 3) / ((2 % 4) * 3) + 6g. 7 * 4 - 9 ** 2 / 4 % 8 + 6 / 5h. !(7 == 4 * 7 - 6) || 4 - 9 ** 2 > 4 && 8 + 6 / 5 < 7 - 3 ** 3

Page 9: Algoritmia

EJERCICIOS#2

Estos son los ejercicios para preparar Estructuras Repetitivas

1. Leyendo como datos los salarios de 23 empleados de una empresa, obtenga el total de la nómina de la misma. Considere si se le debe pagar o no subsidio de transporte, e inclúyalo en el cálculo.

2. Dados N, números enteros, obtenga el número total de números pares entregados. (N es un valor leído).

3. Se desea totalizar el valor de los gastos efectuados en un viaje. Escriba un programa que lea uno a uno los gastos para totalizarlos al momento en que el usuario indique que el viaje ha terminado.

4. Se tienen las calificaciones de un grupo de alumnos que presentaron un examen. Escriba un programa que le permita al profesor establecer el promedio de calificaciones del grupo, cual fue la mayor y la menor nota del mismo. El programa debe permitir continuar utilizando el ejercicio hasta que el usuario lo decida.

5. Escriba un programa, que dados 270 números enteros, obtenga la sumatoria de los números impares y el promedio de los números pares.

6. Escriba un programa, que dados como datos N números enteros, determine cuantos de ellos son positivos, cuantos negativos y cuantos iguales a cero.

7. Escriba un programa que lea un número entero N y calcule el resultado de la

siguiente serie: 1 + ½ + 1/3 + ¼ + … + 1/N.

8. Escriba un programa que lea un número entero N y calcule el resultado de la

siguiente serie: 1 - ½ + 1/3 - ¼ + … + - 1/N.

9. Calcule el aumento de sueldos para N empleados de una empresa, bajo el siguiente criterio: Si el sueldo es menor a $600.000 aumento del 12%, Si el sueldo está comprendido entre $600000 y $2500000 inclusive aumento del 10%, Si el sueldo es mayor a $2500000 aumento del 8%. Imprima El nuevo sueldo del trabajador y el monto de la nómina considerando el aumento.

10 Escriba un programa que determine si un número leído, pertenece al conjunto de los números primos o no.

11. Escriba un programa tal, que dado el peso, la altura y el sexo de N personas, determine el promedio del peso y de la altura, para cada sexo del grupo poblacional.

Page 10: Algoritmia

12. Se tienen calificaciones de un grupo de alumnos que presentaron examen de computación. Escriba el programa que cuantifica el número de calificaciones en los siguientes rangos: 0 ...1.99, 2 … 2.99, 3 … 3.99, 4 … 5.

13. Una persona invierte en un banco un cierto capital, y quiere saber cuánto obtendrá al cabo de cierto tiempo (en meses), si el dinero se colocó a una determinada tasa de interés mensual. Escriba el programa correspondiente.

14. Escriba un programa que lea un número entero N y calcule la sumatoria de la siguiente serie: 11 + 22 + 33 + … + NN.

15. Haga un programa que calcule, un número N de términos de la serie FIBONACCI. Recuerde: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …,

16. Supóngase que en una reciente elección hubo cuatro candidatos (con identificadores 1,2,3,4). Usted habrá de encontrar, mediante un programa, el número de votos correspondiente a cada candidato y el porcentaje que obtuvo con respecto al total de los votantes. El usuario tecleará los votos de manera desorganizada, tal y como se obtuvieron en la elección, el final de datos está representado por un cero.

17. De una empresa con N empleados, se necesita obtener el número del empleado y sueldo del trabajador con el mayor sueldo de la empresa.

18. Escriba un programa que lea un número entero, y una clave alfabética. Si la clave digitada es B el programa debe entregar el correspondiente binario del número leído, si la clave es O el correspondiente octal y si la clave es X el correspondiente hexadecimal.

19. Escriba un programa que genere e imprima todos los números impares de tres cifras que existan.

20. Escriba un programa que lea un número entero para una tabla de multiplicar y el número de términos a realizar. El programa debe imprimir la tabla con la totalidad de los términos indicados y permitirle al usuario la posibilidad de seguir calculando tablas.