Arithmetic and geometric average error solution - c

My code causes problems connected with giving the final result.
Earlier the program returned that there is an error in division by zero in geometric average. Now the program in arithmetic average returns -2.00000.
Program shows #IND00 error in SredniaGeometryczna(); — it is Geometric Average.
Do you have any idea how to solve it? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int ilosc(int*);
double sredniaArytmetyczna(int, int*);
double sredniaGeometryczna(int, int*);
double sredniaHarmoniczna(int, int*);
int main()
{
int tab[10];
char wybor;
printf("Wybierz, ktora srednia chcesz policzyc: [A]rytmetyczna, [G]eometryczna, [H]armoniczna.\n");
wybor=getch();
int ile;
long double srednia;
switch(wybor)
{
case 'a':
case 'A':
//instrukcje dla arytmetycznej
ile=ilosc(tab);
srednia=sredniaArytmetyczna(ile, tab);
printf("Srednia to: %f",srednia);
//tab* == tab[0]
//printf("Srednia to: %f", sredniaArytmetyczna(ilosc(tab),tab)); - mozna tak samo zrobic za pomoca jednej linijki
break;
case 'g':
case 'G':
//instrukcje dla geometrycznej
ile=ilosc(tab);
srednia=sredniaGeometryczna(ile, tab);
printf("Srednia to: %f",srednia);
break;
case 'h':
case 'H':
ile=ilosc(tab);
srednia=sredniaHarmoniczna(ile, tab);
printf("Srednia to: %f",srednia);
break;
default:
printf("Bledny wybor");
}
return 0;
}
int ilosc(int* tablica)
{
int ileLiczb, i;
printf("Podaj ile liczb chcesz wprowadzic (max 10) : \n");
scanf("%d", &ileLiczb);
i=0;
while(i<ileLiczb)
{
printf("Podaj %d liczbe calkowita: ", i+1);
scanf("%d", &tablica[i]);
++i;
}
return 0;
}
double sredniaArytmetyczna(int iloscLiczb, int *Tab)
{
double wynik=0;
for(int i=0; i<iloscLiczb; ++i)
{
wynik+=Tab[i];
}
return wynik/iloscLiczb;
}
double sredniaGeometryczna(int iloscLiczb, int *Tab)
{
double wynik=0;
for(int i=0; i<iloscLiczb; ++i)
{
wynik=Tab[i]*Tab[++i];
}
return pow(wynik,1/iloscLiczb);
}
double sredniaHarmoniczna(int iloscLiczb, int *Tab)
{
double wynik=0;
for(int i=0; i<iloscLiczb; ++i)
{
wynik+=(1/Tab[i]);
}
return iloscLiczb/wynik;
}

ilosc is supposed to return the count of numbers, but it always returns 0. Change
return 0;
to
return ileLiczb;
And when you're calculating the power in sredniaGeometryczna, you're performing integer arithmetic. You need to change 1/iloscLiczb to 1/(double)iloscLiczb so it will perform floating point arithmetic. Or you could change the declaration of the iloscLiczb parameter to double, and it will be converted automatically when the function is called.
You need a similar change in sredniaHarmoniczna. Change 1/Tab[i] to 1/(double)Tab[i]

Related

How to pass an array from function to function

