﻿ Java - Sum all values from all subsets by n natural numbers

# Java: Sum of all the elements from all possible subsets of a set formed by first n natural numbers

## Java Basic: Exercise-193 with Solution

Write a Java program that accepts an integer and sums the elements from all possible subsets of a set formed by the first n natural numbers.

Sample Solution:

Java Code:

``````import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Input a positive integer: ");
int n = in .nextInt();
int result = (n * (n + 1) / 2) * (1 << (n - 1));
System.out.print("Sum of subsets of n is : " + result);
}
}
```
```

Sample Output:

```Input a positive integer:  25
Sum of subsets of n is : 1157627904
```

Flowchart: Java Code Editor:

Company:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿

## Java: Tips of the Day

Java Classes

A Java class is declared with the keywords public class along with a unique class name mirroring its file name. For example, in a file Hello.java in project helloworld:

```package helloworld;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
* @author seth
* A GUI hello world.
*/

public class Hello {
// this is an empty class
}
```

You can declare variables and functions inside a class. In Java, variables within a class are called fields.

Ref: https://red.ht/3sL3sSl

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook