Today’s challenge is to create a program that calculates the sum of all numbers from 1 to a user-provided number n. This task will teach you how to work with loops and arithmetic operations efficiently.
For example:
If the user enters n = 5, the program should calculate: 1 + 2 + 3 + 4 + 5 = 15
By completing this challenge, you will:
There are two main approaches:
# Get input from the user
n = int(input("Enter a positive integer: "))
# Ensure the input is positive
if n < 1:
print("Please enter a positive integer.")
else:
total = 0
for i in range(1, n + 1):
total += i # Add each number to the total
print(f"The sum of numbers from 1 to {n} is: {total}")
# Get input from the user
n = int(input("Enter a positive integer: "))
# Ensure the input is positive
if n < 1:
print("Please enter a positive integer.")
else:
total = n * (n + 1) // 2 # Use the summation formula
print(f"The sum of numbers from 1 to {n} is: {total}")
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
if (n < 1) {
System.out.println("Please enter a positive integer.");
} else {
int total = 0;
for (int i = 1; i <= n; i++) {
total += i; // Add each number to the total
}
System.out.println("The sum of numbers from 1 to " + n + " is: " + total);
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get input from the user
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
if (n < 1) {
System.out.println("Please enter a positive integer.");
} else {
int total = n * (n + 1) / 2; // Use the summation formula
System.out.println("The sum of numbers from 1 to " + n + " is: " + total);
}
}
}
// Get input from the user
let n = parseInt(prompt("Enter a positive integer:"));
if (n < 1) {
console.log("Please enter a positive integer.");
} else {
let total = 0;
for (let i = 1; i <= n; i++) {
total += i; // Add each number to the total
}
console.log(`The sum of numbers from 1 to ${n} is: ${total}`);
}
// Get input from the user
let n = parseInt(prompt("Enter a positive integer:"));
if (n < 1) {
console.log("Please enter a positive integer.");
} else {
let total = (n * (n + 1)) / 2; // Use the summation formula
console.log(`The sum of numbers from 1 to ${n} is: ${total}`);
}
In Day 12: Reverse a String, you’ll dive into string manipulation and write a program to reverse a given string—a skill widely used in many programming tasks!