How to add first numbers and skip the next numbers and print total sum

Viewed 34

I am new to Java, and I have code that print the sum of 1 to 100.

Now, I need to add the first 10 numbers and skip the next 10 until it reaches 100, then it should print the sum of 2275 only by using the following:

  • for-loop
  • Two if-statements
  • Three Variables: x y sum

This is the Flowchart that I need to follow, but I can't understand. I tried to code it with if-statements, but it only prints the sum of 1 to 100.

Can someone help me? How can I implement the if-statement? Is it inside the for loop or should be outside the for loop?

Here is my code, this one prints: 4950

int x = 0;
int sum = 0;

for (int y=0; y<=99; y++)
{
   sum = sum + y;
}
  System.out.println("The total sum is: "+sum); // print: 4950

This is the one with if-statement, but prints: 2450

    int x = 0;
    int sum = 0;

    for (int y=0; y<=99; y++)
    {
       
      if (x<=10)
        {
          sum = sum + y;
          y++;
        }
      if (x==0)
        {
         x++;
        }
    }
      System.out.println("The total sum is: "+sum); // print: 2450
1 Answers

In a loop you need to increament x and y by one. While x <= 10 condition is true sum = sum + y. If x is going to 20 then x is become 0 and again this x <= 10 is become true.

public class Main
{
    public static void main(String[] args) {
        int x = 0;
        int y = 0;
        int sum = 0;
    
        for (int i = 0; i < 100; i++)
        {
            x++;
            y++;
            if(x <= 10)
            {
                sum += y;
            }
            
            if(x == 20)
            {
                x = 0;
            }
        }
        System.out.println("The total sum is: "+sum);
    }
}
Related