So I'm fairly new to programming in general and I am working on a project where I have to create a couple of functions.
Everything is fine with the first function but I can't figure out how to pass the values from the first function to the second function
I know that I need to use some pointers to solve the problem but I was just wondering if there was an easier way until i get the hang of using pointers.
Thanks in advance!
Here's my messy code
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <malloc.h>
#define START_SIZE 2
int number_of_branches=0;
typedef struct
{
int Month_num[12];
double sales[12];
bool active;
}Branch;
double function_one(void);
double function_two(void);
double function_three(void);
void function_four(void);
int main()
{
int User_Selection;
do
{
printf("1. Enter sales data.\n2. Add a record for a new branch.\n3. Delete record of an existing branch.\n4. Calculate total sales.\n5. Calculate percentage share of each branch.\n6. Determine the month of peak sales.\n7. Display sales of a specific month.\n8. Display sales of a specific branch.\n0. Done\n");
scanf("%i",&User_Selection);
switch (User_Selection)
{
case 0:
{
printf("Thankyou for your time :)\n");
break;
}
case 1:
{
function_one();
break;
}
case 2:
{
function_two();
break;
}
case 3:
{
function_three();
break;
}
case 4:
{
function_four();
break;
}
default:
{
printf("Please enter a valid input :)\n");
break;
}
}
}
while(User_Selection!=0);
}
double function_one(void)
{
//FILE *file = fopen("Sales.csv","a");
printf("Ender number of branches: ");
scanf("%d",&number_of_branches);
printf("\n");
Branch Branches[number_of_branches];
RecPointer r;
r = (RecPointer)malloc(sizeof(Rec));
//printf("%d",number_of_branches);
for(int b=0; b<number_of_branches; b++)
{
printf("Sales for branch %d: \n",(b+1));
for(int x=0;x<12;x++)
{
printf("Sales for month %d: ",(x+1));
scanf("%lf",&Branches[b].sales[x]);
//printf("\n%lf\n",Branches[b].sales[x]);
//fprintf(file, "%d,%.2lf\n",x,Branches[b].sales[x]);
//fprintf(file,"\n");
}
printf("\n\n");
}
//fclose(file);
printf("Branch\\Month:\t1\t2\t3\t4\t5\t6\t7\t8\t9\t10\t11\t12\n");
for(int b=0; b<number_of_branches; b++)
{
printf("Branch %d:\t",(b+1));
for(int x=0;x<12;x++)
{
printf("%.2lf\t",(Branches[b].sales[x]));
}
printf("\n");
}
return 0;
Branch * Branchplace = (Branch *) malloc(sizeof(Branch));
}
double function_two(void)
{
Branch Branches[number_of_branches++];
printf("Sales for the new branch number %d\n",(number_of_branches));
for(int x=0;x<12;x++)
{
printf("Sales for month %d: ",(x+1));
scanf("%lf",&Branches[number_of_branches].sales[x]);
//printf("\n%d\n",x);
}
printf("\n");
printf("Branch\\Month:\t1\t2\t3\t4\t5\t6\t7\t8\t9\t10\t11\t12\n");
for(int b=0; b<number_of_branches; b++)
{
printf("Branch %d:\t",(b+1));
for(int x=0;x<12;x++)
{
printf("%.2lf\t",(Branches[b].sales[x]));
//printf("\n%lf\n",Branches[b].sales[x]);
//fprintf(file, "%d,%lf",x,Branches[b].sales[x]);
}
printf("\n");
}
return 0;
}
double function_three(void)
{
Branch Branches[number_of_branches];
int deleted_branch;
printf("Which branch do you want to delete?\n");
scanf("%d",&deleted_branch);
Branches[deleted_branch].active=false;
printf("Deleted branch %d\n",deleted_branch);
return 0;
}
void function_four(void)
{
Branch Branches[number_of_branches];
for(int n=0;n<number_of_branches;n++)
{
for(int x=0;x<12;x++)
printf("%.lf\n",Branches[n].sales[x]);
}
}
it is easy to pass an array, no need for pointer
void myfunction(int array[]) {
/** your code here **/
array[0] = 25;
}
void main() {
int arr[] = {1, 2, 4, 5, 6};
int i;
myfunction(arr);
for(i=0;i<4;i++) {
printf("%d\n", arr[i]);
}
}
Output
25
2
4
5
As you can see the value 25 is printing which is actually modified inside the function

Program Variance and Standard Deviation Using Pointer Function

