Skip to content

Commit fded6ba

Browse files
committed
feat: Calculate sum of first N natural numbers using for loop
🧠 Logic: - Read user input `n` for number of terms. - Initialize sum to 0. - Loop from 1 to `n`, adding each number to `sum`. - Print the final sum after the loop completes. Signed-off-by: Somesh diwan <[email protected]>
1 parent d9d9eb3 commit fded6ba

File tree

1 file changed

+24
-20
lines changed

1 file changed

+24
-20
lines changed

Section8LoopAB/src/ForLoopAB5.java

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,39 @@
1+
import java.util.Scanner;
2+
3+
public class ForLoopAB5 {
4+
public static void main(String[] args) {
5+
Scanner sc=new Scanner(System.in);
6+
System.out.println("Enter a number:");
7+
int n = sc.nextInt();
8+
9+
int sum=0;
10+
for(int i=1; i<=n; i++) {
11+
sum=sum+i;
12+
}
13+
System.out.println("Sum of "+n+" Number is "+sum);
14+
}
15+
}
16+
117
/*
2-
Find the sum of First 10 Natural Numbers.
18+
Find the sum of the First 10 Natural Numbers.
319
420
n=10
521
6-
0+1=1
22+
0+1 = 1
23+
724
1 1
825
2 1+2=3
926
3 3+3=6
1027
6 6+4=10
11-
10 10+5=15
28+
10 10+5 = 15
1229
15 15+6=21
1330
1431
Sum = 0; initially
1532
Sum = Sum + i value
1633
17-
logic for(int i=1; i<=n; i++){}
18-
*/
19-
20-
import java.util.Scanner;
34+
logic:
2135
22-
public class ForLoopAB5 {
23-
public static void main(String[] args) {
24-
Scanner sc=new Scanner(System.in);
25-
System.out.println("Enter a number:");
26-
int n = sc.nextInt();
36+
for(int i=1; i<=n; i++) {
2737
28-
int sum=0;
29-
for(int i=1; i<=n; i++)
30-
{
31-
sum=sum+i;
32-
}
33-
System.out.println("Sum of "+n+" Number is "+sum);
34-
}
35-
}
38+
}
39+
*/

0 commit comments

Comments
 (0)