Badd Speler Badd Speler - 1 year ago 52
Java Question

Using the long variable type in for loops

I've been trying to work using some very large numbers. I've been having trouble using the long variable type in a for loop.

so let's say I want to use


I tried to make a simple for loop that iterates through 600000000000 times. This is my attempt (java):

long n = 2342345234L;
for (int i = 1; i==n; i++)

I run the code, and it outputs nothing. I've tried changing the
int i = 1
long i = 1
long i = 1L

I have no experience with the long variable type so I would appreciate an explanation of what I need to change in my code and/or a simple explanation of the differences between int and long

I have checked for duplicate posts but they all seem to be more centered around people not putting L after their numbers rather than my issue where the loop seems to terminate instantly.

Answer Source

This has nothing to do with long or int, it's due to the fact that you loop while i == n which is false on the first iteration because 1 is not equal to 2342345234.

You can instead loop while i < n:

long n = 2342345234L;
for (long i = 1; i < n; i++)