Creating a histogram in C - c

I have tried many different approaches and it keeps giving me errors...I am definitely not the best coder, please help! I have tried to create a histogram in many different ways, I know the logic behind making a histogram but I do not know how to implement that into C. I need to create a histogram for the x array.
The problem:
Write a computer routine to generate 2,000 values from the given cdf F(x)=x^4/16 on 0<=x<=2. Make a histogram of the 2,000 values and compare it to the theoretical cdf.
int main()
{
int i, b, d, e, j, bins=9, n=2000, y[2000], hist[9];
double seed = 12;
double temp=0, r[2000], temp2=0, x[2000];
int a = 1093, c = 18257, m = 86436;
printf("\nThis program will calculate random variates based on the given CDF\n :x^4/16 on 0<=x<=2\n ");
y[0]=seed;
for (i=1; i<n; i=i+1){
y[i] = (a*y[i-1] + c) % m;
temp = y[i];
r[i] = temp / m;
temp2 = r[i];
x[i] = pow(16*temp2,0.25);
printf("%d %.4lf %lf\n", y[i], r[i], x[i]);
}
//all of my attempts below
/*
int *buildHist(int bins, double min, double max, int n, double *data){
double *hist=malloc(bins*sizeof(int));
if (hist == NULL) return hist;
for (int i=0; i<n; ++i){
int bin=int( (data[i]-min)/((max-min)/(bins)) );
if ( (bin>=0) && (bin<n) ) hist[bin]++;
}
return hist;
}
int max = x[0];
for (d = 1; d < n; d=d+1){
if (x[d] > max)
max = x[d];
}
printf("The max is : %lf\n", max);
int min = x[0];
for (b =1; b<n; b=b+1){
if (x[b] < min)
min = x[b];
}
printf("The min is : %lf\n", min);
//Dividing data into bins
for (b = 0; b < n; b+1){
for (j = 1; j <= bins; j+1){
float bin_max = (float)j / (float)bins;
if (x[b] <= bin_max){
hist[j]+1;
break;
}
}
}
// Plotting histogram
printf("\n\nHistogram of Float data\n");
for (d = 1; d <= bins; d+1){
count = hist[d];
printf("0.%d |", d - 1);
for (e = 0; e < count; e+1)
{
printf("%c", (char)254u);
}
printf("\n");
}
*/
return 0;
}

I guess that your problem is that malloc() returns non-initialized memory. This means that your hist already contains garbage values which you then increment with hist[bin]++.
Use calloc() to allocate hist or use the memset() C library function to clear hist before use.

Related

Run Time Error in finding the probability of prime distance between two nodes of tree

Intro to problem
You are given a tree. If we select 2 distinct nodes uniformly at random, what's the probability that the distance between these 2 nodes is a prime number?
Input
The first line contains a number N: the number of nodes in this tree.
The following N-1 lines contain pairs a[i] and b[i], which means there is an edge with length 1 between a[i] and b[i].
Output
Output a real number denote the probability we want.
You'll get accept if the difference between your answer and standard answer is no more than 10^-6.
#include<stdio.h>
#include<math.h>
int checkprime(int d);
int fact(int m);
void main()
{
int N, i, j, f, p = 0, t, d, x, y, z;
float result;
int a[49999], b[49999];
printf("Enter the number of nodes\n");
scanf("%d", &N);
printf("\n");
for (i = 0; i < N - 1; i++)
{
scanf("%d\t%d", &a[i], &b[i]);//Inputting the nodes
}
for (i = 0; i < N - 1; i++)
{
for (j = i; j < N - 1; j++)
{
d = b[j] - a[i];//Taking distance between nodes
f = checkprime(d);//Checking if it is prime
if (f == 1)
{
p = p + 1;//If found prime,then increasing the number of
//possibilities
}
}
}
x = fact(N);
y = fact(2);
z = fact(N - 2);
y = y * z;
t = x / y;//finding C(N,2).Combination of number of nodes and pair of 2
result = p / t;//finding probability
printf("\n\n%f", result);
}
int checkprime(int d)//function to check prime
{
int k, flag = 1;
for (k = 2; k < d / 2; k++)
{
if (d % k == 0)
{
flag = 0;
}
}
return flag;
}
int fact(int m)//function to calculate factorial
{
int k, r = 1;
for (k = m; k > 1; k--)
{
r = r * k;
}
return r;
}

Crashing with no errors, sorting algorithm

