Stuck with a while loop. In the process

I have an array of 100 numbers, and I gave only the values โ€‹โ€‹of the array. How can I print how many array elements I need to add in order to get a sum <than 1768 using WHILE LOOP? The following is what I still have, and I'm stuck ... in advance for help

void setup() { int[] x = new int[100]; int i=0; int sum=0; for(i=0; i<100; i++) { if (i%2==0) { x[i]=i; sum+=x[i]; } } } 
+4
source share
5 answers
  void setup() { int i = 0; int sum = 0; int counter = 0; while (sum < 1768) { sum += i; i += 2; counter++; } System.out.println(counter); } 

You start with an even index 0. Then just skip the odd numbers using i += 2 .
If the number of elements is limited to 100, add i < 200 to the while condition:

 while (sum < 1768 && i < 200) 

An array of 100 even numbers will contain numbers from 0 to 200.

The counter variable will contain the number of additions completed. Its value will be equal to i / 2 , so you can remove this additional variable.

+2
source

You can use this loop, and the element number will be i+1 .

  for(int i=0,k=0; k<1768; i++,k+=x[i]) { System.out.println(x[i]+" - "+k); } 

While the loop is

  int i=0,k=0; while(k<1768; ) { System.out.println(x[i]+" - "+k); i++,k+=x[i]; } 
+2
source

You are skipping indexes in your array. You fill only each slot.In addition, it would be easier to use a while loop to check for the maximum value (1728)

  int[] x = new int[100]; int i = 0; int sum = 0; int max = 1728; while (sum < max && i < 100) { x[i] = i*2; if ((x[i] + sum) < max) { sum += x[i]; } i++; } 
+2
source
 void setup() { int[] x = new int[100]; int maxValue = 1768; int i; int sum=0; while(sum<maxValue) { if (i%2==0) { x[i]=i; sum+=x[i]; i++; } } System.out.println(i+" Elements needed") } 
+1
source

following code:

 void setup() { int[] x = new int[100]; int i=0; int sum=0; for(i=0; i<100; i++) { if (i%2==0) { sum += i; if(sum<1768){ num +=1; } } } } 
-1
source

Source: https://habr.com/ru/post/1439846/


All Articles