+ 1

guys!An array with given integer N elements,how to find the sum between fist minus number and last minus number of an array?C++

5th Dec 2018, 11:09 PM
Oyu
3 ответов
+ 2
//in java i would do somthing like this int arr[] = {-21,-44,-37}; System.out.print(arr[0]+arr[arr.length-1]);
5th Dec 2018, 11:18 PM
D_Stark
D_Stark - avatar
+ 1
Since I have seen you are coding in C-like languages, and I am only familiar with java, I am going to explain the idea, can't help you with code. Pass array to the method(optional step) Declare two variables which will hold your numbers (first and last for example) Iterate through the array from the beggining and examine condition: is current element less then zero. When true, assign to first and break the first loop. In the second loop, iterate from the end of the array and when the same condition is met, assign to last. Break the second loop. Return first + last. Hope this will help.
5th Dec 2018, 11:45 PM
vlada
0
int arr[] = {1,2,3,-4,5,6,-7,8,9}; int fNum = 0; int lNum = 1; for(int i =0; i < arr.length;i++){ if (arr[i] < 0 && lNum == 1 ){ fNum = arr[i]; lNum = 0; }else if(arr[i] <0 && fNum != 0){ lNum = arr[i]; } } System.out.println("fMN: " +fNum + " lMN: "+ lNum); hope this helps
6th Dec 2018, 4:52 AM
Phäñtøm Phôëñïx
Phäñtøm Phôëñïx - avatar