Computer Science, asked by Vyomsingh, 8 months ago


\large\bf\red\star\blue{CHALLENGE}\red\star
(JAVA ONLY)
Sum of 100 POSITIVE Integers in One Variable.
\large\bf\purple{Restrictions➠}
1.Not to use loop.
2.Use only one variable.​

Answers

Answered by anindyaadhikari13
18

\star\:\:\:\sf\large\underline\blue{Challenge\:Accepted}

\star\:\:\:\sf\large\underline\blue{Question\:1:-}

  • Write a program in java to find the sum of 100 different numbers entered by the user.

\star\:\:\:\sf\large\underline\blue{Source\:Code:-}

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

\star\:\:\:\sf\large\underline\blue{Question\:2:-}

  • Write a program is java to find the sum of first 100 natural numbers using one variable and without loop.

\star\:\:\:\sf\large\underline\blue{Source\:Code:-}

  • First of all, sum of first n natural numbers is calculated by using this formula,

  \sf\displaystyle \boxed{\sum_{i = 1}^{n} a_{i} =  \frac{n(n + 1)}{2} }

So, we shall use this formula to calculate the sum of first 100 numbers.

\star\:\:\:\sf\large\underline\blue{Source\:Code:-}

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);

}

}

\star\:\:\:\sf\large\underline\blue{Restrictions:-}

  1. Loops not allowed ✅✅.
  2. 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