how can i check such programs on paper ? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 1

how can i check such programs on paper ?

i had the same programm on my Exam , how can i calculate this array in paper , wihtout computer ? this is the programm public class Program { public static void main(String[] args) { int [ ] myArr = {1,2,3,4,5,6,7,8}; int i=0; int r=0; while (i<=myArr.length){ for(int x=0; x<i; x++) { r = r + 1; } i = i+1; } System.out.println(r); } }

6th Feb 2018, 11:06 PM
Tarek Oudir
Tarek Oudir - avatar
3 Respuestas
+ 1
There's no array to "calculate", as the array in this code is never modified... Instead, what you can easily compute without execution of code is the output wich occurs at end of main() function and wich is the value of r at end of execution. You have two loops, one in the other, and the inner loop modify the value of r by incrementing by one with r = 0 at start. by doing i times the loop. The outer loop give i from 0 to the array length, so do loop L times, with L = array length + 1. So: i = 0; r = 0; start outer loop (L=9 times): start inner loop (i=0 times): i = 1; start inner loop (i=1 times): r = r + 1 = 1; i = 2; start inner loop (i=2 times): r = r + 2 = 3; i = 3; start inner loop (i=3 times): r = r + 3 = 6; i = 4; start inner loop (i=4 times): r = r + 4 = 10; i = 5; start inner loop (i=5 times): r = r + 5 = 15; i = 6; start inner loop (i=6 times): r = r + 6 = 21; i = 7; start inner loop (i=7 times): r = r + 7 = 28; i = 8; start inner loop (i=8 times): r = r + 8 = 36; i = 9; exit outer loop, as i <= 8 is false... solution is last value of r = 36, if I've not made mistakes (computed only in my head, never run any code nor use any calculator)...
7th Feb 2018, 4:59 AM
visph
visph - avatar
+ 1
Read closer, I've already specified that: << The outer loop give i from 0 to the array length, so do loop L times, with L = array length + 1. >>
7th Feb 2018, 3:08 PM
visph
visph - avatar
0
many thx for ou answer but how did you know that the loop run only 9 time , its because of the array from 1 to 8 or there is another reason ?
7th Feb 2018, 3:06 PM
Tarek Oudir
Tarek Oudir - avatar