Error: CentralTendencies.exe has stopped working, upon clicking Build & Run in codeblocks

0

This code is to find the mean, median and mode for a given sequence of number.

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

int main()
{   /*Inputs*/
int n;
int a[n];
/*Outputs*/
float mean;
int median;
int mode;

printf("Enter the size of array: ");
scanf("%d",&n);
for(int i=0; i<n; i++)
    {
         printf("\nEnter the values of array: ");
         scanf("%d",&a[i]);
    }
/*arrange in ascending order */
int i=0;
for(i=0; i<n-1; i++)
{for(i=0; i<n-1; i++)
{
    if(a[i]>a[i+1])
    {
        int temp = a[i+1];
        a[i+1] = a[i];
        a[i] = temp;
    }
}
}
/*Mean of the series*/
for(i=0; i<n; i++)
{
    int sum = 0;
        sum = sum + a[i];
    mean = sum/n;
}

/*Median of the series*/

I hope the syntax of typecasting here is right, right?

int m = floor((double)n/2);
if(n%2==0)
{
 median = (a[m]+a[m-1])/2;
}
else
{
 median = a[m];
}

/*Mode of the series*/
int count;
int b = 0;
for(i=0; i<n-1; i++)
{
    for(int t=0; t<n; t++)  //Compare a[i] with all the elements of the array
    {if(a[i]==a[t])
        {
                count = 0;
                count++;
        }
     if(b<count)                //Update the new value of mode iff the frequency of one element is greater than that
        {                   // of its preceding element.
            mode = a[i];
        }
    }
}

printf("The value of mean: %f",mean);
printf("\nThe value of mean: %d",median);
printf("\nThe value of mean: %d",mode);
return 0;
}

There were no errors in the code.

I received the following message on the prompt after "CentralT...... working": Process returned -1073741571 (0xC00000FD) execution time : 47.686 s Press any key to continue.

c
codeblocks
asked on Stack Overflow May 20, 2018 by Md Arshad Ali

1 Answer

1

In C you cannot resize an array.

This line

int n;

defines n and leaves its value as garbage, a random value, perhaps 0.

Based on what ever n holds this line

int a[n];

defines a as array to have the number of element as per n now has.

Reading into n in this line

scanf("%d",&n);

does not change the number over a's elements.

To fix this, define a only after n has a well defined, valid value:

scanf("%d",&n);
int a[n];

To really make sure n had been set you want to test the outcome of scanf() like for example:

do {
   if (1 != scanf("%d, &n))
   {
     puts("Bad input or failure reading n!\n");
     continue;
   }
} while (0);
answered on Stack Overflow May 20, 2018 by alk • edited May 20, 2018 by alk

User contributions licensed under CC BY-SA 3.0