Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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.
- Example: Enter a number: 5
- The sum is 15
- */
- import java.util.Scanner;
- public class ForLoop1{
- public static void main(String[] args){
- Scanner kb = new Scanner(System.in);
- System.out.print("Enter a number: ");
- int num = kb.nextInt();
- int sum = 0;
- for(int i = 1; i <= num; i++){
- sum += i;
- }
- System.out.println("The sum is " + sum);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement