Explanation:
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
Approach
Start for loop initialization with i = 1.
Write testing condition as i <= N.
Add increment statement as i++ or i+=1.
Initialize a variable sum with 0.
Start adding i with the sum at each iteration of for loop and print i.
Print sum at the end for loop.
Below is the implementation of above approach
// 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);
Copyright © 2024 EHUB.TIPS team's - All rights reserved.
Answers & Comments
Explanation:
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
Approach
Start for loop initialization with i = 1.
Write testing condition as i <= N.
Add increment statement as i++ or i+=1.
Initialize a variable sum with 0.
Start adding i with the sum at each iteration of for loop and print i.
Print sum at the end for loop.
Below is the implementation of above approach
// 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);
}
}