StefanTobler

Lesson 33 Activity 5

Dec 3rd, 2016
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. /*
  2.  * Lesson 33 Coding Activity 5
  3.  *
  4.  Write a method that takes an array of ints, an integer value, and an integer index. The method should insert the value at the given index and move the values afterwards by one.
  5.  
  6.  This method must be called insertValue() and must have the following parameter types:
  7.  
  8.  int[], integer, integer.
  9.  For example, insertValue(a, 100, 2)would change the array {1, 2, 3, 4, 5} to {1, 2, 100, 3, 4}.
  10.  */
  11.  
  12.  
  13. import java.util.Scanner;
  14.  
  15. class Lesson_33_Activity_Five {
  16.  
  17.     public static void insertValue(int x[], int y, int a)
  18.     {
  19.       int flag = 0;
  20.       for (int i = x.length-1; i >= 0; i--)
  21.       {
  22.         if(i == a)
  23.         {
  24.        x[i] = y;
  25.        flag++;
  26.         }
  27.         else if (flag == 0)
  28.           x[i] = x[i-1];
  29.       }
  30.     }
  31.     public static void main(String[] args)
  32.      {
  33.      int x[] = {1,2,3,4,5};
  34.       insertValue(x, 100, 2);
  35.       for (int i = 0; i < x.length; i++)
  36.        System.out.print(x[i] + " ");
  37.     }
  38. }
Add Comment
Please, Sign In to add comment