Error finding a range of values in an array - c

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/ .

Related

Why this function gives me first sums correct and then prints bad sums

Write a program that prints the sum of digits for the entered interval limits. To calculate the sum of
digits form the corresponding function.
#include <stdio.h>
void suma(int a ,int b ){
int s= 0,i;
for(i=a;i<=b;i++){
while(i != 0 ){
int br = i % 10;
s+=br ;
i = i/10;
}
printf("%d\n",s);
}
}
int main(void){
int a,b;
printf("enter the lower limit of the interval: "); scanf("%d",&a);
printf("enter the upper limit of the interval: "); scanf("%d",&b);
suma(a,b);
return 0;
}
when i set a to be 11 and b to be 13 program does first 3 sums but after that it doesent stop.why doesn't it stop. But if i set a to 3 digit number program gives me first sum but then gives me random sums
The reason why your code is not working is because in your while-loop, you are changing the value of i, but i is also used in the for-loop. This results in undefined behaviour. In order to fix this, I would suggest breaking the problem up in two functions. One for calculating the sum of a the digits of a number, and one function that adds these sums in a particular range.
int sumNumber(int number) {
int sum = 0;
while(number != 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
int suma(int a ,int b){
int totalSum = 0;
for(int i=a;i<=b;i++){
int sum = sumNumber(i);
totalSum += sum;
}
return totalSum;
}
This way, you are not modifying i in the while-loop.
You are mixing up the two loop variables. As arguments are passed by value just a instead of introducing an unnecessary variable. Minimize scope of variables. Check the return value from scanf() otherwise you may be operating on uninitialized variables.
#include <stdio.h>
void suma(int a, int b) {
for(; a <= b; a++) {
int s = 0;
for(int i = a; i; i /= 10) {
s += i % 10;
}
printf("%d\n", s);
}
}
int main(void){
printf("enter the lower limit of the interval: ");
int a;
if(scanf("%d",&a) != 1) {
printf("scanf failed\n");
return 1;
}
printf("enter the upper limit of the interval: ");
int b;
if(scanf("%d",&b) != 1) {
printf("scanf failed\n");
return 1;
}
suma(a,b);
}
and example run:
enter the lower limit of the interval: 10
enter the upper limit of the interval: 13
1
2
3
4
I was unreasonably annoyed by how the code was formatted. Extra white space for no reason including at end of line, missing white space between some operations, variables lumped together on one line.
It's a really good idea to separate i/o from logic as in #mennoschipper's answer. My answer is as close to original code as possible.
i did function like this and it works now
void suma(int a ,int b ){
int s= 0,i;
int x ;
for(i=a;i<=b;i++){
x = i;
while(x != 0 ){
int br = x % 10;
s+=br ;
x = x/10;
}
printf("%d\n",s);
s = 0;
} }

Not able to find my segmentation fault in this code of t-test

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.

Find a two digit number with recursion

I'm trying to code something in C by using recursion.
The user writes two positive numbers of same length and the program gives him a new number, which is composed like this :
new number unity digit = the smallest digit in the second positive number that the user wrote.
new number ten digit = the biggest digit in the first positive number that the user wrote.
Very simple in fact, here is an example :
5642 and 2371
will give us : 61.
I tried something like this :
#include <stdio.h>
int calcPair(int a, int b){
int number = calcPair(a/10, b/10);
int digit1 = (number/10);
int digit2 = number%10;
if(digit1 < a%10){
digit1 = a%10;
}
if(digit2 > b%10){
digit2 = b%10;
}
return(number);
}
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}
BUT the program doesn't run at all.. and closes.
Maybe someone can correct me ? Or helping me finding the mistake.
Thanks by advance.
Your recursion can never end. Consider the following line in calcPair:
int number = calcPair(a/10, b/10);
This statement will always be executed unless you make it conditional, such as:
int number;
if((a != 0) || (b != 0))
number = calcPair(a/10, b/10);
Eventually, because you're dividing both numbers by 10, this condition will prove FALSE.
Something like this:
int calcPair(int a, int b){
int number;
if (a < 10 && b < 10) {
number = a*10 + b;
} else {
int digita = a%10;
int digitb = b%10;
number = calcPair(a/10, b/10);
if(digita > number/10){
number = digita*10 + number%10;
}
if(digitb < number%10){
number = (number/10)*10 + digitb;
}
}
return number;
}
Also, a small fix to the main:
int main()
{
int a, b, number=0;
printf("Please enter two positive number of same length:\n");
scanf("%d", &a);
scanf("%d", &b);
number = calcPair(a, b);
printf("The two-digit number composed from %d, %d is: %d", a, b, number);
return 0;
}
I think you can refactor your code to be more expressive of your requirement, with a few helper functions.
int greater(int a, int b)
{
return (a>b);
}
int less(int a, int b)
{
return (a<b);
}
int pickDigit(int n, int (*func)(int, int))
{
int ret = n%10;
n /= 10;
while ( n > 0 )
{
if ( fun(n%10, ret) )
{
ret = n%10;
}
n /= 10;
}
return ret;
}
int getBiggestDigit(int n)
{
return pickDigit(n, greater);
}
int gteSmallestDigit(int n)
{
return pickDigit(n, less);
}
int numDigits(int n)
{
int ret = 0;
while (n > 0 )
{
++ret;
n /= 10;
}
return ret;
}
int calcPair(int a, int b)
{
if ( numDigits(a) != numDigits(b) )
{
// Deal with error.
}
return betBiggestDigit(a)*10+getSmallestDigit(b);
}
Whether or not you are allowed to (you did not specify in OP),
here is a recursive search method using strings :
Strings are just an array of char. because you are interested in distinguishing the individual digits within a larger integer, the char data type will be a sufficient size container to facilitate the comparison.
Using arrays of char (strings) within a recursive function with exit criteria of strlen() > 0 will allow you to walk through each integer, and select the appropriate value (min or max).
This approach uses two recursive functions: getMinDigit() and getMaxDigit(), both returning a char representing the maximum value digit, or minimum value digit of their respective original multi-digit integer. These results are then concatenated, and converted back into a two digit integer.
Here is the example code that given:
5642 and 2371
will give us : 61.
char getMinDigit(char *digit)
{
static char val='9';//largest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] < val) //test for smallest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMinDigit(digit);
}
else
{
digit[len-1] = 0;
getMinDigit(digit);
}
}
return val;
}
char getMaxDigit(char *digit)
{
static char val='0'; //smallest single digit base 10
int len=0;
if(strlen(digit) > 0)
{
len = strlen(digit);
if(digit[len-1] > val) //search for largest char in string
{
val = digit[len-1];
digit[len-1] = 0;
getMaxDigit(digit);
}
else
{
digit[len-1] = 0;
getMaxDigit(digit);
}
}
return val;
}
int calcPair(int a, int b)
{
char big[10]={""}, small[10]={""};
char Big, Small;
char result[3]={""};
sprintf(big, "%d", a);
sprintf(small, "%d", b);
Big = getMaxDigit(big); //recursive function
Small = getMinDigit(small); //recursive function
sprintf(result, "%c%c", Big, Small);
return atoi(result);
}
int main(void)
{
int result = calcPair(5642, 2371);
printf("%d", result);
return 0;
//for illustration, hard coded to OP values
//int a, b, number=0;
//printf("Please enter two positive number of same length:\n");
//scanf("%d", &a);
//scanf("%d", &b);
//calcPair(a, b);
//printf("The two-digit number composed from %d, %d is: %d", a, b, number);
//return 0;
}

