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 to print the sum of all odd numbers from 1 to n.


View

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


View

Write a function to multiply 2 numbers.


View

Write a function that takes in age as input and returns if that person is eligible to vote or not. A person of age > 18 is eligible to vote.


View

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


View

Find the maximum & minimum number in an array of integers.

[HINT : Read about Integer.MIN_VALUE & Integer.MAX_VALUE in Java]


View

Write a function to calculate the factorial of a number.


View