Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java Exercises: 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 accept an integer and find the sum of all the elements from all possible subsets of a set formed by 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:

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

Java Code Editor:

Company:  Bloomberg

Contribute your code and comments through Disqus.

Previous: Write a Java program to rearrange the alphabets in the order followed by the sum of digits in a given string containing uppercase alphabets and integer digits (from 0 to 9).
Next: Write a Java program to find the all positions of a given number in a given matrix. If the number not found print ("Number not found!").

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe