How to take a generalize value in this code instead of n=5; and why it is printing 49 even after the if condition?
Hey @Nitya_Somani
- Put a loop till the Sum>=0
- Add the new number to the previous sum.
- If the sum is positive print the current number.
- Otherwise, break the loop.
int sum =0;
1
2
88
-100
49
1+ 2 +88 == 91
91 -100= -9 (break loop if sum is negative )
print
1
2
88
package ChallengePatterns;
import java.util.Scanner;
public class SimpleInput {
public static void main(String[] args)
{
System.out.println("simple input");
Scanner scan= new Scanner(System.in);
int sum=0;
int n = 5;
for(int i=1;i<=n;i++)
{
int var = scan.nextInt();
sum=sum+var;
if(sum>=0)
{
System.out.println(var);
}
else
{
break;
}
}
}
}
In this unable to understand how to take n value as generalized and sum i have already set to 0 so how can i use it in loop ?
Why are you looping only 5 times??
int sum=0;
while(sum>=0){
int var = scan.nextInt();
sum=sum+var;
if(sum>=0)
{
System.out.println(var);
}
else
{
break;
}
}
ye krna h
1 Like