Home > Software design >  Numbers aren't showing up right
Numbers aren't showing up right

Time:05-30

Hello there! I'm kind of confused , I literally tried every possible sollution i could think of. Yet the program isn't functioning right ! The purpose of this program is to seperate the odd numbers and the pair numbers from one single array and put each one of them on an array! When i execute , and after putting some simple numbers , another random big numbers appear in each array! why is that and how can i fix this ?

void Pairs_impairs(int* n,int T[], int P[], int Imp[]){
int i,j=0;
for (i=0;i<*n;i  ){
    if(T[i]%2==0){
        P[j]=T[i];
        j  ;}
    else{
        Imp[j]=T[i];
        j  ;
}}
*n=j;
}
int main(){
int t[100],p[100],imp[100];
int n;
puts("saisir n :");
scanf("%d",&n);
puts("saisir le tableau : ");
int i;
for(i=0;i<n;i  ){
    scanf("%d",&t[i]);
}
for(i=0;i<n;i  ){
    printf("%d ",t[i]);
}
Pairs_impairs(&n,t,p,imp);
printf("\nLes pairs : ");
for(i=0;i<n;i  ){
    printf("%d ",p[i]);
}
printf("\nLes impairs : ");
for(i=0;i<n;i  ){
    printf("%d ",imp[i]);
}
return 0;

}

CodePudding user response:

The function is incorrect. You need to keep separate indices for the arrays P and Imp within the function. For example

void Pairs_impairs(int* n,int T[], int P[], int Imp[]){
int i,j1=0, j2 = 0;
for (i=0;i<*n;i  ){
    if(T[i]%2==0){
        P[j1]=T[i];
        j1  ;}
    else{
        Imp[j2]=T[i];
        j2  ;
}}
*n=j1;
}

Also you should guarantee that the both arrays P and Imp will have equal number of elements. Otherwise you need to return from the function two indices.

For example

struct Pair
{
    size_t first;
    size_t second;
};

struct Pair Pairs_impairs( const int T[], size_t n, int P[], int Imp[] )
{
    struct Pair p = { .first = 0, .second = 0 };

    for ( size_t i = 0; i < n; i   )
    {
        if ( T[i] % 2 == 0 )
        {
            P[first  ] = T[i];
        }
        else
        {
            Imp[second  ] = T[i];
        }
    }

    return p;
}
  • Related