w3resource

C Exercises: Double its value and replace the next number with 0 if current and next value are same and shift all 0's to the end

C Array: Exercise-106 with Solution

Write a C program to convert an array in such a way that it doubles its value. This will replace the next element with 0 if the current and next elements are the same. This program will rearrange the array so that all 0's are moved to the end.

Sample Solution:

C Code:

#include<stdio.h> 
void ZerosAtEnd(int arr1[], int n) 
{ 
    int ctr = 0; 
    for (int i = 0; i < n; i++) 
        if (arr1[i] != 0) 
            arr1[ctr++] = arr1[i]; 
    while (ctr < n) 
        arr1[ctr++] = 0; 
} 
void updateArrayRearrange(int arr1[], int n) 
{ 
    if (n == 1) 
        return; 
    for (int i = 0; i < n - 1; i++) 
	{ 
        if ((arr1[i] != 0) && (arr1[i] == arr1[i + 1])) 
		{ 
            arr1[i] = 2 * arr1[i]; 
            arr1[i + 1] = 0; 
            i++; 
        } 
    } 
    ZerosAtEnd(arr1, n); 
} 
void ArrayPrinting(int arr1[], int n) 
{ 
    for (int i = 0; i < n; i++) 
        printf("%d  ",arr1[i]); 
} 
  
int main() 
{ 
    int arr1[] = { 0, 3, 3, 3, 0, 0, 7,7, 0, 9 }; 
    int n = sizeof(arr1) / sizeof(arr1[0]); 
    printf("The given array is:  "); 
    ArrayPrinting(arr1, n); 
    updateArrayRearrange(arr1, n); 
    printf("\nThe new array is: "); 
    ArrayPrinting(arr1, n); 
    return 0; 
}

Sample Output:

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  

Flowchart 1:

Flowchart: Double its value and replace the next number with 0 if current and next value are same and shift all 0's to the end.

Flowchart 2:

Flowchart: Double its value and replace the next number with 0 if current and next value are same and shift all 0's to the end.

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous C Programming Exercise: Minimum swaps to gather all elements less or equal to k.
Next C Programming Exercise: Concatenate two arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

C Programming - What is the argument for printf that formats a long?

Put an l (lowercased letter L) directly before the specifier.

unsigned long n;
long m;

printf("%lu %ld", n, m);

Ref : https://bit.ly/3dIwfkP