1

I have some doubts as to why the value of index is not incrementing here.

The reason why I have declared my array like that is because I need to store n natural numbers where (1 ≤ n ≤ 1012), so numbers are large which is why I have taken an array of type long, but then I get an error that I cannot put any long value in the group, which is why I cast it to int. Is there any way to declare an array for this type of condition, as I want a large number of indexes, and I can not put a long number in the [ ].

hope you guys understand my problem

CODE:

import java.util.Scanner;

class Error{

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    long n = in.nextLong();
    long array[] = new long[(int) n];
    long index = 0;


    for (int j = 1; j <= n; j++) {
            if (j % 2 != 0) {//odd
                array[(int) index++] = j;
                System.out.print(" " + array[(int) --index]);
                System.out.print(index);// index value  -> always 0  why??
                System.out.print(j);
            }
        }
    System.out.println();
    }
}

OUTPUT:

Unix-Box ~/Desktop$ javac Error.java 
Unix-Box ~/Desktop$ java Error
10
 101 303 505 707 909
Unix-Box ~/Desktop$ 

the middle value is of index and it is always 0


what i shout it to be like

 10
     101 313 525 737 949
    Unix-Box ~/Desktop$ 
Javia1492
  • 862
  • 11
  • 28
  • 7
    Well, you increment it, then you decrement it in the immediately following line, so I'm not sure why it would ever be anything other than 0. – Compass Jun 23 '17 at 19:33
  • 3
    You have `index++` followed by `--index`. What do you expect the result to be? – PM 77-1 Jun 23 '17 at 19:34
  • Why do have `n` as `long`? What the purpose? – PM 77-1 Jun 23 '17 at 19:34
  • 2
    You can avoid the observer effect by using instead `System.out.print(" " + array[ (int) (index - 1) ]);`. And consider defining index to be an int, if you're using it as an index into a Java array, which only supports ints as indices. You're not getting more than *2^31 - 1* values in a single Java array. Downcasting from a long to an int won't change this. – Andy Thomas Jun 23 '17 at 19:37
  • 4
    So you want to have array index up to 10^12. That is 10^12 elements in the array, 8 bytes per element gives 8Tb of RAM for this single array. Do you really have so much? – Roman Puchkovskiy Jun 23 '17 at 19:38
  • 1
    Just as a note, Java has a maximum array size of Integer.MAX_VALUE - (?); if you really need that many values in an array, you'll have to use a different language. https://stackoverflow.com/q/3038392/899126 – Chris Forrence Jun 23 '17 at 19:40
  • @ChrisForrence is right, it won't let you do this because Java doesn't support arrays that are as large as a long could be. – MMAdams Jun 23 '17 at 19:41
  • Just to clarify, do you need the array size to be (1 ≤ n ≤ 10^12) or the individual values held by the array to be of value (1 ≤ n ≤ 10^12)? – spanglerb Jun 23 '17 at 19:51
  • @spanglerb yes i want these both -> my array for natural no can be upto 10^12 elements and value of each element can be also 10^12 times long [question link codeforces](http://codeforces.com/problemset/problem/318/A) –  Jun 24 '17 at 08:20
  • thank you all of you guys, -> sorry for the silly question, don't know how did i missed that **thanks all of you : )** –  Jun 24 '17 at 08:26
  • **thanks @AndyThomas, ca you tell me how can i achieve this** –  Jun 24 '17 at 08:36
  • @RomanPuchkovskiy **thats an amazing analysis -> loved it & again thanks for answering : )** –  Jun 24 '17 at 08:41

2 Answers2

1

According to https://www.quora.com/What-is-the-maximum-size-of-the-array-in-Java, the max size of an array is 2147483647 theoretically, but in practice we would want to use 2147483600 to be safe. Declaring the array as type long will mean that long values can be stored inside. Maybe you can use a two dimensional array to store a long n amount of values. Something like--

    public static void main(String[] args)
  {
System.out.println("enter the size of the array:");
Scanner in = new Scanner(System.in);
long n = Long.parseLong(in.nextLine()); 
int secondIndex = 2147483600;
int firstIndex = ((int)(n/secondIndex))+1;

if(secondIndex > n)
{secondIndex = (int)n;
}
    else{int leftover = (int)(n%secondIndex);
        secondIndex = secondIndex - leftover;}

    long[][] array = new long[firstIndex][secondIndex];

    //loop through array
      outerloop:
    for(int i =0;i <firstIndex; i++)
    {
      for(int z = 0; z<secondIndex; z++)
      {

        System.out.println("do work with number here: " + array[i][z]);
        if(z==(secondIndex-1))
        {
          z=0;
          continue outerloop;
        }
      }

    }
  }

