Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: for loop is not working properly

Tags:

java

for-loop

Hello guys I'am beginner of the Java and my English is not good, i hope you will understand my problem:

public static void main(String[] args) {

    int i, a, b, c, d, yil = 1999, rt = 0;


    do{
            //loop searching for 1976
            for( i = 1900; i < 2000; i++){
            //separate "i" to the digits
            a = i / 1000;
            b = i % 1000 / 100;
            c = i % 1000 % 100 / 10;
            d = i % 1000 % 100 % 10;
            rt = a + b + c + d;
            }}
            //while rt=23 and i=1976 equation will be correct then exit the loop and print the 1976.
            while( rt == yil - i );
        System.out.println("Yıl = " + i );

}

But when i run the program it always show 2000 not 1976.


1 Answers

Your messed increments may hide it, but you have no way out of your for loop. It always goes to the end, that is i=2000.

for( i = 1900; i < 2000; i++){
   ... // no break in there
}
...
System.out.println("Yıl = " + i );

There is no reason for having two loops in your case. It seems that what you want is

        int i, a, b, c, d, yil = 1999, rt = 0;
        //loop searching for 1976
        for( i = 1900; i < 2000; i++){
            //separate "i" to the digits
            a = i / 1000;
            b = i % 1000 / 100;
            c = i % 1000 % 100 / 10;
            d = i % 1000 % 100 % 10;
            rt = a + b + c + d;
            if (rt==yil-i) break;
        }
        System.out.println("Yıl = " + i );  }

This outputs

Yıl = 1976
like image 192
Denys Séguret Avatar answered Dec 07 '25 08:12

Denys Séguret