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

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

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


View

Write an infinite loop using do while condition.


View

Write a function which takes in 2 numbers and returns the greater of those two.


View

Reverse a String (using StringBuilder class) in java.


View

Write a function to multiply 2 numbers.


View

Write a function to calculate the product of 2 numbers.


View

Input an email from the user. You have to create a username from the email by deleting the part that comes after ‘@’. Display that username to the user.

Example : 

email = “mejona@gmail.com” ; username = “mejona” 

email = “helloWorld123@gmail.com”; username = “helloWorld123”


View