Abdelrahman Mohamed Abdelrahman Mohamed - 1 month ago 8x
Java Question

Initializing an int variable as in between 2 values in Java

I'm totally new to Java, and I'm facing a little problem. Sometimes I need to declare a numerical variable in between two values like

int x>=2 && x<=20;
but I can't find a way to do that.

For example I have this problem to solve:

Given an integer, N, print its first 10 multiples. Each multiple N*i (where 1 <= i <= 10) should be printed on a new line in the form: N x i = result.


2 <= N <= 20

How can i solve that, and how can I initialize an int variable "in between two values" ?


It makes no sense to "initialize a variable between 2 values", as a variable can have only 1 value at a time.

You should give the different possible values to the variable one by one :

int i=1;
   System.out.println("N x " + i + " = " + (N*i));

Final result

If you don't want to keep your i variable after you can use a for loop:

for(int i=1; i<= 10; i++){
   System.out.println("N x "+ i +" = " + (N*i));

You can do the same if you want to do this for all the specified values of N:

for(int N = 2; N <= 20; N++)
   for(int i = 1; i <= 10; i++)
      System.out.println("N x "+ i +" = " + (N*i));

About variables with several values

In software programming, the very concept of a variable is a "placeholder to store a value". So by definition, a variable can hold only one value, and is doing so at any time.

When you see variables that seem to hold several values, they are actually holding 1 value, which itself is a container for several values.