显示数字和前 N 个自然数之和的Java程序
使用迭代方法打印前 N 个自然数,即使用 for 循环。 For 循环具有初始化、测试条件和增量/减量三个参数。
Input: N = 10
Output: First 10 Numbers = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Sum of first 10 Natural Number = 55
Input: N = 5
Output: First 5 Numbers = 1, 2, 3, 4, 5
Sum of first 5 Natural Number = 15
方法
- 以 i = 1 开始 for 循环初始化。
- 将测试条件写为 i <= N。
- 将增量语句添加为 i++ 或 i+=1。
- 用 0 初始化一个变量 sum。
- 在 for 循环的每次迭代中开始将 i 与总和相加并打印 i。
- 在循环结束时打印 sum。
下面是上述方法的实现
Java
// Java Program to Display Numbers
// from 1 to N Using For Loop and
// sum of First N Natural Number
import java.io.*;
class GFG {
public static void main(String[] args)
{
int N = 10;
int sum = 0;
System.out.print("First " + N + " Numbers = ");
// we initialize the value of the variable i
// with 1 and increment each time with 1
for (int i = 1; i <= N; i++) {
// print the value of the variable as
// long as the code executes
System.out.print(i + " ");
sum += i;
}
System.out.println();
System.out.println("Sum of first " + N
+ " Natural Number = " + sum);
}
}
Java
// Java Program to Display Numbers
// from 1 to N Using For Loop and
// sum of First N Natural Number
import java.io.*;
class GFG {
public static void main(String[] args)
{
int N = 5;
System.out.print("First " + N + " Numbers = ");
// we initialize the value of the variable i
// with 1 and increment each time with 1
for (int i = 1; i <= N; i++) {
// print the value of the variable as
// long as the code executes
System.out.print(i + " ");
}
System.out.println();
System.out.println("Sum of first " + N
+ " Natural Number = " + (N*(N+1))/2);
}
}
输出
First 10 Numbers = 1 2 3 4 5 6 7 8 9 10
Sum of first 10 Natural Number = 55
时间复杂度: O(n)
替代方法
- 以 i = 1 开始 for 循环初始化。
- 将测试条件写为 i <= N。
- 将增量语句添加为 i++ 或 i+=1。
- 每次迭代开始打印 i。
- 在 for 循环结束时使用第一个 N 自然数公式打印 sum。
下面是上述方法的实现
Java
// Java Program to Display Numbers
// from 1 to N Using For Loop and
// sum of First N Natural Number
import java.io.*;
class GFG {
public static void main(String[] args)
{
int N = 5;
System.out.print("First " + N + " Numbers = ");
// we initialize the value of the variable i
// with 1 and increment each time with 1
for (int i = 1; i <= N; i++) {
// print the value of the variable as
// long as the code executes
System.out.print(i + " ");
}
System.out.println();
System.out.println("Sum of first " + N
+ " Natural Number = " + (N*(N+1))/2);
}
}
输出
First 5 Numbers = 1 2 3 4 5
Sum of first 5 Natural Number = 15
时间复杂度: O(n)