+ 18
How can I find the sum of first 5 numbers of an array using for each statement (eg: int num[ ]={1,2,3,4,5,6,7,8,9,10})
31 Answers
+ 28
// using for-each loop
int count = 0;
int sum = 0;
for (int n : num) {
sum += n;
count++;
if (count == 5) break;
}
+ 10
yes thank you Phurinat Puekkham
+ 9
Robert Atkins that solution holds in case of for loop I was talking about for each loop anyways thank you
+ 9
thank you Hamid
+ 8
yes I agree with you Miqdad
+ 6
>= actually not required
once the count becomes 5, break will execute and it will come outof for-each loop. so, no further addition of array elements beyond fifth one.
+ 5
you could act like so:
https://code.sololearn.com/cijSO0YPJ02h/?ref=app
Python wont give error even if elements are less than 5 .
+ 5
static int count = 0;
int sum = 0;
for ( int i : num ){
sum += I;
if ( ++count == 5 ) break;
}
+ 3
This hopefully should help you:
// using for-each loop
int count = 0;
int sum = 0;
for (int n : num) {
sum += n;
count++;
if (count == 5) break;
}
+ 3
hello, 'for each' loops are not appropriate when you want to modify array but you can use 'break' keyword as you want to add only first five numbers.
+ 3
Gajarajan, please check before u comment...
+ 3
sorry i'm wrong
i just confused with that function of break and continue
+ 3
may suggest an easier way of just putting the first 5 element of said given list in a variable of their own and using it as the counter in the for loop.
+ 3
It was nothing.
Happy Coding
+ 3
The problem requires a for-each loop, and no one suggested one. I find this strange. Wikipedia has a nice example. Using that and Phurinat's code, the proper solution can be worked out.
Always pay attention to the requirements, especially on exams.
P.S. My Java is rusty indeed. I assumed "each" should be present in the code, but I read online and it turned out I was wrong. 😝
+ 3
int ar[10] = {1,2,3,4,5,6,7,8,9,10};
int count=5;
int sum;
foreach(int num in ar)
{
if(ar.length<=5)
sum = sum + num;
}
display sum
+ 2
final int SUMTIL= 5;
int sum;
for (int i = 0; i<SUMTIL;++i){
sum +=num[i];
}
then you can change SUMTIL til you get what you need
+ 2
Sujith D My apologies, sometimes it helps to understand what someone is asking lol. the only downside to a for each loop is, you cant use it to find what index you are at, so you could search to see if something was in your array, but you could not easily find what index the value was located at. just a tidbit for you.
+ 2
//for-each loop
int count = 0, sum = 0;
for(int x : num){
sum+=x;
if(++count==5)
break;
}
+ 2
All answer are wrong because the author is asking for foreach loop