pratirup mukherjee
pratirup mukherjee

Reputation: 53

How to add the numbers displayed

Now how do i add the numbers displayed and print them ?
i got how to display them but cant figure out how to add the number please would be a great help for my project

import java.util.Scanner;

public class ReadNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Number: \n");
        int n = sc.nextInt();
        int i = 0;
        while(i <= n){
            System.out.print(i);
            if(i == n){
            System.out.print("=");
            }
            else{
            System.out.print("+");
            }
            i++;
        }
    }
}

Upvotes: 0

Views: 57

Answers (2)

castletheperson
castletheperson

Reputation: 33526

You need another variable for the running total. To be more concise, use a for loop, and handle the i == n outside of the loop.

Scanner sc = new Scanner(System.in);
System.out.println("Enter Number: \n");
int n = sc.nextInt();
int i = 0, sum = n;
for (int i = 0; i < n; i++) {
    sum += i;
    System.out.print(i + "+");
}
System.out.println(n + "=" + sum);

Upvotes: 1

You can create another variable int sum to update the sum of all i's with each loop iteration:

import java.util.Scanner;

public class ReadNumber {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter Number: \n");
        int n = sc.nextInt();
        int i = 0;
        int sum = 0;    // Create a sum variable
        while(i <= n){
            System.out.print(i);
            sum+=i;     // Add `i` to sum
            if(i == n){
                System.out.print("=");
                System.out.println(sum); // Display `sum` after loops finish
            }
            else{
                System.out.print("+");
            }
            i++;
        }
    }
}

Upvotes: 0

Related Questions