1

Here's my function that returns the Sum of all pair numbers in an array, and the Average of Odd numbers. Although it outputs the Average as zero for some reason.

 #include <stdio.h>
 
 int MoySom(int Tab[],float* Moyenne,int Length)
 {
     int S=0,C=0;
     *Moyenne=0;
     for(int i=0;i<Length;++i)
     {
         if(Tab[i] % 2 == 0)
         {
             S=S+Tab[i];
         }
         else if(Tab[i] % 2 != 0)
         {
             *Moyenne+=Tab[i];
             ++C;
         }
     }
     *Moyenne=*Moyenne/C;
     return S;
     
 }
 
 void main()
 {
     int Length,Tab[Length];
     float Moyenne;
     printf("Entrer la longeur de tableau: ");
     scanf("%d",&Length);
     for(int i=0;i<Length;++i)
     {
         printf("Entrer l'element %d: ",i);
         scanf("%d",&Tab[i]);
     }
     printf("Somme est:%d\nMoyenne est: %.2f",
         MoySom(Tab,&Moyenne,Length), Moyenne);
 }
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Inferno
  • 47
  • 6
  • 1
    There isn't any guarantee that the parameters will be evaluated in a certain order. [Parameter evaluation order before a function calling in C](https://stackoverflow.com/a/376288) – 001 Dec 02 '22 at 19:26
  • 2
    Unless you are on windows main returns an int. How do you expect `int Length, Tab[Length]` to possible work? – Allan Wind Dec 02 '22 at 19:28
  • 1
    How many elements are in Tab? It is defined before Length is set. – jmq Dec 02 '22 at 19:30
  • 1
    What is the function supposed to do? If there is no odd numbers in `Tab` then `C` is 0 and you divide by zero. If length is negative or zero your Tab is undefined. – Allan Wind Dec 02 '22 at 19:36

1 Answers1

2

At least these problems:

Wrong declaration order

int Length,Tab[Length]; is junk. The declaration of Tab[Length] is happening, yet the value of Length is indeterminate.

Something more like the below. Declare Tab[] after Length is assigned.

 int Length;
 float Moyenne;
 printf("Entrer la longeur de tableau: ");
 scanf("%d",&Length);
 int Tab[Length];

Better code checks the return value of scanf()

 int cnt = scanf("%d",&Length);
 if (cnt != 1 || Length <= 0) {
   Report_Error_and_exit();
 } 
 int Tab[Length];

Parameter evaluation order assumed

Calculate Moyenne, then used use it.

//printf("Somme est:%d\nMoyenne est: %.2f",
//     MoySom(Tab,&Moyenne,Length), Moyenne);

printf("Somme est:%d\n", MoySom(Tab,&Moyenne,Length));
printf("Moyenne est: %.2f", Moyenne);

Potential /0

*Moyenne=*Moyenne/C; may attempt divide by zero. Better code would prevent that.

Unneeded test

     if(Tab[i] % 2 == 0) {
       S=S+Tab[i];
     } else if(Tab[i] % 2 != 0) {
       *Moyenne+=Tab[i];

simplifies to

     if(Tab[i] % 2 == 0) {
       S=S+Tab[i];
     } else {
       *Moyenne+=Tab[i];
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256