Write a program to convert the array in such a way that double its value and replace the next number with 0 if the current and next element are the same and rearrange the array such that all 0’s shifted to the end.
For Example:
The given array is: 0 3 3 3 0 0 7 7 0 9
The new array is: 6 3 14 9 0 0 0 0 0 0
Explanation :
- In the given array the second and third element is equal hence doubling the first 3 and making the next index value 0.
- The element which is in the third index doesn’t have any match so leave it as it is. finally, move all zeros to the end
Input Format:
The input contains an integer N which is the size of the array and in the next line N elements will be there
Constraints:
1<=N<=100
1<=arr[i] <=1000
Output Format:
Print the updated array with the space
Sample Input 1
10 0 3 3 3 0 0 7 7 0 9
Sample Output 1
6 3 14 9 0 0 0 0 0 0
Code:
#include<stdio.h>
int main()
{
int n;
int a[100];
int i=0;
scanf("%d",&n);
for(;i<n;i++) scanf("%d",&a[i]);
for(int j=0;j<n-1;j++)
{
if(a[j] == a[j+1])
{
a[j]=2*a[j];
a[j+1]=0;
}
}
i=0;
for(int j=0;j<n;j++)
{
if(a[j]!=0) printf("%d ",a[j]);
else i++;
}
for(int j=0;j<i;j++) printf("0 ");
}
Code language: C/AL (cal)