Famela Marie
Famela Marie

Reputation: 1

How can I find the value of the entered elements on array in C

I need to get the percentage of each value inside the array. I already got the sum of the elements. For example I entered 4 elements which is 1 2 2 1,the sum will be 6. Percentage will be: 1 is 16.67percent of the sum 2 is 33.33 percent of the sum 2 is 33.33 percent of the sum 1 is 16.67percent of the sum

I don't know how can I get the value inside the entered elements on array.

#include <stdio.h>

int main(){
    int i,sum,size;
   
    printf("ENter array length : \n");
    scanf("%d",&size);
    int ara[size];
    printf("Enter array elements:\n");
    
    for(i = 0; i < size;  i++){
        scanf("%d", &ara[i]);
    }
    sum=0;
    
    for(i = 0; i < size; i++){
        sum+=ara[i]; 
    }    
    return 0;
}

Upvotes: 0

Views: 53

Answers (1)

David Grayson
David Grayson

Reputation: 87406

The C code for calculating the percentage of element i would be:

int percentage = 100 * ara[i] / sum;
printf("%d\n", percentage);

Note that we do the multiplication first, since the division introduces rounding errors.

I'm just assuming that the elements are small enough so that 100 * ara[i] doesn't overflow your system's int type. You can cast 100 to a larger type if that's not true.

Here is alternative code if you want a floating point answer:

float percentage = 100.0 * ara[i] / sum;
printf("%.2f\n", percentage);

Upvotes: 1

Related Questions