C++ Exercises: Each element of a given list of integers is multiplied by five
Multiply Each Integer in Array by 5
Write a C++ program to create a list from a given list of integers where each element is multiplied by 5.
Test Data:
({ 1, 2, 3}) -> {5, 10, 15}
({2, 4, 7, 8}) -> {10, 20, 35, 40})
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 multiplied by 5
list<int> test(list<int> nums) {
list<int> new_list; // Declare a new list to store the multiplied elements
list<int>::iterator it; // Declare an iterator for traversing the input list 'nums'
// Iterate through 'nums' list and multiply each element by 5, then add it to 'new_list'
for (it = nums.begin(); it != nums.end(); ++it) {
new_list.push_back(*it * 5);
}
return new_list; // Return the new list with elements multiplied by 5
}
// 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 multiply each element by 5
cout << "\nNew list from the said list where each element is multiplied by 5:\n";
display_list(result_list); // Display the new list with elements multiplied by 5
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 where each element is multiplied by 5: 5 10 15 20 25 30 35 40 45
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Create an array of odd numbers and specific lengths from an array.
Next: Multiply each integer in a list three times.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics