C++ Exercises: Multiply each integer in a list three times
Multiply Each Integer in Array Three Times
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 all standard C++ libraries
#include <list> // Include the list container
using namespace std; // Using standard namespace
// Function to create a new list where each element is cubed
list<int> test(list<int> nums) {
list<int> new_list; // Declare a new list to store the cubed elements
list<int>::iterator it; // Declare an iterator for traversing the input list 'nums'
// Iterate through 'nums' list and cube each element, then add it to 'new_list'
for (it = nums.begin(); it != nums.end(); ++it) {
new_list.push_back(*it * *it * *it); // Cube each element and add to 'new_list'
}
return new_list; // Return the new list with elements cubed
}
// Function to display the elements of a list
display_list(list<int> g)
{
list<int>::iterator it; // Declare an iterator for traversing the input list 'g'
// Iterate through 'g' list and display each element
for (it = g.begin(); it != g.end(); ++it) {
cout << *it << ' '; // Print each element followed by a space
}
cout << '\n'; // Move to a new line after displaying all elements
}
int main() {
list<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // Initialize a list 'nums' with integers
cout << "Original list of elements:\n";
display_list(nums); // Display the original list 'nums'
list<int> result_list; // Declare a list to store the result of test() function
result_list = test(nums); // Call the test() function to cube each element
cout << "\nNew list from the said list multiplies each integer three times:\n";
display_list(result_list); // Display the new list with elements cubed
return 0; // Return 0 to indicate successful completion of the program
}
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?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics