+ 3
i want to print sum of all integers from 1to 100 like for example : 1 3 6 10 15...... i tried it i know my code is wrong please help me class Program { public static void main(String[] args) { for(int x = 1; x <101; x++) { int sum = int x; System.out.println("1"); System.out.println("sum"); } } }
11 Respuestas
+ 4
To get the sequence 1, 3, 6, 10, 15 … try the following:
class Sums {
public static void main(String[] args) {
int sum = 0; // Use zero not oh.
for (int i = 1; i <= 100; ++i) {
sum += i;
System.out.println(sum);
}
}
}
Of course, remember that the source file must be called "Sums.java". Then at the command line type
javac Sums.java
java Sums
Adapt to your IDE as required.
+ 1
class Program {
public static void main(String[] args) {
int sum=O;
for(int x = 1; x <=100; x++) {
sum = sum + x
System.out.println("sum");
}
}
}
+ 1
If, your want to print series
1,3,6,10,15,.... then use
public class Program
{
public static void main(String[] args) {
int i,s=1;
for(i=1;i<=100;i++,s++)
{
System.out.println(i);
i+=s;
}
}
}
+ 1
write i<=100 instead of writing i<101
+ 1
class Program {
public static void main(String[] args) {
int sum=0;
for(int x = 1; x <=100; x++) {
sum+= x;
System.out.println("sum= "+sum);
}
}
}
/*
output:
sum= 1
sum= 3
sum = 6
sum= 10
....
*/
0
Please explain the s++ @Aditya
0
Let x<100
0
public class Program {
public static void main(String[] args) {
for (int i=1,k=0;i<=100;k+=i,i++)
System.out.println(k);
}
}
- 1
public static void main(String[] args)
{
for(int x = 1; x <101; x++)
{
System.out.println("x");
}
}
You could just simply print out 'x' , because 'x' itself will constantly be added by '1' due to the for loop anyway. Try it and you will know what I mean.
- 1
public class Program {
public static void main(String[] args) {
for(int x = 1; x <101; x++) {
int sum = x ;
System.out.println(sum);
}
}
}
- 2
If you just want the numbers 1 to 100 printed out, use this:
public class Test {
public static void main(String[] args) {
for(int i = 1; i <= 100; i++) {
System.out.println("i is: " + i);
}
}
}
Then again though, if you want to print 1, 3, 6, 10, 15 etc. this isn't what you want.