Computer Science, asked by sivamsingh638, 1 month ago

I am in class 9 write a java program to print sun of even and odd number from first 50 natural numbers

right answer will get branliest mark spam will be reported​

Answers

Answered by sharmapriyansu33
1

Explanation:

class jav

{

public static void main()

{ int i,a=2,b=1,Se=0,So=0;

for(i=1;i<=50;i++)

{

Se+=a+2;

So+=b+2;

}

System.out.print(Se+" "+So);

}

}

Answered by saurabhsinghrajput07
1

Explanation:

When any number which ends with 0,2,4,6,8 is divided by 2 that is an even number. And when any number ends with 1,3,5,7,9 is not divided by two is an odd number.

Example:

Input : 8

Output: Sum of First 8 Even numbers = 72

Sum of First 8 Odd numbers = 64

Approach #1: Iterative

Create two variables evenSum and oddSum and initialize them by 0.

Start For loop from 1 to 2*n.

If i is even Add i with evenSum.

Else add i with oddSum.

Print evenSum and oddSum at the end of loop.

Below is the implementation of the Java program:

// Calculate the Sum of First N Odd & Even Numbers in Java

import java.io.*;

public class GFG {

// Driver function

public static void main(String[] args)

{

int n = 8;

int evenSum = 0;

int oddSum = 0;

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

// check even & odd using Bitwise AND operator

if ((i & 1) == 0)

evenSum += i;

else

oddSum += i;

}

// Sum of even numbers less then 17

System.out.println("Sum of First " + n

+ " Even numbers = " + evenSum);

// sum of odd numbers less then 17

System.out.println("Sum of First " + n

+ " Odd numbers = " + oddSum);

}

}

Output

Sum of First 8 Even numbers = 72

Sum of First 8 Odd numbers = 64

Time Complexity: O(N), where N is the number of First N even/odd numbers.

Method 2: Using AP Formulas.

Sum of First N Even Numbers = n * (n+1)

Sum of First N Odd Numbers = n * n

Below is the implementation of the above approach:

// Calculate the Sum of First N Odd & Even Numbers in Java

import java.io.*;

public class GFG {

// Function to find the sum of even numbers

static int sumOfEvenNums(int n) { return n * (n + 1); }

// Function to find the sum of odd numbers.

static int sumOfOddNums(int n) { return n * n; }

// Driver function

public static void main(String[] args)

{

int n = 10;

int evenSum = sumOfEvenNums(n);

int oddSum = sumOfOddNums(n);

// Sum of even numbers

System.out.println("Sum of First " + n

+ " Even numbers = " + evenSum);

// sum of odd numbers

System.out.println("Sum of First " + n

+ " Odd numbers = " + oddSum);

}

}

Output

Sum of First 10 Even numbers = 110

Sum of First 10 Odd numbers = 100

HOPE THIS HELPS YOU

SOLVE THIS BY YOUR OWN

MARK ME AS BRAINLIST

Similar questions