C while loop infinite loop EOF not working

I am having problem with EOF in my while loop. It does not seem to simply end when EOF is entered but rather does this...
How can I fix it and have the while loop stop and move on. Thanks.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest, int* average, int count);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int count; // number count
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
// Starting prompts
printf("\nHello this program will take in intagers and print");
printf("\nout the largest, smallest and avarage of integers");
printf("\nenterd int.");
printf("\nPlease enter in a integer ");
while (scanf("%d", &integer) != EOF)
{
if (integer != EOF)
{
count++;
findLargestandSmallest(integer, &largest, &smallest, &average, count);
}
else
{
printf("\n \n");
}
}
printf("\nThe largest number entered is %d and the smallest", largest);
printf("\nwas %d and the average of all the numbers is %d\n", smallest, average);
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest, int *average, int count)
{
int x; // just a holder variable
// finds average
x = 0;
x += integer;
*average = (x / count);
// Finds smallest and largest
if (integer <= *smallest)
{
*smallest = integer;
}
if (integer >= *largest)
{
*largest = integer;
}
printf("Enter another integer or <EOF> to quit ");
return;
}
[1]: http://i.stack.imgur.com/P0307.png
UPDATE: I found out what I was doing wrong. Its simple. In the while loop while(scanf("%d", &integer) != EOF) don't set it like that but like this (scanf("%d", &integer)) EOF is understood. To simply call it in DOS use use "Ctrl+Z" on your last input. i.e "number^Z" is how it will look after using "Ctrl+Z" Also here is the better and working code for this problem for anyone else that runs into this.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int sum;
int count;
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
sum = 0;
// Starting prompts
printf("\n--------------------------------------------------------");
printf("\n- Hello, this program will take in intagers and print -");
printf("\n- out the largest, smallest, and avarage of the -");
printf("\n- integers enterd. -");
printf("\n- NOTE: To quit: use \"Ctrl+Z\" on the last integer -");
printf("\n- you enter i.e \"number^z\" -");
printf("\n--------------------------------------------------------\n");
printf("\nEnter integers\n");
// Finds largest and smallest number
while (scanf("%d", &integer))
{
sum += integer;
count++;
findLargestandSmallest(integer, &largest, &smallest);
}
// Finds average
count--;
average = (sum / count);
// End prompts
printf("\n--------------------------------------------------------");
printf("\nThe largest number entered was %d, the smallest", largest);
printf("\nwas %d, and the average of all the numbers is %d.", smallest, average);
printf("\n--------------------------------------------------------");
printf("\nGoodbye\n");
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest)
{
if (integer < *smallest)
{
*smallest = integer;
}
if (integer > *largest)
{
*largest = integer;
}
return;
}
scanf returns the number of elements successfully converted. If it can't convert any, it returns 0. EOF is only returned for end-of-file (on Unix a Control-D).
So you should modify your program to save the return value from scanf and then test it for 0 and EOF separately.
It is also pointless to compare the integer variable with EOF, since all you can possibly know about EOF is that it is a negative integer. Read the scanf manual page and understand what it does and what it returns when and where. That'll solve the puzzle. :-)
Alright, some more hints. Can you make sense of this?
for (;;) {
int successfully_converted = scanf("%d", &integer);
if (successfully_converted == EOF) {
/* Do something when the user is tired of typing. */
puts("Thank you for an enjoyable game.\n");
exit(0);
} else if (successfully_converted == 0) {
puts("This didn't look like an integer\n");
exit(1);
} else {
/* Do something with integer. */
}
}
You are not comparing the integer value with EOF
. You are comparing the scanf result with EOF..
Here as you enter 1 value each time, scanf result will be 1.
So evrrytime the while loop condition fails and infinite loop is generated.
Also if you EOF then what character would you enter to end the loop???
So EOF should not be used.
So I would suggest you to use do while loop
do
{
scanf("%d",&integer);
....
...
printf("enter 1 to continue");
scanf("%d",&check);
}while(check == 1);
Test the result of scanf() against EOF, 0, and 1.
int cnt;
while ((cnt = scanf("%d", &integer)) == 1) {
count++;
findLargestandSmallest(integer, &largest, &smallest, &average, count);
}
if (cnt == 0) {
printf("Something other than an integer was entered.\n");
}
else if (cnt == EOF) {
printf("EOF or I/O Error occurred.\n");
}
// Add the following for debug if desired
else {
printf("Should _never get here!\n");
}
...
UPDATE: I found out what I was doing wrong. Its simple. In the while loop while(scanf("%d", &integer) != EOF) don't set it like that but like this (scanf("%d", &integer)) EOF is understood. To simply call it in DOS use use "Ctrl+Z" on your last input. i.e "number^Z" is how it will look after using "Ctrl+Z" Also here is the better and working code for this problem for anyone else that runs into this.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <limits.h>
void findLargestandSmallest(int integer, int* largest, int* smallest);
int main(void)
{
//Local Declaration
int integer;
int largest;
int smallest;
int average;
int sum;
int count;
//Starting statemnets
smallest = INT_MAX;
largest = INT_MIN;
count = 0;
sum = 0;
// Starting prompts
printf("\n--------------------------------------------------------");
printf("\n- Hello, this program will take in intagers and print -");
printf("\n- out the largest, smallest, and avarage of the -");
printf("\n- integers enterd. -");
printf("\n- NOTE: To quit: use \"Ctrl+Z\" on the last integer -");
printf("\n- you enter i.e \"number^z\" -");
printf("\n--------------------------------------------------------\n");
printf("\nEnter integers\n");
// Finds largest and smallest number
while (scanf("%d", &integer))
{
sum += integer;
count++;
findLargestandSmallest(integer, &largest, &smallest);
}
// Finds average
count--;
average = (sum / count);
// End prompts
printf("\n--------------------------------------------------------");
printf("\nThe largest number entered was %d, the smallest", largest);
printf("\nwas %d, and the average of all the numbers is %d.", smallest, average);
printf("\n--------------------------------------------------------");
printf("\nGoodbye\n");
return 0;
}
void findLargestandSmallest(int integer, int *largest, int *smallest)
{
if (integer < *smallest)
{
*smallest = integer;
}
if (integer > *largest)
{
*largest = integer;
}
return;
}

finding min & max

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

Resources