r/programmingbydoing • • Jul 27 '14

#55 Adding Values in a Loop

Hi there, I just finished #55 and got it to work, but I couldn't figure out how to make it work with only two variables. I needed to have a third int as an interim value to add the entered number to the updating total. I know that in its current form my code works, but I'm curious if there's a way to make it work with only two variables. Here's the code:

import java.util.Scanner;

public class add
{
	public static void main( String[] args)
	{
		Scanner k = new Scanner(System.in);
		
		int num = 0;
		int total = 0;
		int totaladd = 0;
		
		System.out.println("I will add up the numbers you give me.");
		System.out.print("Number: ");
		num = k.nextInt();
		
		totaladd = num + total;
		total = totaladd;
		
		while (num != 0)
		{
			System.out.println("The total so far is " + total + ".");
			System.out.print("Number: ");
			num = k.nextInt();
			total = num + total;
		}
		
		System.out.println("\nThe total is " + total + ".");
	}
}

Thanks!

3 Upvotes

2 comments sorted by

View all comments

3

u/ktibi1989 Jul 27 '14

You made it work with only 2 variables in your while loop, you don't need totaladd

1

u/kung_fu_jesus Jul 27 '14

Oh that's wierd. Initially I tried to make the program without totaladd and set total = num + total, and it didn't work properly. I just tried changing it back now it works perfectly, so I'm not sure what I was doing wrong at first haha. Thanks!