user3129682
user3129682

Reputation: 23

infinite loop when asking for number

Hi all thanks for taking the time, I am continuosly getting an infinate loop when i am inserting the variable m could anyone please take a look thanks.

public static void main program7_2(String args [])
{
    Scanner sc = new Scanner (System.in);
    System.out.println("Please enter the first number: ");
    int n = sc.nextInt();
    while((n%2)== 0)
    {
        System.out.println("The number you entered is incorrect please enter an odd number:");
        n = sc.nextInt();
    }
    System.out.println("Please enter the second number: ");
    int m = sc.nextInt();
    while((m%2)== 0)
    {
        System.out.println("The number you entered is incorrect please enter an odd number:");
        m = sc.nextInt();
    }

    int sum =0;

    for (int i = n; n<=m; i++)
    {
        if ((i%2) != 0)
            sum = sum + i;
    }
    System.out.println("Sum of the numbers between "+n+ " and " +m+": " + sum);
}

The problem of the program is to enter 2 odd numbers and get the sum of the odd numbers in between

Thanks and regards

Upvotes: 0

Views: 95

Answers (3)

SUBZ
SUBZ

Reputation: 139

if u want to get the sum of nubers between those two use

public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the first number: ");
        int n = sc.nextInt();
        while ((n % 2) == 0) {
            System.out.println("The number you entered is incorrect please enter an odd number:");
            n = sc.nextInt();
        }
        System.out.println("Please enter the second number: ");
        int m = sc.nextInt();
        while ((m % 2) == 0) {
            System.out.println("The number you entered is incorrect please enter an odd number:");
            m = sc.nextInt();
        }

         int sum= 0;        

        for (int i = n; i <= m; i++) {

                    sum = sum + i;
        }
        System.out.println("Sum of the numbers  between  " + n + " and " + m + ": " + sum);
    }
}

Upvotes: 0

NoobEditor
NoobEditor

Reputation: 15881

This is the error :

for (int i = n; n<=m; i++) /* terminating condition "n<=m" is never met here */
{
    if ((i%2) != 0)
        sum = sum + i;
}

Why : this loop increments i but terminating condition is n<=m which is never met....so either do i<n Or i<m which ever suits you for terminating the condition!!

Upvotes: 1

vandale
vandale

Reputation: 3650

Instead of n<=m in your for loop use i<=m since you are using i as your counter and not n

Upvotes: 3

Related Questions