Sum of Natural Numbers which are Divisible by 3 or 5


SUBMITTED BY: anilkumarsomasi

DATE: May 3, 2016, 3:13 a.m.

FORMAT: Text only

SIZE: 677 Bytes

HITS: 2488

  1. Sum of Natural Numbers which are Divisible by 3 or 5
  2. import java.util.Scanner;
  3. public class SumOf_n_NaturalNumbers {
  4. public static void main(String[] args) {
  5. int n;
  6. Scanner input = new Scanner(System.in);
  7. System.out.println("Enter Number :");
  8. n = input.nextInt();
  9. calculate_Sum(n);
  10. }
  11. public static void calculate_Sum(int n) {
  12. int i = 1, sum = 0;
  13. if (n % 3 == 0 || n % 5 == 0) {
  14. do {
  15. sum = sum + i;
  16. i += 1;
  17. } while (i <= n);
  18. System.out.print("Sum of First " + n + " Numbers = " + sum);
  19. } else
  20. System.out.print("not divisble by 3 or 5");
  21. }
  22. }
  23. Result:
  24. Input: Enter Number 4
  25. Ouput: not divisble by 3 or 5

comments powered by Disqus