- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Double the first element and move zero to end in C++ Program
In this tutorial, we are going to write a program that doubles the first element and moves all the zeroes to the end of the given array.
We have to double a number when there are tow the same elements in adjacent indices. After that, we have to add a zero to the array.
Move all the zeroes in the array to the end.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; void moveZeroesToEnd(int arr[], int n) { int count = 0; for (int i = 0; i < n; i++) { if (arr[i] != 0) { arr[count++] = arr[i]; } } while (count < n) { arr[count++] = 0; } } void updateAndRearrangeArray(int arr[], int n) { if (n == 1) { return; } for (int i = 0; i < n - 1; i++) { if ((arr[i] != 0) && (arr[i] == arr[i + 1])) { arr[i] = 2 * arr[i]; arr[i + 1] = 0; i++; } } moveZeroesToEnd(arr, n); } void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } int main() { int arr[] = { 2, 3, 3, 4, 0, 5, 5, 0 }, n = 7; cout << "Given Array: "; printArray(arr, n); cout << endl; updateAndRearrangeArray(arr, n); cout << "Updated Array: "; printArray(arr, n); cout << endl; return 0; }
Output
If you execute the above program, then you will get the following result.
Given Array: 2 3 3 4 0 5 5 Updated Array: 2 6 4 10 0 0 0
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements
To Continue Learning Please Login
Login with Google