What's new

C & C++ Multiple of 3

-useR_name-

Forum Veteran
Elite
Joined
Sep 29, 2016
Posts
1,588
Solutions
6
Reaction
1,480
Points
644
Magandang araw mga master, pasuyo naman oh
Ito po yung code ko sa program na
Function that moves the sorted Multiple of 3 in descending order at the beginning followed by the sorted remaining numbers in ascending order.

Problema ko po san ko ilalagay ang (n%3==0) para sa Multiples of 3 na ma sort sa unahan.
Maraming salamat sa makakatulong
[CODE lang="c" title="Multiple of 3"]#include<stdio.h>
#include<stdlib.h>
int main()
{
int *a,n,i,j,temp;
printf("Enter size of array:\n");
scanf("%d",&n);

a=malloc(sizeof(int)*n);

printf("Enter %d Elements:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a);
}

for(i=0;i<n-1;i++)
{
for(j=0;j<n/2;j++)
{
if(a[j]<a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

for(j=n/2;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Sorted Multiple of 3 in descending and remaining in ascending order:\n");
for(i=0;i<n;i++)
{
printf("%d ",a);
}
return 0;

}[/CODE]
 
C++:
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *a,n,temp;
    printf("Enter size of array:\n");
    scanf("%i",&n);

    a=(int*)malloc(sizeof(int)*n);

    printf("Enter %d Elements:\n",n);
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }

    for(int i=0;i<n;i++)
    {
        if(a[i]%3==0)
        {
            for(int k=i;k-1>=0&&(a[k]>a[k-1]||a[k-1]%3!=0);k--){
                temp=a[k];
                a[k]=a[k-1];
                a[k-1]=temp;

            }
        }else{
            for(int k=i;k-1>=0&&a[k]<a[k-1]&&a[k-1]%3!=0;k--){
                temp=a[k];
                a[k]=a[k-1];
                a[k-1]=temp;
            }
        }
    }


    printf("Sorted Multiple of 3 in descending and remaining in ascending order:\n");
    for(int i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
    return 0;

}
 

Similar threads

Back
Top