The purpose of the program is to create a random list of 1000 numbers in an array, sort that array, then find the greatest set of numbers within (x, x+50). The program successfully generates and sorts the numbers within the array, but crashes when the (i, j) set finding algorithm starts. The program generates no errors on compiling, and I'm sure the error is simple, but for the life of me I can't find the issue. Thanks in advance you amazing people!
int main( ){
int a, b, temp, i, j, x, y, tempTotal, arrayStartMax;
int finalTotal = 0;
int *info[ARRAY_FULL];
for (i=0; i<ARRAY_FULL; i++){
info[i]=(int*)malloc(sizeof(int));
*info[i]=rand()%1000;
}
for (a = 0; a < ARRAY_FULL; ++a){
for (b = a + 1; b < ARRAY_FULL; ++b){
if (*info[a] > *info[b]){
temp = *info[a];
*info[a] = *info[b];
*info[b] = temp;
}
}
}
for (i=0; i<ARRAY_FULL; i++){
printf("%d\n", *info[i]);
}
for (i = 0; i <= ARRAY_HALF; i++){
x = *info[i];
y = x+ARRAY_HALF;
tempTotal = 0;
for (j = i; j < i+ARRAY_HALF; i++){
if (*info[j] >= x || *info[j] <= y) {
tempTotal++;
}
if (tempTotal > finalTotal) {
arrayStartMax = *info[i];
finalTotal = tempTotal;
}
}
}
printf("Interval should start at %d for maximum numbers in a set.", arrayStartMax);
}
For the purpose of this program I would like to mention that ARRAY_FULL = 100 and ARRAY_HALF = 50.
Your code is throwing segfault because you're walking i out of bounds in this for loop.
for (j = i; j < i+ARRAY_HALF; i++){
if (*info[j] >= x || *info[j] <= y) {
tempTotal++;
}
if (tempTotal > finalTotal) {
arrayStartMax = *info[i];
finalTotal = tempTotal;
}
You set j = i then increment i prior to the comparison. So j will always be less than i.
Limit i in the comparison section of the for loop and it won't segfault.
I don't think the comparison is doing what you want, but you should be able to find your way home from here.

Fill a defined 2D Array with random numbers in C / Average / Max Value

I've created this 2D 21x21 array that has all it's values set to -1. I wrote it to print the address and value and somehow it only starts at [6][19] why?
What i want to do is to replace some of the -1 values with random numbers from 0 to 100 in the same array. I know i need to seed it with srand but i'm having problems connecting the functions since i'm a total beginner in C.
EDIT 1:
Now i can print the whole array and fill it with random numbers. For the -1 values i just assigned directly which for this case its fine.
What i'm trying now is finding the average of all the values and the maximum number, so what i have is:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[21][21], i , j;
for (i = 0; i < 21; i++)
{
for ( j = 0; j < 21; j++)
{
a[i][j] = GetRand(0, 100);
a[7][15] = -1;
a[10][6] = -1;
a[13][5] = -1;
a[15][17] = -1;
a[17][17] = -1;
a[19][6] = -1;
printf("%3d" , a[i][j]);
}
printf("\n");
}
return 0;
}
// random seed
int GetRand(int min, int max);
int get() {
int i, r;
for (i = 0; i < 21; i++)
{
r = GetRand(0, 100);
printf("Your number is %d \n", r);
}
return(0);
}
int GetRand(int min, int max)
{
static int Init = 0;
int rc;
if (Init == 0)
{
srand(time(NULL));
Init = 1;
}
rc = (rand() % (max - min +1) +min);
return (rc);
}
// average
int avg()
float sum=0.0;
for(i = 0; i <= 21; i = i + 1) {
for(j = 0; j <= 21; j = j + 1){
sum = sum + a[21][21];
}
printf("The the average number is %.2f\n", sum/21);
}
//find maximum of all values
int *pv = &a[0][0];
max = min = 0;
for (i = 1; i < i*j; ++i){
if (pv[i] > pv[max])
max =i;
if (pv[i] < pv[min])
min = i;
}
printf("The max value is %d in row %d, col %d\n", pv[max], max/j, max%j);
return 0;
}
For the average function the compiler tells me that expected a declaration before i, which is "float sum=0.0;" but i haven't been able to fix that yet.
For the finding the max function i'm not sure yet what i'm doing there, i just have a vague idea of how it's done...am i going in the right direction?
Thanks!
It's very simple: Just assign the result of your GetRand function to the matrix entry.

Why is my product cost average coming out at 0?

//Program Written By: Andre Chitsaz-zadeh
//Program Written On: 10/7/12
//Program calculates book cost for multiple book orders.
//Program written using multiple functions.
#include <stdio.h>
#define SIZE 5
void inputData();
void processingData(float costs[]);
float costs[5];
float sortedCosts[5];
int main()
{
inputData();
processingData(costs);
}
void inputData()
{
int i = 0;
printf("\nPlease enter five products costs.\n");
while (i < 5)
{
scanf("%d", &costs[i]);
i = i + 1;
}
}
void processingData(float costs[])
{
int i;
int j;
float sum = 0.00f;
float average = 0.00f;
for (i = 0; i < 4; ++i)
{
int j, min, temp;
min = i;
for (j = i + 1; j < 5; ++j)
if (costs[j] < costs[min])
min = j;
temp = costs[i];
costs[i] = costs[min];
costs[min] = temp;
}
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
sortedCosts[i] = costs[i];
for (i = 0; i < 5; ++i)
sum += costs[i];
average = sum / 5;
printf("Product Cost Average = %.2f\n", average);
}
Why is my product cost average coming out as zero? As far as I can see all of my variables are declared as float? I have tried all sorts of combinations and I cant seem to get it to work. I really appreciate your help!
scanf("%d", &costs[i]);
cost[i] is of type float in your program not int.
Use %f conversion specification to read a float.
Also:
temp = costs[i];
Your temp value is of type int but costs[i] is of type float. I don't think it is deliberate.
Use the "%f" modifier in scanf to get a float, rather than "%d".
Also, you
#define SIZE 5
but you use 5's throughout your code rather than SIZE. Use SIZE to reduce the possibility of bugs.
There's nothing wrong with
i = i + 1;
but that is much more commonly written as
i++;

