Problem statement:- Program to Move all zeros to the end of an Array.
Example:-
Input : Given
size=5
arr[]=[4,0,7,0,0]
Output:
arr[]=[4,7,0,0,0]
Data requirement:-
Input Data:- size, arr
Output Data:-arr
Additional Data:- i, c
Program in C
Input Data:- size, arr
Output Data:-arr
Additional Data:- i, c
Program in C
Here is the source code of the C Program to Move all zeros to the end of an Array.
Code:
#include<stdio.h>
main()
{
printf("Enter the size of the array:");
int size;
scanf("%d",&size);
int arr[size];
int i;
printf("Enter the Element of the array:\n");
for(i=0;i<size;i++)
{
scanf("%d",&arr[i]);
}
int c=0;
for(i=0;i<size;i++)
{
if(arr[i]!=0)
{
arr[c]=arr[i];
c++;
}
}
for(i=c;i<size;i++){
arr[c]=0;
c++;
}
printf("After Move all zeros to end, Array is:");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
}
Enter the size of the array:5
Enter the Element of the array:
4
0
7
0
0
After Move all zeros to end, Array is:4 7 0 0 0
Program in C++
Here is the source code of the C++ Program to Move all zeros to the end of an Array.
Code:
#include<iostream>
using namespace std;
main()
{
cout<<"Enter the size of the array:";
int size;
cin>>size;
int arr[size];
int i,temp=0,j;
cout<<"Enter the Element of the array:\n";
for(i=0;i<size;i++)
{
cin>>arr[i];
}
int c=0;
for(i=0;i<size;i++)
{
if(arr[i]!=0)
{
arr[c]=arr[i];
c++;
}
}
for(i=c;i<size;i++){
arr[c]=0;
c++;
}
cout<<"After Move all zeros to end, Array is:";
for(i=0;i<size;i++)
{
cout<<arr[i]<<" ";
}
}
Enter the size of the array:6
Enter the Element of the array:
9 0 0 10 0 6
After Move all zeros to end, Array is:9 10 6 0 0 0
Program in Java
Here is the source code of the Java Program to Move all zeros to the end of an Array.
Code:
import java.util.Scanner;
public class MoveAllZeorsToEnd {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of the array:");
int size,i;
size=sc.nextInt();
int arr[ ]=new int[size];
System.out.println("Enter the Element of the array:");
for(i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
int c=0;
for(i=0;i<size;i++)
{
if(arr[i]!=0)
{
arr[c]=arr[i];
c++;
}
}
for(i=c;i<size;i++){
arr[c]=0;
c++;
}
System.out.println("After Move all zeros to end, Array is:");
for(i=0;i<size;i++)
{
System.out.print(arr[i]+" ");
}
sc.close();
}
}
Enter the size of the array:
5
Enter the Element of the array:
0 22 0 3 0
After Move all zeros to end, Array is:
22 3 0 0 0
Program in Python
Here is the source code of the Python Program to Move all zeros to the end of an Array.
Code:
arr=[]
size = int(input("Enter the size of the array: "))
print("Enter the Element of the array:")
for i in range(0,size):
num = int(input())
arr.append(num)
c=0
for i in range(0,size):
if arr[i]!=0:
arr[c]=arr[i]
c+=1
for i in range(c,size):
arr[c]=0
c+=1
print("After Move all zeros to end, Array is:")
print(arr)
Enter the Element of the array:
0
0
5
After Move all zeros to end, Array is:
[5, 0, 0]
0 Comments
Please do not Enter any spam link in the comment box