While will not end after user enters

32 views Asked by At

Everything runs fine. However, I need the loop to end contingent upon how many numbers the user enters in the first question.

using System;

namespace Looping
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How many numbers will you provide?");
            int numbersProvide = Convert.ToInt32(Console.ReadLine());

            int i = 0;

            while (i <= numbersProvide)

            {
                Console.WriteLine("Please enter number:");
                int firstNum = Convert.ToInt32(Console.ReadLine());

                int j;
                int sum = 0;
              
                double addDiv;

                for (j = 1; j <= 25; j++)
                {
                    
                    if (firstNum % j == 0)
                    {
                       addDiv = firstNum / j;
                       Console.WriteLine(firstNum + " is divisible by " + j + "(" + addDiv + ")");
                        sum += j;

                    }
                }
                Console.WriteLine("The sum of the quotient is: " + sum);

            }
            Console.ReadKey();
        }
    }
}
1

There are 1 answers

2
Thomas Weller On

You set int i = 0; and i never increases. Nor does numbersProvide decrease.

Since you have a fixed amount of times that the loopo shall run, a for loop is much more suitable for the situation than the while loop you have. Use while loops if you don't know how often the loop will run. Use for loops, if you know the number of runs in advance.

A typical for loop will combine your declaration (int i=0), the condition (i <= numbersProvide) and the missing increment (i++) in one line.

for (int i=0; i<=numbersProvide; i++)

When seeing that, I immediately recognize that the loop is off by one and it should be

for (int i=0; i<numbersProvide; i++)