![Amazon Prime](https://technologystrive.com/images/amazonPrime.jpg)
Sum of First n Numbers
Problem Statement
1Problem Description :2Write Algorithm, Flowchart and Program to Find Sum of First n Integers345Example 1 :6 Input : n = 47 Output : 108 Explanation : First 4 integers are 1,2,3 and 4 so sum is 1+2+3+4 = 1091011Example 2 :12 Input : n = 1013 Output : 5514 Explanation : First 10 integers are 1,2,3,..., 1015 so sum is = 1+2+3+...+10 = 55
Algorithm
1Input : input number n2Step 1: Start3Step 2: Read number n Step 3: Declare sum to 0 and i to 14Step 4: Repeat steps 5 to 7 until i <= n5Step 5: update sum as sum = sum + i6Step 6: increment i7Step 7: Print sum8Step 8: Stop9Output: sum
Video Explanation
Flow Chart
Code Implementation
- Java
- C
1import java.util.Scanner;23public class SumOfFirstNNumbers {45 public static void main(String[] args) {6 Scanner sc = new Scanner(System.in);78 // Read n9 System.out.print("Enter n : ");10 int n = sc.nextInt();1112 // Declare sum and counter variable i13 int sum = 0;14 int i;1516 // loop continues until i<=n17 for (i = 1; i <= n; i++) {18 // update sum19 sum = sum + i;20 }21 // Print sum22 System.out.printf("Sum of First %d numbers is %d \n", n, sum);23 }24}
1Output 1 :2Enter n : 43Sum of First 4 numbers is 10