So i'm trying to make a standard deviation and variance function and I can't really figure out why it doesn't work. I'm suppose to call variance in case 3 and SD in case 4. everything else works in the program. If you see anything that doesn't look right let me know.
#include <stdio.h>
#include <math.h>
#define Max_Nums 20
void sortNums(float nums[], int size);
float meanValue(float nums[],int size);
float medianValue(float nums[], int size);
void var_stdDev(float nums[],int size,float *var,float *stdDev);
float sqrtf(float);
int main (void)
{
int NumValue = 0;
float array[Max_Nums];
int i=0;
int choice=0;
float avg=0;
float median=0;
printf("How many numbers do you wish to enter (Max of 20): ");
scanf("%d",&NumValue);
while (NumValue<1 || NumValue>Max_Nums)
{
printf("Invalid response. You must enter a value between 1 and 20.\n");
scanf("%d",&NumValue);
}
printf("Enter %d real numbers: ",NumValue);
for (i=0;i<NumValue;i++)
{
scanf("%f", &array[i]);
}
do
{
sortNums(array,NumValue);
printf("-----Menu-----\n\a");
printf("Enter 1 for mean value\n");
printf("Enter 2 for median value\n");
printf("Enter 3 for variance\n");
printf("Enter 4 for standard deviation\n");
printf("Enter 5 to exit the program\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
avg=meanValue(array,NumValue);
printf("The mean is:%.2f\n",avg);
break;
case 2:
median=medianValue(array,NumValue);
printf("The median is:%.2f\n",median);
break;
case 3:
//printf("The variance is:%.2f",variance);
//break;
case 4:
//printf("The standard deviation is:%.2f\n");
//break;
case 5:
printf("Exiting the program\n");
break;
default:
printf("\nInvalid, try again");
break;
}
}while (choice!=5);
return 0;
}
void sortNums(float nums[], int size)
{
int x;
int y;
float z;
for(x=0;x<(size-1);x++)
{
for(y=0;y<size-x-1;y++)
{
if(nums[y]>nums[y+1])
{
z=nums[y];
nums[y]=nums[y+1];
nums[y+1]=z;
}
}
}
}
float meanValue(float nums[],int size)
{
int i;
float avg;
float sum;
for(i=0;i<size;i++)
{
sum+=nums[i];
}
avg = (sum/size);
return avg;
}
float medianValue(float nums[], int size)
{
float EvenMed;
float Med;
void sortNums(float nums[], int size);
if (size%2==0)
{
EvenMed=(nums[size/2]+nums[size/2-1])/2;
return EvenMed;
}
else
{
Med=nums[size/2];
return Med;
}
}
void var_stdDev(float nums[],int size,float *var,float *stdDev)
{
int i;
float sum;
float meanValue(float nums[],int size);
for(i=0;i<size;i++)
{
sum+=pow((nums[i]-meanValue,2);
}
*var=sum/(float)size;
*stdDev=sqrt(*var);
}
This line is wrong:
sum+=pow((nums[i]-meanValue,2);
This is trying to subtract a function pointer from a number, which makes no sense. You need to call the meanValue function to get the mean, and then subtract that.
Also, you didn't initialize sum before adding to it.
void var_stdDev(float nums[],int size,float *var,float *stdDev)
{
int i;
float sum = 0;
float mean = meanValue(nums, size);
for(i=0;i<size;i++)
{
sum+=pow((nums[i]-mean,2);
}
*var=sum/(float)size;
*stdDev=sqrt(*var);
}
There's no need to have a declaration of meanValue inside var_stdDev, the declaration at the top of the file serves that purpose throughout.
In medianValue(), you have a declaration of sortNums(), but you never call it, so the numbers aren't sorted (it seems like you don't understand the difference between a prototype and a call).
float medianValue(float nums[], int size)
{
float EvenMed;
float Med;
sortNums(nums, size);
if (size%2==0)
{
EvenMed=(nums[size/2]+nums[size/2-1])/2;
return EvenMed;
}
else
{
Med=nums[size/2];
return Med;
}
}
As well explained by #Barmar , OP's code has a number of problems:
void var_stdDev(float nums[],int size,float *var,float *stdDev) {
int i;
// sum not initialize
float sum;
// unneeded function declaration
float meanValue(float nums[],int size);
// missing code to find the mean
for(i=0;i<size;i++) {
// improper call to accumulate the average derivation from the mean
sum+=pow((nums[i]-meanValue,2);
}
...
Recommend a new approach to standard deviation calculation
from here
std = sqrt(n*sum_of_squares - sum_of_x*sum_of_x)/n
Suggested improvements:
Use double for intermediate calculation. float is fine to reduce storage and sometimes for speed. Yet statistics often subtract values leading to significant lost of precision. Use double.
Due to rounding, select data sets could result in a tiny negative number - even if mathematically the result should be >= 0.0. So good to check sign before sqrt().
Handle case when size == 0 and do not perform a run-time division by 0.
void var_stdDev2(const float x[], size_t size, float *var, float *stdDev) {
double sumx = 0.0;
double sumxx = 0.0;
double std = 0.0; // Used when size == 0.0 - or set to NaN
if (size > 0) {
for (size_t i = 0; i < size; i++) {
sumx += x[i];
sumxx += 1.0 * x[i] * x[i];
}
double std = sumxx * size - sumx * sumx;
std = std >= 0.0 ? sqrt(std) : 0.0;
std /= size;
}
if (stdDev) *stdDev = (float) std;
if (var) *var = (float) sqrt(std);
}
Minor bits:
Use a const in the signature as function does not modify nums[].
Array are best indexed with size_t rather than int.

Segmentation fault in C? Arrays, pointers, functions

Hi due to my lack of knowledge in C (second year in college). Compiler ate my code and built the app. But after accepting first value - numOfIntegers it stops working and debugging tells that the segmentation has been failed. SIGSEGV.
How to fix that?
There is the code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/* -----------------------------------------
Program: Question 1
Author: Maggot #9
Email: maggot99999#gmail.com
ID: B00076450
Date: 16 September 2015
Purpose: Who knows?
------------------------------------------ */
void wait(int);
void controlMenu(int, int[]);
int sumOfIntegers(int, int[]);
int avgOfIntegers(int, int[]);
int prodOfIntegers(int, int[]);
int minInteger(int, int[]);
int maxInteger(int, int[]);
const char * getName (int value)
{
static char * arrayName[] = {"first","second","third", "fourth",
"fifth","sixth", "seventh", "eighth", "ninth", "tenth"};
static char badValue[] = "unknown";
if (value<10 && value>=0)
return arrayName[value];
else
return badValue;
}
int getValue(int numOfInteger)
{
int value;
wait(100);
printf("Please enter %s the value:", getName(numOfInteger));
scanf("%d",&value);
return value;
}
void prepare(int * numOfIntegers)
{
wait(300);
printf("Hey again that C stupid lang\n\n");
wait(200);
printf("Please enter how many values you want to put: ");
scanf("%d",numOfIntegers);
return;
}
void initialize(int numOfIntegers,int* arrayNum[])
{
int i;
for(i=0; i<(numOfIntegers); i++)
arrayNum[i] = getValue(i);
wait(500);
printf("\nPlease enter press any button to continue");
wait(100);
getch();
wait(600);
system("cls");
wait(200);
return;
}
int main()
{
int numOfIntegers;
prepare(&numOfIntegers);
int arrayNum[numOfIntegers];
initialize(numOfIntegers, &arrayNum[numOfIntegers]);
controlMenu(numOfIntegers, &arrayNum[numOfIntegers]);
return 0;
}
void controlMenu(int numOfIntegers, int arrayNum[])
{
int i;
char chooseNum;
printf("Please choose any of the following:\n\n1. The integers accepted\n2. The sum of the integers\n3. The average of the integers\n4. The product of the integers\n5. The smallest integer\n6. The largest integer\n0. Exit menu\n");
while(1)
{
chooseNum = getch();
switch(chooseNum)
{
case '0':
return;
case '1':
printf("\n>>> The integers are:");
for(i=0; i<(numOfIntegers); i++)
{
printf("\n>>> The %s is %d", getName((i+1)), arrayNum[i]);
}
break;
case '2':
printf("\n>>> The sum of integers is: %d", sumOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '3':
printf("\n>>> The average of integers is: %d", avgOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '4':
printf("\n>>> The product of integers is: %d", prodOfIntegers(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '5':
printf("\n>>> The smallest integer is: %d", minInteger(numOfIntegers, &arrayNum[numOfIntegers]));
break;
case '6':
printf("\n>>> The largest integer is: %d", maxInteger(numOfIntegers, &arrayNum[numOfIntegers]));
break;
default:
break;
}
printf("\n\n");
}
}
int sumOfIntegers(int numOfIntegers,int arrayNum[])
{
int sum=0;
for(int i=0; i<(numOfIntegers); i++)
sum += arrayNum[i];
return sum;
}
int avgOfIntegers(int numOfIntegers, int arrayNum[])
{
int average=0;
average = sumOfIntegers(numOfIntegers, arrayNum[numOfIntegers])/numOfIntegers;
return average;
}
int prodOfIntegers(int numOfIntegers, int arrayNum[])
{
int i,product=0;
for(i=0; i<(numOfIntegers); i++)
product *= arrayNum[i];
return product;
}
int minInteger(int numOfIntegers, int arrayNum[])
{
int i,smallest=0;
smallest = arrayNum[0];
for(i=1; i<(numOfIntegers); i++)
{
if(smallest>arrayNum[i])
smallest=arrayNum[i];
else
continue;
}
return smallest;
}
int maxInteger(int numOfIntegers, int arrayNum[])
{
int i,largest=0;
largest = arrayNum[0];
for(i=1; i<(numOfIntegers); i++)
{
if(largest<arrayNum[i])
largest=arrayNum[i];
else
continue;
}
return largest;
}
void wait(int ms)
{
Sleep(ms);
return;
}
I can see this fault in getName() which will access memory beyond the array bounds
if (value>10 || value<1)
return arrayName[value];
I believe you are using the wrong test, try
if (value <= 10 && value > 0)
return arrayName[value-1];
assuming value is in the range 1..10 as the textual array implies.
2) a fault in GetValue where you input into numOfInteger but return value, which is uninitialised.
3) in prepare the statement
scanf("%d",&numOfIntegers);
will not pass the input value back to the caller. You should have either passed a pointer to the variable, or returned the value input.
But there might be a lot else wrong. Build your program step by step, checking and trying to break it as you go (with absurd input). Pay attention to compiler warnings - the second fault I listed will generate one.
EDIT okay... let's examine function prepare which after removing noise is
void prepare(int numOfIntegers)
{
scanf("%d",&numOfIntegers);
return;
}
This inputs a value to the function parameter that was passed. This is legal, since you can use a function argument in the same way you can a local variable (perhaps subject to const qualification).
Although it's not a coding error, it does not achieve anything. 1) you usually pass an argument like this to be used by the function in some way, perhaps in its limits and/or in its prompt. 2) Altering the argument like this will not find its way back to the caller.
Here are two ways to deal with this.
A) the function returns the input value
int prepare(void)
{
int value;
scanf("%d", &value); // the address of value
return value;
}
...
int input = prepare();
printf("%d\n", input);
B) the function takes a pointer argument
void prepare(int *value)
{
scanf("%d", value); // value is already a pointer
}
...
int input;
prepare(&input);
printf("%d\n", input);

Advance calculator for finding the mode of a set of numbers

I am currently working on a project for school in which I need to program a calculator to determine the mode of a set of numbers. The parameters are the numbers have to be between 1 and 30. Have to check whether the user inserts a number within that range and that the number must be validated as an integer. I have most of it done except my main issues are the for loop in inputing the numbers and validating them and making sure my mode function works. Any suggestions in fixing the issue with the loop? Also I must use a mode function in order to calculate the mode does the one I'm using work well or is there a better way in going about it?
#include <stdio.h>
#include <string.h>
#include <math.h>
int mode(int *num, int size);
int main(int n, char **p) {
int modearray[], size, i;
printf("What is the size of the Array?");
scanf("%d", &size);
for (i=0; i<modearray[size]; i++) {
printf("Enter an integer value (1 to 30): ");
scanf("%d", modearray[i]);
if (modearray[i] < 1 || modearray[i] > 30) {
printf("Please enter a value within the range");
scanf("%d", modearray[i])
}
else if (sscanf(p[i], "%i", &a[i]) != 1) {
printf("ERROR\n");
return -1;
}
}
}
//used the mode function code frome http://www.dreamincode.net/forums/topic/43713- pointers-and-modefunction/
int mode(int *num, int size) {
int currentnum = (*num);
int count = 0;
int modenum = -1;
int modecount = 1;
for (int x=0; x<size; x++) {
if (currentnum==(*num + x)) count ++;
else {
if(count > modecount) {
modenum = currentnum;
// modecount = count;
x--;
}
currentnum=*(num + x);
count = 0;
}
}
}
As Charlie and user2533527 have already indicated, there are errors in the OP code, and they have offered suggestions regarding those errors. There are a few others that I have noted in my edit of your original code below, that without addressing, the code did not build and/or run. So, if you are interested, look at the inline comments at the bottom of this post to see some corrections to your original code.
This answer is focused on validation of input, per your stated objective ( Have to check whether the user inserts a number within that range and that the number must be validated as an integer ) Specifically it appears you need to verify that the numbers input fall within a range, AND that they all be an integers.
If you move all of the validation steps into one function, such as:
int ValidateInput(char *num)
{
if(strstr(num, ".")!=NULL) return FLOAT;
if (atoi(num) < 1) return SMALL;
if (atoi(num) > 30) return LARGE;
return VALID;
}
then the main user input loop can be easily executed to include specific errors, if any, or continue with data collection by using a switch() statement, such as:
status = ValidateInput(number);
switch(status) {
case VALID:
modearray[i] = atoi(number);
printf("Enter an integer value %d: (1 to 30): ", i+2);
break;
case FLOAT:
printf("float detected, enter an integer");
i--;//try again
break;
case SMALL:
printf("value too small, enter value from 1 to 30");
i--;//try again
break;
case LARGE:
printf("value too large, enter value from 1 to 30");
i--;//try again
break;
default:
//do something else here
break;
}
Altogether, this approach does not use the mode function, rather replaces it with ValidateInput() which ensures only numbers that are integers, and within the stated range are included in the modearray varible.
EDIT to include searching for mode (highest occurring number within group)
My approach will do three things to get mode
sort the array,
walk through the sorted array tracking count of the matches along the way.
keep the highest string of matches.
To do this, I will use qsort() and looping in the mode() function.
int mode(int *num, int size) {
int count = 0;
int countKeep=0;
int modenum = -1;
qsort(num, size, sizeof(int), cmpfunc);
//now we have size in ascending order, get count of most occuring
for (int x=1; x<size; x++)
{
if(num[x-1] == num[x])
{
count++;
if(count > countKeep)
{
countKeep = count;
modenum=num[x];
}
else
{
count = 0;
}
}
}
return modenum;
}
Here is the complete code for my approach: (This code will capture the mode of a string of numbers with only one mode. You can modify the looping to determine if the string is multi-modal, or having two equally occuring numbers)
#include <ansi_c.h> //malloc
//#include <stdio.h>//I did not need these others, you might
//#include <string.h>
//#include <math.h>
int ValidateInput(char *num);
int mode(int *num, int size);
int cmpfunc (const void * a, const void * b);
enum {
VALID,
FLOAT,
SMALL,
LARGE
};
int main(int n, char **p)
{
int *modearray, size, i;
int *a;
char number[10];
int status=-1;
int modeOfArray;
printf("What is the size of the Array?");
scanf("%d", &size);
modearray = malloc(size*sizeof(int));
a = malloc(size);
printf("Enter an integer value 1: (1 to 30): ");
for (i=0; i<size; i++)
{
scanf("%s", number);
//Validate Number:
status = ValidateInput(number);
switch(status) {
case VALID:
modearray[i] = atoi(number);
printf("Enter an integer value %d: (1 to 30): ", i+2);
break;
case FLOAT:
printf("float detected, enter an integer");
i--;//try again
break;
case SMALL:
printf("value too small, enter value from 1 to 30");
i--;//try again
break;
case LARGE:
printf("value too large, enter value from 1 to 30");
i--;//try again
break;
default:
//do something else here
break;
}
}
modeOfArray = mode(modearray, size);
getchar();//to view printf before execution exits
}
int ValidateInput(char *num)
{
if(strstr(num, ".")!=NULL) return FLOAT;
if (atoi(num) < 1) return SMALL;
if (atoi(num) > 30) return LARGE;
return VALID;
}
int mode(int *num, int size) {
int count = 0;
int countKeep=0;
int modenum = -1;
qsort(num, size, sizeof(int), cmpfunc);
//now we have size in ascending order, get count of most occuring
for (int x=1; x<size; x++)
{
if(num[x-1] == num[x])
{
count++;
if(count > countKeep)
{
countKeep = count;
modenum=num[x];
}
else
{
count = 0;
}
}
}
return modenum;
}
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
Assuming that the question is about crashing after the scanf in to array:
int main(int n, char **p) {
int *modearray, size, i;
printf("What is the size of the Array?");
scanf("%d", &size);
modearray = malloc(size * sizeof(int)); //imo size of int is 4 so u can replace with
for (i=0; i<modearray[size]; i++) {
printf("Enter an integer value (1 to 30): ");
scanf("%d", modearray[i]);
if (modearray[i] < 1 || modearray[i] > 30) {
printf("Please enter a value within the range");
scanf("%d", &modearray[i])
}
else if (sscanf(p[i], "%i", &a[i]) != 1) {
printf("ERROR\n");
return -1;
}
}
}

Segmentation fault with no pointers?

Here is my code and problem. The code compiles fine. But when I run it. After I enter the menu option in getMenuOption() "Segmentation Fault (core dumped)" pops up. What is wrong?
I'm new to programming in general. Thanks for the help if its provided.
#include <stdio.h>
#include<math.h>
#define CALCULATE_PI 'a'
#define CALCULATE_GEOMEAN 'b'
#define CALCULATE_HARMMEAN 'c'
void printInstructions (void);
void printMenuOptions (void);
int runMenuOption ();
int getMenuOption ();
int getLimit ();
int calculatePi ();
int calculateGeoMean ();
int calculateHarmonicMean ();
int main(void)
{
printInstructions();
printMenuOptions();
runMenuOption(getMenuOption());
return 0;
}
void printInstructions (void)
{
printf("======================================================\n");
printf("= PI, Geometric Mean, and Harmonic Mean Calculator =\n");
printf("= Please refer to the menu to choose calucaltion =\n");
printf("=Choose desired menu option and press enter to begin =\n");
printf("= Proceed to follow on-screen instructions =\n");
printf("======================================================\n\n\n");
return;
}
void printMenuOptions (void)
{
printf("3 choices: Please enter a VALID letter.\n");
printf("Choice 'a' = Calcualtes PI\n");
printf("Choice 'b' = Calculates Geometric Mean\n");
printf("Choice 'c' = Calculates Harmonic Mean\n\n");
return;
}
int runMenuOption (int getMenuOption())
{
char option;
double answer,
Pi = 0.0,
geoMean = 0.0;
option = getMenuOption();
switch (option)
{
case CALCULATE_PI:
calculatePi(getLimit());
answer = Pi;
break;
case CALCULATE_GEOMEAN:
calculateGeoMean(getLimit());
answer = geoMean;
case CALCULATE_HARMMEAN:
printf("Harmonic Mean");
break;
default:
printf("Incorrect Character!\n");
printf("Try again");
break;
}
printf("Your answer is %5p", &answer);
return 0;
}
int getMenuOption (void)
{
char option;
printf("Please enter choice: ");
scanf("%c", &option);
return option;
}
int getLimit ()
{
int limit;
scanf("%d", &limit);
return limit;
}
int calculatePi (void)
{
int limit,
count = 0,
Pi = 0;
printf("Please enter the PI limit: ");
limit = getLimit();
for (count = 1; count <= limit; count++)
{
Pi += 1 / count;
}
return sqrt(Pi * 6);
}
int calculateGeoMean()
{
int limit,
userValue = 0,
count = 0;
double geoMean = 0;
limit = getLimit();
while(count <= limit)
{
if (userValue <= 0)
printf("Incorrect. Try again");
else
{
count++;
userValue *= userValue;
}
}
geoMean = userValue;
return sqrt(userValue);
}
int calculateHarmonicMean()
{
int limit,
userValue = 0,
count = 0;
double harmMean = 0;
limit = getLimit();
while(count <= limit)
{
if (userValue <= 0)
printf("Incorrect. Try again");
else
{
count++;
userValue *= 1 / userValue;
}
}
harmMean = userValue;
return limit / userValue;
}
This function definition is totally wrong.
int runMenuOption (int getMenuOption())
either you can pass the return value of getMenuOption like this
int runMenuOption (int option)
or
you shouldn't pass any value to this function and call getMenuOption inside runMenuOption. You are doing both, which is incorrect.
int runMenuOption (int getMenuOption())
Here's your problem.
That should be:
int runMenuOption (int opt)
Also, you shouldn't be calling getMenuOption() within runMenuOption since you're calling getMenuOption() as you pass it to runMenuOption as a parameter. runMenuOption should only have a switch statement.
You need to modify the definition of your function from int runMenuOption (int getMenuOption()) to int runMenuOption (int option). In the call, getMenuOption() will be invoked and the output placed into the stack frame of the called function.
According to your declaration of the runMenuOption function, it takes a pointer to a function which returns an integer as its first argument:
int runMenuOption (int getMenuOption())
The function is then called in this line:
option = getMenuOption();
This is perfectly fine. However, the problem lies in this line:
runMenuOption(getMenuOption());
Here you are calling the getMenuOption function and passing the return value into the runMenuOption function. But what you should be doing is passing the function itself as the argument:
runMenuOption(getMenuOption);
The reason you are getting a Segmentation Fault error is because the return value from the getMenuOption function is being treated as a function pointer, and your program is attempting to call a function at that address, which is of course invalid.

Resources