Calculate matrix determinant with partial pivoting Gauss in C

I'm trying to make a simple console application in C which will calculate the determinant of a Matrix using the Gauss partial pivoting elimination method. The 2 problems that I have are :
- someone told me that there are certain matrix-es that don't work with this method ( mathematically speaking ), after reading articles on google, i could not find what is that special case
- after a lot of tests I found out that my program is not working for some matrix-es, after 2 days of "wasting" time editing and undoing, i could not find the problem.
Any type of improvements are more than welcomed. I'm just starting with C.
#include<stdio.h>
#include<cstdlib>
#include<math.h>
#include<conio.h>
#include<windows.h>
// calculate biggest element on column
int indice_max(int dim, int col, float coloana[20][20]) {
float max = 0;
int indice;
for(int i = 1; i <= dim; i++)
if(fabs(max) < fabs(coloana[i][col])) {
max = coloana[i][col];
indice = i;
}
return indice;
}
// permute 2 lines
void permutare_linie(int linie1, int linie2, int dim, float matrice[20][20]) {
float aux;
for(int i = 1; i <= dim; i++) {
aux = matrice[linie1][i];
matrice[linie1][i] = matrice[linie2][i];
matrice[linie2][i] = aux;
}
}
// print matrix
void afisare_matrice(int dimensiune, float matrice[20][20], int lpiv) {
for(int i = 1; i<= dimensiune; i++) {
for(int j = 1; j <= dimensiune; j++) {
if(i == lpiv)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_GREEN);
else
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE );
printf("%4.2f ", matrice[i][j]);
}
printf("\n");
}
}
void main(void) {
float matrice[20][20];
int dimensiune ;
float rezultat = 1;
float pivot;
int lpiv;
int cpiv;
int optiune;
while(1) {
// MENU
printf("ALEGET OPTIUNEA:\n");
printf("1) Calculate matrix determinant\n");
printf("2) Exit\n");
scanf("%d", &optiune);
if(optiune == 1) {
// Read determinant dimension
printf("Matrix dimension:");
scanf("%d", &dimensiune);
// Read determinant
for(int i = 1; i <= dimensiune; i++)
for(int j = 1; j <= dimensiune; j++) {
printf("M[%d][%d]=", i, j);
scanf("%f", &matrice[i][j]);
}
// pivot initial coords
lpiv = 1;
cpiv = 1;
printf("\n----- Entered Matrix -----\n\n");
afisare_matrice(dimensiune, matrice, 0);
printf("\n");
for(int pas = 1; pas <= dimensiune - 1; pas++) {
if(fabs(matrice[lpiv][cpiv]) > fabs(matrice[indice_max(dimensiune, cpiv, matrice)][cpiv])) {
permutare_linie(lpiv, indice_max(dimensiune, cpiv, matrice), dimensiune, matrice);
rezultat = -(rezultat);
}
pivot = matrice[lpiv][cpiv];
for(int inm = 1; inm <= dimensiune; inm++) {
matrice[lpiv][inm] = matrice[lpiv][inm] / pivot;
}
rezultat *= fabs(pivot);
// transform matrix to a superior triangular
for(int l = lpiv+1; l <= dimensiune; l++)
for(int c=cpiv+1; c <= dimensiune; c++) {
matrice[l][c] -= matrice[l][cpiv] * matrice[lpiv][c] / matrice[lpiv][cpiv];
}
for(int i = lpiv + 1; i <= dimensiune; i++)
matrice[i][cpiv] = 0;
// afisam rezultat / pas
printf("----- Step %d -----\n\n", pas);
afisare_matrice(dimensiune, matrice, lpiv);
printf("\nResult after step %d : %4.2f\n\n", pas, rezultat);
lpiv++;
cpiv++;
}
// final result
rezultat = rezultat * matrice[dimensiune][dimensiune];
printf("----- REZULTAT FINAL -----\n\n");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_INTENSITY);
printf("Rezultat = %4.2f\nRezultat rotunjit:%4.0f\n\n", rezultat, floorf(rezultat * 100 + 0.5) / 100);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE );
}
else {
exit(0);
}
}
}
Your code does some division:
matrice[lpiv][inm] = matrice[lpiv][inm] / pivot;
If it happens to divide by zero, an error will occur. I guess this will happen for the zero matrix.
It seems that your code is actually trying to invert the matrix, not just calculate the determinant.

Resources