This code for tolerance analysis compiles and runs, but the output is incorrect and I believe it to be the incorrect handling of the file and the data within the file.
The data in the file is:
PART,2.000,-1,0.050,V
PART,0.975,-1,0.025,V
PART,3.000,+1,0.010,F
GAP,0.000,0.080
The code:
#include <stdlib.h>
#include <string.h>
#include <math.h>
void parsePart(char input[], float*pnom, int*pinp, float*ptol, char*pFV);
void parseGap(char input[], float *pmin, float *pmax);
float meanGap(float nom[], float imp[], int size);
float tolGap(float tol[], int size);
int main()
{
FILE *ptable;
int i, num_of_parts;
int impact[10];
float nominal[10], tolerance[10];
char FV[10];
char input_str[30];
float max, min, gap, tol;
float curr_max, curr_min;
ptable=fopen("D:\\Input.txt", "r");
for(i=0; i<11; i++);
{
fgets(input_str, 30, ptable);
if(input_str[0] == 'P')
{
parsePart(input_str, &nominal[i], &impact[i], &tolerance[i], &FV[i]);
}
else
{
parseGap(input_str, &min, &max);
num_of_parts = i;
}
}
gap = meanGap(nominal, impact, num_of_parts);
tol = tolGap(tolerance, num_of_parts);
curr_max = gap+tol;
curr_min = gap-tol;
printf("Gap mean is: %f inches\n", gap);
printf("Gap tolerance is: %f inches\n", tol);
if(fabs(max-curr_max)< 0.0001 && curr_max > (gap*2)) //they are equal
{
printf("The maximum gap is %f which is greater than the allowed %f\n", curr_max, gap*2);
}
else
{
printf("The maximum gap is %f which is within the allowed %f\n", curr_max, gap*2);
}
if(fabs(min+curr_min)<0.0001 && curr_min < gap-gap)
{
printf("The minimum gap is %f which is less than the allowed %f\n", curr_min, gap-gap);
}
else
{
printf("The minimum gap is %f which is within the allowed %f\n", curr_min, gap-gap);
}
return 0;
}
void parsePart(char input[], float*pnom, int*pinp, float*ptol, char*pFV)
{
int i;
char * field[5];
field[0]=strtok(input, ",");
for(i=1; i<5; i++);
{
field[i] = strtok(NULL, ",");
}
*pnom = atof(field[1]);
*pinp = atoi(field[2]);
*ptol = atof(field[3]);
*pFV = *field[4];
}
void parseGap(char input[], float *pmin, float *pmax)
{
char *field[2];
field[0] = strtok(input, ",");
field[1] = strtok(NULL, ",");
field[2] = strtok(NULL, ",");
*pmin = atof(field[1]);
*pmax = atof(field[2]);
}
float meanGap(float nom[], float imp[], int size)
{
int i;
float sum=0;
for(i=0; i<size; i++);
{
sum += nom[i]*imp[i];
}
return sum;
}
float tolGap(float tol[], int size)
{
int i;
float sum=0;
for(i=0; i<size; i++);
{
sum += tol[i];
}
return sum;
}
The output should look something like:
Actual Gap Mean: 0.025”
Actual Gap Tolerance: 0.085”
The Maximum Gap (0.110”) is (Greater) than specified (0.080”)
The Minimum Gap (-0.060”) is (Less) than the specified (0.000”)
I get a 0 for gap mean and all the other values are incredibly large numbers.
Any and all hints as to where I could be going wrong or need improvement are great. Thank you.
In line 85, char *field[2]; should be char *field[3];.
Firstly arrays impact et al are sized at 10, so
for(i=0; i<11; i++);
Is wrong for 2 reasons:
1) loop should go from 0 to 9
2) a for statement shouldn't have a ; after it, that terminates the whole statement.
typedef struct{char c[6];} String;
String field1,field2,… …;
String *pf1,*pf2,… …;
pf1=field1;
pf2=field2;
…
…
pf1=strtok(input,…
Is the correct (outline) way to code parseGap assuming the longest data in the input file is 5 characters long,
Related
I have written this program for t-test. I'll add other functions as well, but first, I need to find my error. Here's my code
# include <stdio.h>
# include <math.h>
float mean(float x[], int size)
{
float sum = 0.0;
for (int i=0; i<size;i++)
sum += x[i];
return sum/size;
}
float sumsq(float x[], int size)
{
float sum = 0.0;
for (int i=0; i<size;i++)
sum += pow(x[i]-mean(x,size),2);
return sum;
}
int input(n)
{
float x[n];
printf("Enter the values one by one");
for (int i = 0; i<n;i++)
scanf("%f", &x[i]);
return x;
}
void t_check(float x)// Make sure to write this function before each of the t-tests. That is because it is of void type. If the t-test is done before the checking function is declared, then it assumes it's datatype to be "int", and we get an error. So either write the t-check function before those functions, or just define it at the beginning of the program
{
float t_tab;
printf("Enter the tabulated value of t");
scanf("%f",&t_tab);
if (x<t_tab)
printf("We do not have enough evidence to reject the null hypothesis");
else
printf("Reject the null hypothesis");
}
float t_diff_of_means()
{
float x=0.0,y=0.0,s1=0.0,s2=0.0,S=0.0,t=0.0,tcal;
int n,m,a,b;
printf("Enter the number of variables in population 1");
scanf("%d", &n);
a = input(n);
printf("Enter the number of variables in population 2");
scanf("%d", &m);
b = input(m);
x = mean(a,n);
y = mean(b,m);
s1 = sumsq(a, n);
s2 = sumsq(b, m);
S = sqrt((s1+s2)/(n+m-2));
t = (x-y)/(S*sqrt(1.0/n+1.0/m));
t_check(t);
}
int main(void)
{
t_diff_of_means();
return 0;
}
It gives segmentation fault as an error. I'm not able to understand where my code uses any memory uses a part of memory that is not allocated to it
The main issue is you expect input() to read an array floats but you return an int. You should declare the type of the argument n. You cannot return an address to a local variable as it out of scope for caller. The easiest option is to the declare the array variable in main() then pass it to input to populate (pun). (not fixed) Check that return value of scanf() otherwise the variable you expect to be initialized may not be.
t_diff_of_means() is declared to return a float but nothing is returned. Not sure what you want to return so I changed the return type to void.
Tweaked various prompts to make it more them more readable.
#include <stdio.h>
#include <math.h>
float mean(float x[], int size)
{
float sum = 0.0;
for (int i=0; i<size;i++)
sum += x[i];
return sum/size;
}
float sumsq(float x[], int size)
{
float sum = 0.0;
for (int i=0; i<size;i++)
sum += pow(x[i]-mean(x,size),2);
return sum;
}
void input(size_t n, float a[n])
{
printf("Enter the values one by one: ");
for (int i = 0; i<n;i++)
scanf("%f", a+i);
}
void t_check(float x)
{
float t_tab;
printf("Enter the tabulated value of t: ");
scanf("%f",&t_tab);
if (x<t_tab)
printf("We do not have enough evidence to reject the null hypothesis\n");
else
printf("Reject the null hypothesis\n");
}
void t_diff_of_means()
{
float x=0.0,y=0.0,s1=0.0,s2=0.0,S=0.0,t=0.0;
int n,m;
printf("Enter the number of variables in population 1: ");
scanf("%d", &n);
float a[n];
input(n, a);
printf("Enter the number of variables in population 2: ");
scanf("%d", &m);
float b[m];
input(m, b);
x = mean(a,n);
y = mean(b,m);
s1 = sumsq(a, n);
s2 = sumsq(b, m);
S = sqrt((s1+s2)/(n+m-2));
t = (x-y)/(S*sqrt(1.0/n+1.0/m));
t_check(t);
}
int main(void)
{
t_diff_of_means();
return 0;
}
and example run:
Enter the number of variables in population 1: 2
Enter the values one by one: 1
2
Enter the number of variables in population 2: 2
Enter the values one by one: 2
3
Enter the tabulated value of t: 0.05
We do not have enough evidence to reject the null hypothesis
Consider eliminating the variables you only use once (x, y, s1, s2, S, t and t_cal):
t_check(
(mean(a, n) - mean(b, m)) / (sqrt((sumsq(a, n)+sumsq(b, m))/(n+m-2))*sqrt(1.0/n+1.0/m))
);
then I observed that this only depends on variables a, n, b and m so push that calculation into t_check():
void t_check(size_t a_len, float a[a_len], size_t b_len, float b[b_len]) {
float t = (mean(a, a_len) - mean(b, b_len)) / (sqrt((sumsq(a, a_len)+sumsq(b, b_len))/(a_len+b_len-2))*sqrt(1.0/a_len+1.0/b_len));
// ...
}
Then I changed the length types to size_t and used the clearer variable names in t_diff_of_means():
void t_diff_of_means()
{
printf("Enter the number of variables in population 1: ");
size_t a_len;
scanf("%zu", &a_len);
float a[a_len];
input(a_len, a);
printf("Enter the number of variables in population 2: ");
size_t b_len;
scanf("%zu", &b_len);
float b[b_len];
input(b_len, b);
t_check(a_len, a, b_len, b);
}
We could take this another step by observing the two first sections in t_diff_of_means() are very similar, so we could have input() take a prompt and a pointer to an array of floats along with elements read. input() would then need to dynamically allocate the array of floats. This means most of our functions take a array of float and length argument. Let's create a type for that and refactor our functions to use it:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct array {
size_t len;
float *data;
};
float mean(struct array *a)
{
float sum = 0;
for (int i=0; i<a->len;i++)
sum += a->data[i];
return sum/a->len;
}
float sumsq(struct array *a)
{
float sum = 0;
for (int i=0; i<a->len;i++)
sum += pow(a->data[i] - mean(a), 2);
return sum;
}
void input(int prompt, struct array *a)
{
printf("Enter the number of variables in population %d: ", prompt);
scanf("%zu", &a->len);
a->data = malloc(a->len * sizeof(a->data[0]));
//if(!a->data) ...
printf("Enter the values one by one: ");
for (int i = 0; i<a->len;i++)
scanf("%f", &a->data[i]);
}
void t_check(struct array a[2])
{
float t = (mean(a) - mean(a+1)) / (
sqrt(
(sumsq(a) + sumsq(a+1)) / (a[0].len + a[1].len-2)
) * sqrt(1.0/a[0].len + 1.0/a[1].len)
);
printf("Enter the tabulated value of t: ");
float t_tab;
scanf("%f",&t_tab);
if (t<t_tab)
printf("We do not have enough evidence to reject the null hypothesis\n");
else
printf("Reject the null hypothesis\n");
}
int main(void)
{
struct array a[2];
input(1, a);
input(2, a+1);
t_check(a);
}
This would be a good base to add additional functions to.
The program "reads" non negative integers and fills an array of MAX size 100 until it is filled or the user gives -1.Then, function range finds the min and max values and "sends" them to the program.For example,if the user gives 67 54 78 85 -1 the range of values is 54-85.
Problem is, main doesn't print the range. Instead, it prints: "The range of values is 2 - 24576000"
#include <stdio.h>
#include "simpio.h"
int read_data(int A[]);
void range(int sum,int A[100], int *r1, int *r2);
int main()
{
int A[100], sum, max, min,i;
int *r1,*r2;
r1 = &max;
r2 = &min;
printf("Enter the elements of the array, one per line.\n");
printf("Use -1 to signal the end of the list.\n");
sum=read_data(A);
range(sum,A, &max, &min);
printf("The number of elements is: %d\n",sum);
printf("The range of values is %d - %d",min ,max);
}
int read_data(int A[])
{
int i,sum,value;
sum=value=i=0;
while ( i<100 && value !=-1)
{
printf("? ");
value = GetInteger();
if (value != -1)
{
A[i] = value;
value = A[i];
sum+=1;
}
i++;
}
return sum;
}
void range(int sum,int A[100], int *r1, int *r2)
{
int i,max,min;
max =0;
min = 32767;
*r1 = min;
*r2 = max;
for(i=0;i<sum;i++)
{
if (A[i]!=-1)
{
if (A[i]>max)
max = A[i];
if (A[i]<min)
min = A[i];
}
}
*r1 = max;
*r2 = min;
}
One of the problems is that you are not incrementing the value of i in function read_data.
The other problem is that the 4th printf
printf("%The number of elements is: %d\n",sum);
in the function main has a "%T" which is considered by the printf function to be a format specifier(like the one you use for the integer "%d"). If you really want to write % there you should use the format
printf("%%The number of elements is: %d\n",sum);
and it will print only one %.
If you would like to know more about the format specifiers accepted by printf http://www.cplusplus.com/reference/cstdio/printf/ .
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.
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;
}
}
}
i wrote the code but i dont get max value how to find max value
#include <stdio.h>
int main(void)
{
double temp[0];
float max,min;
float i;
short c,j,k;
float sum=0;
float nu[c];
printf("Number of values :");
scanf("%f",&i);
for (c=1;i>=c;c++)
{
printf("values=");
scanf("%f",&nu[c]);
nu[c]=temp[0];
for (j = 0; i>=j; j++)
{
if (temp[0]> nu[c])
{
// nu[c]=temp[0];
max = temp[0];
}
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f\n",max);
}
If you run your compiler with a -Wall (as you should always do), you should have seen the problems :
gcc -Wall -o foo foo.c
foo.c: In function 'main':
foo.c:35:14: warning: unused variable 'k'
foo.c:33:14: warning: unused variable 'min'
foo.c:62:1: warning: control reaches end of non-void function
foo.c:37:4: warning: 'c' is used uninitialized in this function
Here is the source code of a program that works :
#include <stdio.h>
int main(void)
{
float max = 0; // hypothesis : numbers keyed by the users are > 0
float min = 0; // hypothesis : numbers keyed by the users are > 0
int i, c;
float sum = 0;
float nu[100]; // hypothesis : no more than 100 numbers keyed by user
// hypothesis : float type is enough to store numbers keyed by user
printf("Number of values :");
scanf("%d",&i);
for (c = 0; c < i; c++)
{
printf("values=");
scanf("%f",&(nu[c]));
if (nu[c] > max) {
max = nu[c];
}
if (min == 0) {
min = nu[c];
} else if(nu[c] < min) {
min = nu[c];
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f \n", max);
printf("minimum value = %f \n", min);
return 0;
}
You need a single for loop and not nested for loop.
Get input using the first for loop
Assign first element of the input array to variable, call this max
Compare each element of the array using a for loop again
If you get a value greater than max then change max to this value using the below code
if(max< a[i])
max=a[i];
At the end of these steps you can get max value.
Try to put these steps into a C code and it should be fine. There are some problems with the code you have written. I have written a small snippet for you to get input for number of elements and store them into your array for floats.
int number_of_elements;
printf("Enter the number of elements:\n");
scanf("%d", &number_of_elements);
for(i=0;i<number_of_elements;i++)
scanf("%f",&a[i]);
Here's the code with some helpful pointers:
#include <stdio.h>
int main(void)
{
double temp[0];
float max,min;
float i;
short c,j,k; // k isn't used anywhere.
float sum=0;
float nu[c]; // c isn't set at this point so the
// runtime couldn't create an
// array anyway.
printf("Number of values :");
scanf("%f",&i);
for (c=1;i>=c;c++)
{
printf("values=");
scanf("%f",&nu[c]);
// You should set min/max to nu[c]
// if c is 1 regardless.
nu[c]=temp[0]; // Why are you scanning into nu[c]
// then immediately overwriting?
for (j = 0; i>=j; j++) // Why figure out the max *every*
{ // time you enter a value?
if (temp[0]> nu[c])
{
// nu[c]=temp[0];
max = temp[0];
}
}
sum = sum + nu[c];
}
printf("sum = %f \n",sum);
printf("maximum value = %f\n",max);
}
I'd also suggest you go back to my original answer and create your code from that. It really is a much cleaner way of doing it than trying to fiddle around with arrays.
Let me emphasise that: if you're using an array, you're doing it the hard way!
Or this
#include <stdio.h>
int main(void)
{
float temp;
int val,i,j,k;
double sum = 0;
double number[val];
printf("Enter the number of values: ");
scanf("%d", &val);
double number[val];
for(i=1; i <= val ;i++)
{
printf("enter a value: ");
scanf("%lf", &number[i]);
sum = sum + number[i];
}
for(i=1;i<=val;i++)
{
for(j=i+1;j<=val;j++)
{
if(number[i] > number[j])
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sum = %.lf\n", sum);
printf ("Maximum element: %f\n",number[val]);
printf ("Minimum element: %lf\n", number[1]);
}
remove the temp (cant see the point of it)
set max to some initial value (e.g. first element of the array)
and change if statement to:
if (nu[c]> max)
{
max = nu[c];
}
This may not solve your question but nu[c] seems bad allocated to me since c value is undefined