Program to find the sum of all odd numbers 1 to n number using function in java.

 import java.util.*;

public class function {

    public static void sumOfOddNumbers(int n){

        int sum=0;

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

            if(i%2!=0){

                sum=sum+i;

            }

        }

        System.out.print("the sum of odd number is="+sum);

    }

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);

        System.out.println("enter the number where you want to add odd numbers=");

        int n=sc.nextInt();

        sumOfOddNumbers(n);

    }

}

■》Output->

enter the number where you want to add odd numbers= 7

the sum of odd number is=16

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.