Write a function to print the sum of all odd numbers from 1 to n.


import java.util.*;

public class Solutions {

   public static void printSum(int n) {

       int sum = 0;

 

      for(int i=1; i<=n; i++) {

        if(i % 2 != 0) {

            sum = sum + i;

        }

      }

 

      System.out.println(sum);

   }

   public static void main(String args[]) {

      Scanner sc = new Scanner(System.in);

 

int n = sc.nextInt();

      printSum(n);

   }   

}

 



Share to whatsapp

More Questions from Java Basic Codes Module 0

Write a function that calculates the Greatest Common Divisor of 2 numbers.


View

Write a function that takes in the radius as input and returns the circumference of a circle.


View

For a given matrix of N x M, print its transpose in java.


View

Two numbers are entered by the user, x and n. Write a function to find the value of one number raised to the power of another i.e. x^n.


View

Searching for an element x in a matrix.


View

Take an array of names as input from the user and print them on the screen.


View

Print the spiral order matrix as output for a given matrix of numbers.


View