Write a C++ program to sort a given array of 0s, 1s and 2s. In the final array put all 0s first, then all 1s and all 2s in last. Consider the image and flowchart given below for reference:
#include <iostream>
using namespace std;
int main()
{
int n,i;
cout<<"Enter size: ";
cin>>n;
int a[n];
cout<<"Enter number(only 0 1 or 2): "<<endl;
for(int i=0;i<n;i++){
cin>>a[i];
}
int temp;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]!=0 && a[i]!=1 && a[i]!=2)
{
cout<<"Numbers other than 0,1,2 were entered. Hence, array not sorted";
return 0;
}
else {
//ascending order
if(a[i]>a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
continue;
}
/*desceding order
if(a[i]<a[j]){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
*/
}
}
}
for(int i=0;i<n;i++)
{
cout<<a[i];
}
}
Write a C++ program to find the element that appears once in an array of integers and every other element appears twice. Consider the image and flowchart given below for reference:
#include <iostream>
using namespace std;
int main()
{
int num_arr[] ={3, 1, 5, 1, 5, 7, 9, 7, 9};
int res = num_arr[0];
for (int i=1; i<9; i++)
{
res = res ^ num_arr[i];
}
cout<<res;
}