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

6th Nov 2023, 5:54 PM
Christopher kyllonen
Christopher kyllonen - avatar
10 Respostas
+ 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.
7th Nov 2023, 7:52 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 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
6th Nov 2023, 7:08 PM
Lothar
Lothar - avatar
+ 3
Why not put it in the playground and test it out?
7th Nov 2023, 1:16 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 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.
7th Nov 2023, 12:14 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 1
I did but I'm also trying to engage more in discussions as I usually just code myself
7th Nov 2023, 7:10 AM
Christopher kyllonen
Christopher kyllonen - avatar
+ 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);
8th Nov 2023, 12:46 PM
KRISHNA NAYAK
KRISHNA NAYAK - avatar
+ 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); } }
8th Nov 2023, 1:11 PM
Christopher kyllonen
Christopher kyllonen - avatar
+ 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.
8th Nov 2023, 1:21 PM
Wong Hei Ming
Wong Hei Ming - avatar
0
Look at my code please The issue not decrement but increment adding to total sum or that's what challenge requests
6th Nov 2023, 9:07 PM
Christopher kyllonen
Christopher kyllonen - avatar
0
Print(9+9)
7th Nov 2023, 1:17 PM
Tattu Tattu
Tattu Tattu - avatar