Hello Every One Today we are going to learn to write a program in Java.

Welcome to this post by Techmoodly and Follow us for more information on Technology and Programs.

So Here, Consider first n even numbers starting from zero(0). and We have to Complete the code segment to **calculate sum of all these numbers divisible by 3 and will have to Print the sum.**

##### Example:

Like if We **Input: n = 5**

So Numbers in Variable n can be 0,2,4,6,8.

Here Only 6 is divisible by 3 So the Sum will be 6.

**Now Let’s have a look in the Coding Section:**

#### Using **For Loop:**

```
import java.util.Scanner;
public class Exercise1_3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
// For Taking Input from User
int sum=0; //Initialized Sum
for (int i=0; i<n; i++)
{
int eEven=2*i;
//nEven is to calculate the Only Even Number
if(eEven%3==0)
{
sum+=eEven;
}
}
// Print the output.
System.out.print(sum);
}
}
```

```
input: 10
// (0, 2, 4, 6, 8, 10, 12, 14, 16, 18) only 6 divides by 3 thus
output: 6
```

#### Using **While Loop:**

```
import java.util.Scanner;
public class Exercise1_3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = 0;
int count=0;
while(count<n){
// I am stuck here
System.out.print(sum+" ");
sum=sum+2;
count++;
}
}
}
```

```
input: 5
// (0, 2, 4, 6, 8) only 6 divides by 3 thus
output: 6
```

So Hope you learnt something here. Guys If you know any other way to make this program output possible, So You are welcome here to Post or Comment. It may help others.

Thank you.

Follow Us: