c program to find average

I think this code is a little bit better. I’ve used the function malloc() instead of the “scattered” declaration int arr[n] (in this case I prefer the old C style).

People already said you the problem relevant to the variable types and some ways to solve the problem. Here there’s another way similar to the others you just saw between the answers.

#include <math.h>
#include <stdio.h>
#include <malloc.h>

#define STR_ORD_SUFFIX(i) (i>3)?"th":(i==0)?"--":(i==1)?"st":(i==2)?"nd":"rd"

int main()
{
    int n, *arr=NULL;
    float per1,per2,per3;

    int sum1=0;
    int sum2=0;
    int sum3=0;

    printf("How many number you have to insert? ");
    scanf("%d",&n);
    if (n<=0)
        return 1;

    arr=malloc(n*sizeof(*arr));
    if (arr==NULL)
        return 2;

    printf("Insert %d number%c\n",n,(n!=1)?'s':'\x0');
    for(int i = 0; i < n; i++){
        printf("%4d%s: ",i+1,STR_ORD_SUFFIX(i+1));
        scanf("%d",&arr[i]);
    }

    for(int i=0;i<=n-1;i++)
    {
        if(arr[i]<0){
            sum1=sum1+1;
        } else if(arr[i]>0){
            sum2=sum2+1;
        } else {
            sum3=sum3+1;
        }
    }

    per1=sum1; per1/=n; per1*=100.0;
    per2=sum2; per2/=n; per2*=100.0;
    per3=sum3; per3/=n; per3*=100.0;

    printf("\n<0 %.6f%%\n>0 %.6f%%\n=0 %.6f%%\n",per1,per2,per3);

    if (arr!=NULL)
        free(arr);

    return 0;

}

Leave a Comment