Program to insert 0 after consecutive 1’s

Program to insert 0 after consecutive 1’s

Question:

Insert 0 after the consecutive  1’s appear for k times.

Logic:

  • Get the input bits from the user.
  • Then find the count of consecutive 1’s.
  • If the count is equal to consecutive value then insert 0 after 1.
  • Print the output after insertion.

Algorithm:

  1. Get the input bits and consecutive value from the user.
  2. Then count the consecutive 1’s from the input.
  3. Insert 0 in the next of consecutive of 1 when the count is equal to k.
  4. The insertion made by increment the length of the array and also swapping.
  5. Then print the elements in the array after insertion.

Program:

[code lang=”c”]
#include<stdio.h>
void main()
{
int a[20],i,j,n,k,cnt=0;
clrscr();
printf("enter the length of bits:");
scanf("%d",&n);
printf("enter the consecutive length:");
scanf("%d",&k);
printf("enter the bits:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
if(a[i]==1) //counts the consecutive 1’s
{
cnt++;
}
else //count initializes to zero when it is not consecutive
{
cnt=0;
}
if(cnt==k) //insert 0 next of consecutive 1
{
n++; //increments length of the array
for(j=n-1;j>i;j–) //copies the elements upto i
{
a[j]=a[j-1];
}
a[i+1]=0; //consecutive 1’s next element makes to 0
}
}
for(i=0;i<n;i++) //prints elements after insertion
{
printf("%d",a[i]);
}
getch();
}
[/code]

You might also like:

To find the count of specific character

Vignesh

A Computer Science graduate who likes to make things simpler. When he’s not working, you can find him surfing the web, learning facts, tricks and life hacks. He also enjoys movies in his leisure time.

Leave a Reply

Your email address will not be published. Required fields are marked *