Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

While loop to For loop

for loop loop

  • Please log in to reply
1 reply to this topic

#1 yourmom615

yourmom615

    CC Regular

  • Just Joined
  • PipPipPip
  • 33 posts

Posted 12 March 2011 - 01:56 PM

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.

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

  • 0

#2 Simonxz

Simonxz

    CC Regular

  • Just Joined
  • PipPipPip
  • 42 posts

Posted 12 March 2011 - 06:30 PM

You would do something like this :

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

  • 0





Also tagged with one or more of these keywords: for loop, loop

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download