2
I’m trying to solve the following problem using DESVIO CONDICIONAL COMPOSTO
. I can’t imagine how I calculate the numbers that make up the digit
Request an integer value from the user between 100 and 999. If the read value is less than 500, display the sum between its component numbers. Otherwise, subtract its components.
I only know I must wear IF
and ELSE
, where I will place this condition
if(nb > 500 ) {
for the sum of the component numbers to occur.
What I broke my head but really couldn’t come to a conclusion is how I’m going to accomplish the sum!
For example, if the number is 328, how will I add the numbers 3, 2 and 8?
Ours is even more confusing now!
– Carol M
Exercise is actually only with If and Else..
– Carol M
How so just with if and Else? What you didn’t understand?
– Costamilam
You gave me a Solution with For, but for this exercise I should only use If(condition) and Else{ instruction I should only use :IF a condition is TRUE, THEN deviate and perform the instructions linked to the true condition ELSE if that condition is FALSE, deviates and performs the instructions linked to the false condition
– Carol M
From what I understood the question the doubt was how to sum the digits of a number and that’s what the code does, now just put the if to the loop add and Else to the reverse. I got the question wrong?
– Costamilam
Exactly William! If the number for example is 328 ,I must add the three numbers to get the result!
– Carol M
Then, that’s what the code does, the split splits the string to generate an array with 3 elements, then a loop is made to add each item of the array to the total variable. Have you tested?
– Costamilam
And that would work for any number? Because the user will enter the number,!
– Carol M
Yes, but if the variable value is not a number it will generate an exception when trying to convert
– Costamilam
I’ll try then! Until tomorrow I’ll come here and tell you if it worked!
– Carol M
I edited the answer with a more complete example
– Costamilam