What is a sentinel value What is the format for a while loop W.docx
1. What is a "sentinel value"? What is the format for a while
loop? What is the format for a do-while loop? .Write some
instructions which will read a series of numbers (type double)
and add them to a total until the number -1 is entered The - 1 is
not added to the total. Write some instructions which will read
a series of numbers (type double) and add them to a total until
the character control-d is entered. Write a loop that will print
10 lines of output The output-is a table converting miles to
kilometers (each mile is 1.609 kilometers). Use a counter to
count the miles from 1 to 10 and print the distance in miles and
kilometers. For example, the first line of output should be. 1
mile = 1.609 kilometer. Write some code (including a loop)
that will read numbers from the user and count how many
numbers are positive and how many are negative. When the user
enters a zero, end the loop and print the totals. Explain what
the following instructions do. Explain what the following
instructions do.
Solution
a) sentinel is any value which is not in your data set so as to
mark the termination condition.
for example if the score is always greatter than or equal to 0
then -100 can be used as sentinel value to show the termination
case.
b) while loop is used when we need to execute a
statement/statements repeatedly until it is true.
2. while(Boolean_expression)
{
//Statements
}
Do while loop:
Do while loop is similar to while loop but in do while will be
executed atleast once.
do
{
//statements
while(Boolean expression);
16,18)
import java.util.Scanner;
public class list_of_numbers {
public static void main ( String[] args) {
int positive = 0;
int negetive = 0;
int sum = 0;
int count =0;
Scanner input = new Scanner (Sysytem.in);
System.out.println ("ënter a value, if 0 is entered program
stops:");
int data = input.nextInt();
while(data ! =0) {
sum+= data;
3. if(data<0)
negetive++;
else if (data > 0)
positive++;
count++;
data = input.nextInt();
}
System.out.println("the number of positive numbers
is:"+positive);
System.out.println("the number of negtive numbers is
:"+negetive);
System.out.println("the total is : "+sum);
}
20) this method is not adviced because Q and q have ASCII
values of 81,113 so chance of going into an infinite loop is
there so always better to use 0 as termination condition.exit(0)
can be used.