I need some help! | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

I need some help!

An array of natural numbers is read and it is required to calculate the sum of the elements symmetrically positioned in the array and display them. for example: a[0]=7 a[1]=3 a[2]=5 a[3]=4 a[4]=10 a[5]=8 a[6]=2 So 2+7=9 8+3=11 10+5=15 4=4

7th Oct 2017, 8:39 AM
Filip German
Filip German - avatar
8 Answers
+ 13
If you had any question about that feel free and ask.
7th Oct 2017, 9:34 AM
Babak
Babak - avatar
+ 12
Here is an example which produces your desired result on a random basis. #include <iostream> #include <vector> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(static_cast<size_t>(time(0))); int n = 2 + rand() % (11 - 2); // [2 , 10] length of array vector<int> arr(n); bool odd_flag; for (auto &i : arr) { i = rand() % 11; // [0, 10] array values range cout << i << endl; } odd_flag = arr.size() % 2 == 0 ? false : true; cout << endl; for (size_t i = 0; i < arr.size() / 2 + odd_flag; ++i) { if (i < arr.size() / 2) { cout << arr.at(i) << " + " << arr.at(n - (i + 1)) << " = "; cout << arr.at(i) + arr.at(n - (i + 1)) << endl; } else cout << arr.at(i) << " = " << arr.at(i) << endl; } } [https://code.sololearn.com/caNd1bpeQGg0]
7th Oct 2017, 9:32 AM
Babak
Babak - avatar
+ 12
In fact, it's a good time for you to expand your knowledge by doing some examples. size_t is a synonym for unsigned int. I used that because it's necessary to compare the length(size) of a vector type (which is similar to an array but with more features and very easy to use) with an unsigned integral (integer) type. Instead of the random number generator, you could feed those variable/container elements manually, but as you see it makes your life a lot easier.
7th Oct 2017, 9:54 AM
Babak
Babak - avatar
+ 12
I'm all ears to answer all of your questions, my friend. ;D
7th Oct 2017, 9:55 AM
Babak
Babak - avatar
+ 12
Thank you Mr. JPM7 to providing us a better solution. @~)~~~~
7th Oct 2017, 11:59 AM
Babak
Babak - avatar
+ 6
HINT:- Use loops(yes loop'S') ,preferably, nested loops(loop inside loop) Try yourself, if you cannot make it, then ask again.
7th Oct 2017, 8:49 AM
Meharban Singh
Meharban Singh - avatar
+ 3
@BabakSheykhan I am a begginer in C++ and since you used other libraries and rand and size_of I'm a bit confused about your example :)) I am looking for something more simple, but thanks for offering help :)
7th Oct 2017, 9:41 AM
Filip German
Filip German - avatar
+ 1
I am blocked at this point, but here is what i wrote Meharban Singh: for (i=0;i<n/2;i++) { for (j=n-1;j>=n/2;j--) { s=v[i]+v[j]; } cout<<s<<endl; s=0; }
7th Oct 2017, 8:59 AM
Filip German
Filip German - avatar