I have been recently started learning Java and would want to make code that sums the numbers from 1 to 100 (result would be 5050)
The code should go like 1+2+3+4+5+6+7+8+
You have started to learn Java by implementing a for
loop. Unfortunately that is probably the least intuitive syntax in the entire language. It was inherited from c
and, while convenient, really makes no sense: the meaning of the three positions bears no resemblance to natural language (unlike if
, while
, implements
etc.). Much better to start with simpler constructs until you get the hang of things.
Java 8 provides a more intuitive (in my opinion) way of representing a group of numbers to add. In your case you don't really want to iterate through all the numbers from 1 to 100. You just want a way to represent all those numbers and then sum them. In Java 8 this concept is represented by a stream of integers: the IntStream
class. It provides a handy way of asking for 'all integers between x and y': the rangeClosed
method. And it provides a method for adding all the integers together: the sum
method.
So your operation could be implemented with a single, simple Java statement:
IntStream.rangeClosed(1, 100).sum();
That seems a pretty straightforward statement to read: give me a stream of integers in the range from 1 to 100 and then sum them. Even better you don't need to declare a variable you have no real use for.
Use this code. It will print the value like
1+2+3.. + 100 = 5050
public class T35{
public static void main(String[] args) {
int total=0;
StringBuilder stringBuilder=new StringBuilder();
for(int nmb= 1; nmb<= 100; nmb++){
total+=nmb;
stringBuilder.append(nmb);
if(nmb!=100)
stringBuilder.append("+");
}
stringBuilder.append(" = "+total);
System.out.println(stringBuilder.toString());
}
}
nmb++
is equal to nmb = nmb + 1
. It only adds one till it's 101, which is when it stops.
You should add a new variable, let's call it total
, and sum nmb
to it every iteration.
public class T35{
public static void main(String[] args) {
int nmb;
int total = 0;
for(nmb= 1; nmb<= 100; nmb++){
total = total + nmb;
}
System.out.println(total);
}
}
This will do what you want.
Hey you can find the sum from 1 to 100 like this also. Just a option.
You can use the mathematical formula for sum of numbers i.e n(n+1)/2
public class test {
public static void main(String[] args) {
int i =100;
int sum = (i)*(i+1)/2;
System.out.println(sum);
}
}
You output the value of nmb
that is the numeric value that you iterate on, you don't increment the actual value with the current sum.
You should introduce a local variable before the loop to compute and maintain the actual sum.
Besides, int nmb;
could be declared directly in the loop.
Narrowing the scope of variables makes the code more robust.
public class T35{
public static void main(String[] args) {
int sum = 0;
for(int i= 1; i<= 100; i++){
sum += i;
System.out.println(sum);
}
}
}