Advertisement
fosterbl

ForLoop1.java

Oct 8th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.62 KB | None | 0 0
  1. /*
  2. Prompt the user and receive input for an int variable, n. Write a loop that prints the first n integers from 1 to n. Then modify this loop to calculate and print the sum of the first n integers.
  3. Example: Enter a number: 5
  4.         The sum is 15
  5. */
  6. import java.util.Scanner;
  7.  
  8. public class ForLoop1{
  9.    public static void main(String[] args){
  10.       Scanner kb = new Scanner(System.in);
  11.       System.out.print("Enter a number: ");
  12.       int num = kb.nextInt();
  13.      
  14.       int sum = 0;
  15.       for(int i = 1; i <= num; i++){
  16.          sum += i;
  17.       }
  18.      
  19.       System.out.println("The sum is " + sum);
  20.    }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement