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

Searching for an element x in a matrix.


View

Write a program to print Fibonacci series of n terms where n is input by user :

0 1 1 2 3 5 8 13 21 ..... 

In the Fibonacci series, a number is the sum of the previous 2 numbers that came before it.


View

Input a string from the user. Create a new string called ‘result’ in which you will replace the letter ‘e’ in the original string with letter ‘i’. 

Example : 

original = “eabcdef’ ; result = “iabcdif”

Original = “xyz” ; result = “xyz”


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

Write an infinite loop using do while condition.


View

Enter 3 numbers from the user & make a function to print their average.


View

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


View