How to create array at run time according to user input value

In this problem we will learn how to create Array at run time . The program will asked user to enter the value of the array size which you want to create. After this the program will receive the values from the user.

Source Code


package com.ancodingpoint.www;

import java.util.Scanner;
public class Array_Size
{
 public static void main(String[] args)
 {
  Scanner input=new Scanner(System.in);
  int size;
  System.out.print("\nEnter Size of Array: ");
  size=input.nextInt();

  int[] myArray=new int[size];

  for(int i=0;i<size;i++)
  {
   System.out.print("Enter Value "+(i+1)+": ");
   myArray[i]=input.nextInt();
  }
  
  myArray=zeroMax(myArray,size);
  
  for(int i=0;i<size;i++)
  {
   System.out.print(myArray[i]+", ");
  }
 }

 public static int[] zeroMax(int[] myArray, int size)
 {
  for(int i=0;i<size;i++)
  {
   if(myArray[i]==0)
   {
    if((i+1)<size)
    {
     if(myArray[(i+1)]%2==0 && myArray[(i+1)]!=0)
     {
      myArray[i]=myArray[(i+1)]-1;
     }
     else if(myArray[(i+1)]%2==1)
     {
      myArray[i]=myArray[(i+1)];
     }
     else
     {
      myArray[i]=0;
     }
    }
   }
  }
  return myArray;
 }
}

Outout of the Program

Java Array Programming




Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

2 comments:

  1. nice brother., great work for helping student in programming

    ReplyDelete
  2. Why did you say C++ in the title if this is Java?

    ReplyDelete