Jump to content

While loop to For loop

- - - - -

  • Please log in to reply
1 reply to this topic

#1
yourmom615

yourmom615

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
Need help getting this while loop to perforn in the same manner as a for loop. Any help greatly appreciated.


int n1, n2;


      Scanner input = new Scanner(System.in);

      System.out.println("Multiplication by repetitive addition\n");


      System.out.print("Please enter the first positive integer: ");

      n1 = input.nextInt();


      System.out.print("Please enter the second positive integer: ");

      n2 = input.nextInt();


      // multiplication through repetitive addition using a while loop

      int result  = 0;

      while (n2 > 0) {

          result += n1;

          n2--;

      }


      System.out.println("Multiplication result is " + result);


    }            

   

Above is the functioning while loop that allows the user to enter two integers and then using the loop adds them repeatedly to look like they have been multiplied

Below is what I have come up with. The result is the correct computation and the last system.out as n2

 int n1, n2;


      Scanner input = new Scanner(System.in);

      System.out.println("Multiplication by repetitive addition\n");


      System.out.print("Please enter the first positive integer: ");

      n1 = input.nextInt();


      System.out.print("Please enter the second positive integer: ");

      n2 = input.nextInt();


      // multiplication through repetitive addition using a for loop

      int result  = 0;

      for (result += n1; n2 > 0;  n2--){

      System.out.println("Multiplication result is " + result); 

      }

    }


Here what is returned when running the for loop in the second peice of code.

Quote

Multiplication by repetitive addition

Please enter the first positive integer: 4
Please enter the second positive integer: 2
Multiplication result is 4
Multiplication result is 4
BUILD SUCCESSFUL (total time: 5 seconds)

Any thoughts would be great!!!!!

Edited by yourmom615, 12 March 2011 - 05:31 PM.
Simpliying issues, to many at once


#2
Simonxz

Simonxz

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
You would do something like this :


		int result = 0;

		for (int i = n2; i > 0; i--) {

			result += n1;

		}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users