Dilu
Dilu

Reputation: 21

changing value of the last 3 index in an array

i am currently learning java, bellow are my current code

import java.util.*;
public class numbers {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("How big is the array: ");
        int size = input.nextInt();
        int[] numb = new int[size];
        for (int i=0;i<size;i++)
        {
            numb[i] = i;
        }
        
        //change value of last 3 index of array to 0

        for (int i =0; i<size;i++)
        {
            System.out.println(numb[i]);
        }        
    }
}

Here are how the output if i ran it currently

How big is the array: 7
0
1
2
3
4
5
6

how could i change the value of the last 3 index to 0? bellow are my expected output

How big is the array: 7
0
1
2
3
0
0
0

thanks in advance!

Upvotes: 1

Views: 50

Answers (4)

Sumit
Sumit

Reputation: 1119

Just subtract 3 from the size, it will work perfectly

for (int i=0;i<size-3;i++)
        {
            numb[i] = i;
        }

Upvotes: 0

Tony Scott
Tony Scott

Reputation: 205

This should do the trick:

//change value of last 3 index of array to 0
        if (size <= 3) {
            for (int i =0; i<size;i++)
            {
                numb[i] = 0;
            }  
        } else {
            for (int i=size-3; i<size; i++) {
                numb[i] = 0;
            }
        }

Upvotes: 0

Mark
Mark

Reputation: 84

You mean?

//change value of last 3 index of array to 0   
        for (int i = size-1; i >= size-3;i--)
        {
            numb[i] = 0;
        }
        
        //OR
        
        for (int i = size-2; i<size;i++)
        {
            numb[i] = 0;
        } 
        
        for (int i = 0; i<size;i++)
        {
            System.out.println(numb[i]);
        } 

Upvotes: 0

Praveen
Praveen

Reputation: 9345

You can loop through the last 3 index and set it to 0.

for (int i = 1; i <= 3; i++) {
    num[num.length - i] = 0;
}

Upvotes: 2

Related Questions