In this example, we're going to discuss how to calculate the sum of all natural numbers up to a given positive integer using different programming languages. This concept is fundamental in programming and is often used in various mathematical computations.
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
for (int i = 1; i <= num; ++i) {
sum += i;
}
printf("Sum of natural numbers up to %d is: %d
", num, sum);
return 0;
}
#include <iostream>
using namespace std;
int main() {
int num, sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum of natural numbers up to " << num << " is: " << sum << endl;
return 0;
}
def main():
num = int(input("Enter a positive integer: "))
sum = 0
for i in range(1, num + 1):
sum += i
print("Sum of natural numbers up to", num, "is:", sum)
if __name__ == "__main__":
main()
import java.util.Scanner;
public class SumOfNaturalNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = scanner.nextInt();
int sum = 0;
for (int i = 1; i <= num; ++i) {
sum += i;
}
System.out.println("Sum of natural numbers up to " + num + " is: " + sum);
}
}