You might get a java.lang.OutOfMemoryError:, which can be resolved by reading this article https://plumbr.eu/outofmemoryerror/java-heap-space.

Paymon Wang-Lotfi
  • 545
  • 2
  • 11
  • 29
0

As others have indicated,

array[(int) index++] = j; // You use index and then increment it
System.out.print(" " + array[(int) --index]); // You decrement the index here

That's why index will always be 0 when you print it.

Personally, I don't like mixing brackets with increment operators for the precise reason you're seeing here - it tends to be confusing and it lends itself to subtle (and not-so-subtle) bugs and off-by-one errors. In fact, I really don't like mixing them with any other syntax (with the exception of for loops) as it can quickly become very unclear. For example, if you had done something like

index++;
array[(int)index] = j;
index--;
System.out.print(" " + array[(int)index]);

the problem would've been obvious immediately.

In general, it's a bad idea to sacrifice clarity for brevity.

Also, just to review how the operators in question are working:
index++ - use the value and then increment it
index-- - use the value and then decrement it
++index - increment the value and then use it
--index - decrement the value and then use it.

Here's a C# code sample I put together (Java's behavior will be identical) to illustrate this:

int i = 0;

Trace.TraceInformation((i++).ToString()); // Prints 0

Trace.TraceInformation(i.ToString()); // Prints 1

Trace.TraceInformation((--i).ToString()); // Prints 0

Trace.TraceInformation((i--).ToString()); // Prints 0

Trace.TraceInformation(i.ToString()); // Prints -1

I'd encourage you to trace/step through this to convince yourself that that's the case and to understand exactly why the value is what it is at every point.

Either way, this syntax can be very confusing if overused.

  • 2
    Why use a C# example in a Java question? Also, on *"I strongly discourage using this syntax in this way ..."* -- to what way are you referring, specifically? – Andy Thomas Jun 23 '17 at 19:56
  • @AndyThomas Possibly the mixture of post and pre increment/decrements? – Javia1492 Jun 23 '17 at 20:00
  • 1
    Maybe. If he or she is strongly discouraging something, it would be useful to explicitly specify what he or she is strongly discouraging. – Andy Thomas Jun 23 '17 at 20:06
  • @AndyThomas I edited - is that more clear? Basically, my point is that it's really confusing to try to do stuff like `array[i++]` and that if OP had just put the `i++` and `i--` on separate lines in the first place the problem would've been obvious right away. Basically, the OP sacrificed clarity for brevity and it caused a bug. – EJoshuaS - Stand with Ukraine Jun 23 '17 at 20:37
  • 2
    Yes, your suggestion is more clear. Note that using a post-fix increment/decrement operator as a standalone statement may add an unnecessary cost to store the original value as the value of the expression after incrementing/decrementing. Prefer prefix increment/decrement operators for standalone statements. This has the side-benefit of putting the short operator before the arbitrarily long variable name, where the operator is more easily seen. – Andy Thomas Jun 23 '17 at 20:44
  • @PrashantKr No problem, glad to help. Can you [accept one of the answers](https://stackoverflow.com/help/accepted-answer) if they resolved the issue for you? (Accepting an answer indicates to future readers that it solved the problem for you, plus it awards reputation to the person whose answer was accepted). – EJoshuaS - Stand with Ukraine Jun 24 '17 at 14:34
  • @EJoshuaS i would love to, in fact i was trying to do that but stack-overflow does not allow me to do so, well it says that it has recorded my feedback, i am new here and i think it need certain amount of points for me to be eligible to vote , –  Jun 24 '17 at 18:08