MrAwesome8
MrAwesome8

Reputation: 269

Using loops and ints

So I have a basic project that does this:

User inputs a number 1-10

program prints all numbers below it added together

For example:

user inputs 6

program prints " 1+2+3+4+5+6=21"

Here is what I have

import java.util.Scanner;

public class Loop {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int num;
        int sum = 0;
        int temp = 1;

        do {
            System.out.print("Enter a number 1-10: ");
            num = in.nextInt();
        } while (!(num > 0 && num <= 10));

        System.out.print("\n");


        while (temp != num) {
            System.out.print(temp + "+");
            sum += ++temp;
        }
        sum += 1;
        System.out.print(num + "=" + sum);
    }

}

Okay I changed the code

sum += ++temp;

now all the sums are one off?

I added sum += 1; after the while loop but is there another way to fix it?

Upvotes: 0

Views: 132

Answers (4)

Scorpion
Scorpion

Reputation: 587

I prefer using of For loop, you can do this with some fun ..

// number is the user input and you must validate it before

for (int i = number; i >= 1; i--) {
    if (i == 1) {
        System.out.print(i);
        sum = sum + 1;
    } else {
        System.out.print(i + " + ");
        sum = sum + i;
    }
}
System.out.print(" = " + sum);

Upvotes: 0

Morteza Adi
Morteza Adi

Reputation: 2473

just for fun use this function :)

  private static String oOo(int OoO) {
    if (OoO == 1) return "1";
    return oOo(OoO - 1) + "+" + String.valueOf(OoO);
  }

Upvotes: 0

Ashot Karakhanyan
Ashot Karakhanyan

Reputation: 2830

You have the temp variable to track the current number you're adding, but you don't ever change it. Change:

sum += ++temp;

instead of

sum += temp;

Upvotes: 3

rockStar
rockStar

Reputation: 1296

I might not be familiar with java, but i guess you can do the loop like this

int temp =0;
int inputedNumber = 6;
for(int a = 1; a <= inputedNumber; a++){
 temp += a;
}
cout << temp;

Upvotes: 0

Related Questions