Write a Java program to increment all elements of an array by one using for loop. In this Java example, for loop will iterate array items, and within it, we incremented each array element by one.
package NumPrograms; import java.util.Scanner; public class ArrayEleIncrementOne1 { private static Scanner sc; public static void main(String[] args) { int Size, i; sc = new Scanner(System.in); System.out.print("Please Enter the Array size = "); Size = sc.nextInt(); int[] arr = new int[Size]; System.out.format("Enter the Array %d elements : ", Size); for(i = 0; i < Size; i++) { arr[i] = sc.nextInt(); } for(i = 0; i < arr.length; i++) { arr[i] = arr[i] + 1; } System.out.println("\nThe Final Array After Incremented by One"); for(i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
We removed the extra for loop in this Java example and incremented the array element while assigning the value.
package NumPrograms; import java.util.Scanner; public class ArrayEleIncrementOne2 { private static Scanner sc; public static void main(String[] args) { int Size, i; sc = new Scanner(System.in); System.out.print("Please Enter the Array size = "); Size = sc.nextInt(); int[] arr = new int[Size]; System.out.format("Enter the Array %d elements : ", Size); for(i = 0; i < Size; i++) { arr[i] = sc.nextInt(); arr[i] = arr[i] + 1; } System.out.println("\nThe Final Array After Incremented by One"); for(i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Please Enter the Array size = 7
Enter the Array 7 elements : 13 33 54 76 34 98 11
The Final Array After Incremented by One
14 34 55 77 35 99 12
Java program to increment all elements of an array by one using a while loop.
package NumPrograms; import java.util.Scanner; public class ArrayEleIncrementOne3 { private static Scanner sc; public static void main(String[] args) { int Size, i; sc = new Scanner(System.in); System.out.print("Please Enter the Array size = "); Size = sc.nextInt(); int[] arr = new int[Size]; System.out.format("Enter the Array %d elements : ", Size); i = 0; while(i < Size) { arr[i] = sc.nextInt(); arr[i] = arr[i] + 1; i++; } System.out.println("\nThe Final Array After Incremented by One"); i = 0; while(i < arr.length) { System.out.print(arr[i] + " "); i++; } } }
Please Enter the Array size = 8
Enter the Array 8 elements : 11 22 33 44 55 66 77 88
The Final Array After Incremented by One
12 23 34 45 56 67 78 89