Amazon Prime




 
Tagged
  • Flow Chart
  •  

    Sum of First n Numbers

    Problem Statement

    1Problem Description :
    2Write Algorithm, Flowchart and Program to Find Sum of First n Integers
    3
    4
    5Example 1 :
    6 Input : n = 4
    7 Output : 10
    8 Explanation : First 4 integers are 1,2,3 and 4 so sum is 1+2+3+4 = 10
    9
    10
    11Example 2 :
    12 Input : n = 10
    13 Output : 55
    14 Explanation : First 10 integers are 1,2,3,..., 10
    15 so sum is = 1+2+3+...+10 = 55

    Algorithm

    1Input : input number n
    2Step 1: Start
    3Step 2: Read number n Step 3: Declare sum to 0 and i to 1
    4Step 4: Repeat steps 5 to 7 until i <= n
    5Step 5: update sum as sum = sum + i
    6Step 6: increment i
    7Step 7: Print sum
    8Step 8: Stop
    9Output: sum

    Video Explanation

    Flow Chart

    Sum Of First N Numbers - Flowchart

    Code Implementation

    1. Java
    2. C

    1import java.util.Scanner;
    2
    3public class SumOfFirstNNumbers {
    4
    5 public static void main(String[] args) {
    6 Scanner sc = new Scanner(System.in);
    7
    8 // Read n
    9 System.out.print("Enter n : ");
    10 int n = sc.nextInt();
    11
    12 // Declare sum and counter variable i
    13 int sum = 0;
    14 int i;
    15
    16 // loop continues until i<=n
    17 for (i = 1; i <= n; i++) {
    18 // update sum
    19 sum = sum + i;
    20 }
    21 // Print sum
    22 System.out.printf("Sum of First %d numbers is %d \n", n, sum);
    23 }
    24}

    1Output 1 :
    2Enter n : 4
    3Sum of First 4 numbers is 10
     

  • Flow Chart
  •  
    ...