Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Update every array element by multiplication of next and previous values of a given array of integers

C++ Array: Exercise-11 with Solution

Write a C++ program to update every array element by multiplication of next and previous values of a given array of integers.

Pictorial Presentation:

C++ Exercises: Update every array element by multiplication of next and previous values of a given array of integers

Sample Solution:

C++ Code :

#include<iostream>
using namespace std;
 
void replace_elements(int nums[], int n)
{
    if (n <= 1)
      return;
 
    int prev_element = nums[0];
    nums[0] = nums[0] * nums[1];
 
    for (int i=1; i<n-1; i++)
    {
        int curr_element = nums[i];
 
        nums[i] = prev_element * nums[i+1];
 
        prev_element = curr_element;
    }
 
    nums[n-1] = prev_element * nums[n-1];
    }
 
int main()
{
    int nums[] = {0, 1, 3, 4, 5, 6, 7, 8, 10};
    int n = sizeof(nums)/sizeof(nums[0]);
   	cout << "Original array: ";
    for (int i=0; i < n; i++) 
    cout << nums[i] <<" ";
    replace_elements(nums,n);
    cout << "\nNew array elements: ";
    for (int i=0; i < n; i++) 
      cout << nums[i] <<" ";
  return 0;     

}

Sample Output:

Original array: 0 1 3 4 5 6 7 8 10 
New array elements: 0 0 4 15 24 35 48 70 80 

Flowchart:

Flowchart: Update every array element by multiplication of next and previous values of a given array of integers

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to find the smallest element missing in a sorted array.
Next: Write a C++ program to rearrange the elements of a given array of integers in zig-zag fashion way.

What is the difficulty level of this exercise?