(JAVA ONLY)
Sum of 100 POSITIVE Integers in One Variable.
1.Not to use loop.
2.Use only one variable.
Answers
Answered by
18
- Write a program in java to find the sum of 100 different numbers entered by the user.
import java.util.*;
class Program
{
static Program z[ ] = new Program [100]; //creating array of object.
static int s[ ] = new int[2];
Scanner sc=new Scanner(System.in);
Program()
{ // default constructor
s[0]+=sc.nextInt();
}
static void disp()
{
if(s[1]>=100)
return;
else
{
Program obj = new Program();
s[1]+=1;
disp();
} // end of else part.
} // end of disp()
public static void main()
{ // main method
disp();
calc();
}
static void calc()
{
System.out.println("\nSum of 100 entered numbers is: "+s[0]);
}
} // end of class
- Write a program is java to find the sum of first 100 natural numbers using one variable and without loop.
- First of all, sum of first n natural numbers is calculated by using this formula,
So, we shall use this formula to calculate the sum of first 100 numbers.
class x
{
public static void main()
{
int a=100;
a=a*(a+1)/2;
System.out.println("Sum of first 100 natural numbers is: "+a);
}
}
- Loops not allowed ✅✅.
- Use only one variable ✅✅
I am not sure about which program u are asking, I have done both of them.
- For the first question, I have created array of objects and one integer array, so, total number of variable=1.
- For the second question,I have calculated by using formula.
Have a great day.
Similar questions