Here, we have a basic program example to print the sum of even natural numbers using different languages. This program is created in c language, c++, Java, and Python.
Code to print the sum of even natural numbers is C language
#include <stdio.h>
void main(){
int i, n, sum=0;
printf("Input the number of terms : ");
scanf("%d",&n);
printf("\nThe even numbers are: ");
for(i=1;i<=n;i++)
{
printf("%d ",2*i);
sum += 2*i;
}
printf("\nThe Sum of even natural numbers upto %d terms is : %d \n ",n,sum);
}
Code to print the sum of even natural numbers is C++ language
#include <iostream>
using namespace std;
int main()
{
int i, n, sum=0;
cout<<"Input the number of terms : ";
cin>>n;
cout<<"\nThe even numbers are: ";
for(i=1;i<=n;i++)
{
cout<<2*i<<" ";
sum += 2*i;
}
cout<<"\nThe Sum of even natural numbers upto "<<n<<" terms is: "<<sum;
}
Code to print the sum of even natural numbers is Python language
sum=0
n = int(input("Input the number of terms: "))
print("\n The even numbers are: ")
for i in range(1, n+1):
print(2*i)
sum=sum+(2*i)
print("The Sum of even natural numbers upto ", n," is:", sum)
Code to print the sum of even natural numbers is Java language
import java.util.*;
public class sum {
public static void main(String[] args) {
int i, n, sum=0;
System.out.println("Enter the number of terms : ");
Scanner s=new Scanner(System.in);
n = s.nextInt();
System.out.println("\nThe even numbers are: ");
for(i=1;i<=n;i++)
{
System.out.println(2*i);
sum += 2*i;
}
System.out.println("\nThe Sum of even natural numbers upto " +n +" terms is : \n "+sum);
}
}