This C# program needs to add only positive values USING A DO WHILE LOOP ONLY . I
ID: 3792203 • Letter: T
Question
This C# program needs to add only positive values USING A DO WHILE LOOP ONLY. If there is a negative value it has to be ignored. Any thoughts on how to do that?
The output should look like this:
Output:
Item1: $2.00 (Enter 1st value)
Item 2:: $3.00 (Enter 2nd value)
Item 3: $1.00 (Enter 3rd value. Other positive values can be entered after this)
Item 4: $-2 (Note: A negative number will not be substracted in the subtotal. It will only be ignored)
There are 3 Items in this order (This is the total ITEM count)
Subtotal: $6.00 (This are the values of Items 1, 2,3)
Tax 0.035: $0.21(This is the subtotal multiplied to 0.035)
Total: $6.21(This is the sum of Subtotal and Tax)
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
decimal Count = 0.00m;
decimal price = 0.00m;
decimal subtotal = 0.00m;
decimal tax = 0.00m;
decimal total = 0.00m;
do
{
Count = Count +1;
Console.Write ("Item"+ Convert.ToInt32(Count) + ": $");
price = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine (price);
subtotal = subtotal + price;
}
while (price > -1);
tax = (decimal)0.035 * subtotal;
total = tax + subtotal;
Count = Count -1;
Console.WriteLine ("There are "+ Count + " Items in this order.");
Console.WriteLine ("Subtotal: "+ subtotal);
Console.WriteLine ("Tax 0.035: "+ tax);
Console.WriteLine ("Total: "+ total);
}
}
Explanation / Answer
From the above program just try to keep a decision statement that checks, if(price<0) then continue loop
Program:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
decimal Count = 0.00m;
decimal price = 0.00m;
decimal subtotal = 0.00m;
decimal tax = 0.00m;
decimal total = 0.00m;
do
{
Count = Count +1;
Console.Write ("Item"+ Convert.ToInt32(Count) + ": $");
price = Convert.ToDecimal(Console.ReadLine());
if(price<0)
continue;
Console.WriteLine (price);
subtotal = subtotal + price;
}
while (price > -1);
tax = (decimal)0.035 * subtotal;
total = tax + subtotal;
Count = Count -1;
Console.WriteLine ("There are "+ Count + " Items in this order.");
Console.WriteLine ("Subtotal: $"+ subtotal);
Console.WriteLine ("Tax 0.035: $"+ tax);
Console.WriteLine ("Total: $"+ total);
}
}
Output:
Item1: $2
2
Item2: $3
3
Item3: $1
1
Item4: $-2
There are 3.00 Items in this order.
Subtotal: $6.00
Tax 0.035: $0.21000
Total: $6.21000
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.