skip to Main Content

I wanted it to look like this:

preferred

And here’s my result:

actual

This is my code

private static void Main(string[] args)
{
    Console.WriteLine("CASHIER");
    Console.WriteLine("Enter Quantity of Products: ");
    
    int qty = Convert.ToInt32(Console.ReadLine());

    if (qty > 5)
    {
        Console.WriteLine("Maximum of 5 products");
    } 
    else 
    {
        int i = 1;

        while (i <= qty)
        {
            Console.WriteLine(i);
            i++;

            Console.WriteLine("Enter Price: ");
            int price = Convert.ToInt32(Console.ReadLine());

            int total = + price;
            Console.WriteLine("Total: " + total);
        }
    }
}

2

Answers


  1. Not sure, that I fully understand your question.
    But you should consider declaring your total outside your loop and doing total +=

        int i = 1;
        int total = 0;
        while (i <= qty)
        {
            Console.WriteLine(i);
            i++;
            Console.WriteLine("Enter Price: ");
            int price = Convert.ToInt32(Console.ReadLine());
    
            total += price;
            Console.WriteLine("Total: " + total);
        }
    
    Login or Signup to reply.
  2. Your

    int total = + price;
    

    inside the loop redeclares total as a new variable each time your loop executed its block and you always assign price in a positive manner to it instead of adding price to the previous total. The solution is to:

    • declare total outside the loop and initialize it with 0
    • add price to it at each step
    private static void Main(string[] args)
        {
            Console.WriteLine("CASHIER");
            Console.WriteLine("Enter Quantity of Products: ");
            
            int qty = Convert.ToInt32(Console.ReadLine());
    
            int total = 0;
    
            if (qty > 5){
                Console.WriteLine("5 Maximum Products");
            } else {
                int i = 1;
                while (i <= qty ){
                    Console.WriteLine(i);
                    i++;
                Console.WriteLine("Enter Price: ");
                int price = Convert.ToInt32(Console.ReadLine());
    
                total += price;
                Console.WriteLine("Total: " + total);
                }
            }
        }
    

    If you want to show total only once, at the very end, you need to move your last Console.WriteLine outside (after) the loop.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search