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