Skip to main content

Command Palette

Search for a command to run...

Nth Natural Numbers Sum and Its Average

Updated
Nth Natural Numbers Sum and Its Average
M

IIIT - N Software Geek. Startup Enthusiast. Build for the Future.

Explanation:

Step 1: First we need to take the nth term value from the user. For that, we are taking the Scanner class object to take input.

Step 2: With that input, we need to store that input number in some variable.

Step 3: now we need to iterate for loop until the user entered a number because we need to add the sums up to the user's input value.

Step 4: First we need to take the sum=0 as a variable.

Step 5: for every iteration, we need to add i value to the sum variable sum = sum + i.

Step 6: so that it will calculate the sum of the nth term.

Step 7: And in the last step we need to divide the total sum by the input value to get the Average.

Java Code:

// sum of nth term and its avg
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
        System.out.print("Enter a Number = ");
        float sum = 0;
        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();
        for(int i = 1; i<= input;i++){
            sum = sum + i;
        }
        System.out.println("Sum is = " + sum);
        System.out.println("Avg is = " + (sum / input));
    }
}

C++ code:

#include<iostream>
using namespace std;

int main(){
    float sum = 0 ;
    int number;
    cout<<"Enter a Number = ";
    cin>>number;
    for(int i = 1;i<=number;i++){
        sum = sum + i;
    }
    cout<<"natural Numbers sum = " << sum <<endl;
    cout<<"Avg is  = " << sum/number <<endl;    
}

Python code:

num = int(input("Enter a number = "))
total_items=float(num)
sum = 0;
for i in range(1,num+1):
    sum = sum + i
print("Natural Number sum = "  , sum)
print("Avg is  = "  , float(sum/total_items))