0
How to get sum of numbers of while loop
Take an integer from input and out the sum of the numbers inclusively https://code.sololearn.com/c2mGYbHG97kN/?ref=app
10 ответов
+ 1
Christopher kyllonen
That's ok.
This kind of question can use both for loop and while loop. In both loops, decrement and increment also works.
That means there are at least 4 ways to solve this question.
Try them all to practice.
+ 8
Christopher kyllonen ,
there are several issues we should fix:
> use the input num and start with it as a counter. decrement it in each loop iteration by 1.
> sum += num; //move this inside the loop
> num++; // move this inside the loop and make it num--,
> the loop body needs to have curly braces around
> loop condition has to be: while(num > 0)
> output the result has to be done after / outside loop
+ 3
Why not put it in the playground and test it out?
+ 1
Decrement or increment doesn't matter.
1+2+3+4=10
4+3+2+1=10
You get the same result from both direction.
+ 1
I did but I'm also trying to engage more in discussions as I usually just code myself
+ 1
Here is the code
import java.util.*;
class Sum
{
public static void main (String args[])
{
int n,r,sum=0;
Scanner sc=new Scanner (System.in);
System.out.println("Enter an integer value ");
n=sc.nextInt();
while(n!=0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
System.out.println("Sum is : "+sum);
+ 1
Krishna Nayak
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
//your code goes here
Scanner sc = new Scanner(System.in);
int sum = 0;
int num = sc.nextInt();
while(num > 0){
sum += num;
num--;
}
System.out.println(sum);
}
}
+ 1
Christopher kyllonen
You can mention other by typing @, then select the name.
Krishna's code is to solve another kind of question.
Given an integer, what is the sum of individual digit.
Say the given integer is 123, the answer is 3+2+1=6.
n%10 return the last digit and assigned to r.
So r will be 3 in the first run, 2 in the second run, and 1 in the last run.
0
Look at my code please The issue not decrement but increment adding to total sum or that's what challenge requests
0
Print(9+9)