简体   繁体   中英

Java, sum range of numbers in a for loop

Sorry I have been trying to figure this out and it's driving me crazy.

I need to write a java program that sums a range of numbers entered by the user and by the count of numbers entered by a user. So if a user enters 5, 25 with count of 5. It should sum 5+10+15+20+25=75 I have gotten it to work with a while loop, but not a for loop. Sorry if I am asking for help for something that should be simple. I left school almost 15 years ago involuntarily and struggling to get back into in.

Do I need to nest the loop?

import java.util.Scanner;
public class example1

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {

      for (; s <= e; s++)
        sum += c;
      System.out.println("Sum of your numbers  " + sum);
    }

  }
}

You are incrementing s by one with s++ , sounds like you should be incrementing by the count:

for (; s <= e; s+=c)
    sum += s;

im not sure what you are asking. but follows show the method with for loop and while loop

 int i=2;
   while(i<c){
         System.out.println("Enter "+i+ " number :" );
         sum += sc.nextInt();
         i++;               
    }

for loop =>

for(int i=2; i< c ; i++){
       System.out.println("Enter "+i+ " number :" );
        sum += sc.nextInt();

   }

   System.out.println("Count : "+ (sum+s+e));

This is what the final code looked like and it worked with several different numbers I entered. Is there a way to make this as "answered"?

 import java.util.Scanner ; public class example1 { public static void main(String[] args) { int s,e,c = 0, sum = 0; Scanner sc = new Scanner(System.in); System.out.print("Enter starting number: "); s = sc.nextInt(); System.out.print("Enter an end number: "); e = sc.nextInt(); System.out.print("Enter a count by number: "); c = sc.nextInt(); for (; s <= e; s+=c) sum += s; System.out.println("The sum of your number range is " + sum); } } 

Try this code:

import java.util.Scanner;
public class count

{
  public static void main(String[] args) {
    int s, e, c = 0, sum = 0,i=1;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter a starting number:  ");
    s = sc.nextInt();
    System.out.print("Enter an end number:  ");
    e = sc.nextInt();
    System.out.print("Enter a count by number:  ");
    c = sc.nextInt();

    {
      for (i=s; i <= e; i+=c)
        sum += i;
      System.out.println("Sum of your numbers  " + sum);

    }

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM