w3resource

C++ Exercises: Multiply each integer in a list three times

C++ Basic Algorithm: Exercise-125 with Solution

Write a C++ program that multiplies each integer three times to create a list from a given list of integers.

Test Data:
({1, 2, 3, 4}-> (1 8 27 64}

Sample Solution:

C++ Code :

#include <bits/stdc++.h>
#include <list>

using namespace std;

list<int> test(list<int> nums) {
	       list<int> new_list;
	       list<int>::iterator it;
           for (it = nums.begin(); it != nums.end(); ++it)
            {
                new_list.push_back(*it * *it * *it);                
            }
      return new_list;
}

display_list(list<int> g)
{
    list<int>::iterator it;
    for (it = g.begin(); it != g.end(); ++it)
        cout << *it << ' ';
    cout << '\n';
}

int main() {

  list<int> nums = {1,2,3,4,5,6,7,8,9};
  cout << "Original list of elements:\n";
  display_list(nums);
  list<int> result_list;
  result_list = test(nums);
  cout << "\nNew list from the said list multiplies each integer three times:\n";
  display_list(result_list);
  return 0;
}

Sample Output:

Original list of elements:
1 2 3 4 5 6 7 8 9

New list from the said list multiplies each integer three times:
1 8 27 64 125 216 343 512 729

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: From a list of strings, create a new list with "$" at the beginning and end.
Next: From a list of strings, create a new list with "$" at the beginning and end.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.