I want to write a program that tells me how many no. of times a desired value is repeated between 1 to 100 or any other range. Ex:- 9 appears 20 times between 1 to 100.
public class NumberCal {
public static void main(String []args){
int counter = 0;
for(int i=1; i<=100; i++){
while(i > 0){
int LastDig = i%10;
if(LastDig == 9){
counter = counter+1 ;
i = i/10;
} else{
i = i/10;
}
}
}
System.out.println(counter);
}
}
I tried this but there is no output. Any suggestions?
You're using i
for the outer loop but then you also use it for the check and divide it by 10
int counter = 0;
for (int i = 1; i <= 100; i++) {
int j = i;
while (j > 0) {
int LastDig = j % 10;
if (LastDig == 9) {
counter = counter + 1;
}
j = j / 10;
}
}
System.out.println(counter);
Details
int i = 1
makes i at 1 i = i/10
makes i at 0 i++
makes i at 1 i = i/10
makes i at 0 i++
makes i at 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.