In: Computer Science
Sentinel While Loop Lab
Convert Lab 11 from a counter controlled WHILE loop to a sentinel WHILE loop. Do the following:
Include the following:
NOTE 1:
NOTE 2:
1. Declare all variables within the data declaration section of
each class and method. (-.1)
2 Do not get input on the same line as a variable
declaration. (-.1)
3. Do not place an equation for computation on the same line as
declaring a variable. (-.1)
4. Do not place an equation for computation on the same line as an
output statement. (-.1)
Answer: Hey!! dear student kindly find your solution below.Let me know if any issue. Thanks.
Copy to code: This code asks for grades from user and continue asks until sentinel value is entered.After entering sentinel value,user display a message and average of the grades.
You didn't mention any language so C++ used here if any change you want just comment me in the comment box.
#include<iostream>
using namespace std;
int main()
{
int counter = 0;//declaration of varaibles
double grade,sum = 0,avg;
while(grade!=-1)//whle loop until sentinel value is
entered
{
cout<<"Enter grades:
";//prompts for grades
cin>>grade;
if(grade>0)//if grade not less
than 0
{
counter++;
//increment of counter
sum =
sum+grade;//sum of grades
}
else
if(grade==-1)//if sentinel vlaue is
entered
{
cout<<"User is done entering grades";//display message
}
}
if(counter!=0)//check counter if not equal to 0
{
avg = sum/counter;
}
cout<<"\nAverage of grades: "<<avg;
return 0;
}
Snapshot of code and output:
Java Code:
import java.util.*;
import java.util.Scanner;
class Main
{
public static void main(String[]args)
{
int counter = 0;//declaration of varaibles
double grade = 0,sum = 0,avg= 0.0;
Scanner sc = new Scanner(System.in);
while(grade!=-1)//while loop until sentinel value is entered
{
System.out.println("Enter grades: ");//prompts for grades
grade = sc.nextDouble();
if(grade>0)//if grade not less than 0
{
counter++; //increment of counter
sum = sum+grade;//sum of grades
}
else
if(grade==-1)//if sentinel vlaue is entered
{
System.out.println("User is done entering grades");//display
message
}
}
if(counter!=0)//check counter if not equal to 0
{
avg = sum/counter;
}
System.out.println("Average of grades: "+avg);
}
}