for(int i=0;i<10;i++)
{
if((i%2)==0)
{
System.out.println(i);
}
}
In the above coding instead of printing "i" values I need to save the values of "i" in array. How can I save the values in an array??
int[] arr=new int[10];
int j=0;
for(int i=0;i<10;i++)
{
if((i%2)==0)
{
arr[j]=i;
j++;
}
}
You can declare an array like int a[10];
and then simply add the i value to the array by doing
a[1] = i;
Declare array and assign value to it.
int a[] = new int[10];
for(int i=0;i<10;i++){
if((i%2)==0){
a[i] = i;
}
}
You have to declare an Array with the length of your for loop
divided by 2
, as you getting the Reminder of the value of i/2
which will give you half of the values of i
:
int length = 10;
int arr_i[] = new int[(int)(length/2)];
int index = 0;
for(int i=0;i<length;i++)
{
if((i%2) == 0){
arr[index] = i;
index ++;
}
}
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.