0

Array using function argument(BlueJ)

//program to add sum of 10 numbers entered by user in single dimension array... public class check { public static void main(int a[]) { int sum=0,i; for(i=0;i<10;i++) s+=a[i]; System.out.println("Sum ="+s); } } In this, the user have to enter 10 numbers .... If the user enters more than 10 numbers, there is no problem as the compiler will take till index 9... But if the user enters less than 10 numbers, it will show error... So, how can I fix the number of elements to be entered....

27th Mar 2019, 9:58 AM
mn121
mn121 - avatar
5 Answers
+ 4
As explained by "Manu Pandey" Array size must be predefined this is because compiler need to allocate spaces to that many elements to be entered. Simply ,if you will not specify the size of the array(either asking user or considering by your self) you cannot declare an array. Here comes to your assignment. Your teacher perhaps means that "the user will must enter 10 elements only".Hence you can ask user System.out.println("Enter 10 integer elements"); Now, if the user will enter all the ten elements then on pressing enter after entering 10th element the output(sum of elements) will be displayed immediately and the program terminates. If user enter elements (say only 8 elements)less than ten then the remaining elements will be stored 0 by default and the sum will be printed accordingly. I hope this will help you. If you have any further queries you can ask. Remember: JAVA IS SMART!!!
28th Mar 2019, 1:09 AM
Ananya Pandey
Ananya Pandey - avatar
+ 2
This is how an array works.You must specify the array length and cannot change the length through out the program. You can alternatively ask the user to give the number of elements to be entered(I.e. array size) or crate an array of a greater length (say 100)and store 0 in the remaining array indexes after user has given the inputs. I hope this will solve your problem.😊 Keep practicing!!!
27th Mar 2019, 6:13 PM
Manu Pandey
Manu Pandey - avatar
+ 2
Ananya Pandey thanks a lot for giving the suggestion of 0... 😄😄😄
28th Mar 2019, 1:11 AM
mn121
mn121 - avatar
+ 1
It means that there is no way to fix the length of array while entering it's value through public static void main(int a[]) ...
28th Mar 2019, 12:21 AM
mn121
mn121 - avatar
+ 1
Manu Pandey my teacher has told me to "enter 10 numbers using function assignment and print their sum".... So, I cannot do your suggestion...
28th Mar 2019, 12:22 AM
mn121
mn121 - avatar