Float pointer malloc array receiving into array - c

I am writing a code which requires me to use the malloc function, feed input into an array, determine and print the average as well as how each array value relates to the average. Here is my code
#include <stdio.h>
#include <stdlib.h>
int main (){
int i, n;
float* numbers;
float sum, average;
sum = 0;
printf("How many numbers? ");
scanf("%d", &n);
numbers = (int*)malloc(n * sizeof(int));
printf("Enter %d decimal numbers\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &numbers[i]);
printf("%f\n", &numbers[i]);
sum = sum + numbers[i];
}
printf("%f\n", &sum);
average = sum / n;
printf("The average was %f\n", &average);
for(i = 0; i < n; i++)
{
if (numbers[i] < average)
printf("%f is less than the average\n" , &average);
else if (numbers[i] > average)
printf("%f is less than the average\n" , &average);
else
printf("%f is average\n" , &average);
}
return 0;
}
The print statement in the very first for loop I was using to check whether or not my array is receiving the input properly, it is not, as shown by my output, which is below, my question is why is my array not receiving the values?
How many numbers? 4
Enter 4 decimal numbers
4
0.000000
4
0.000000
4
0.000000
4
0.000000
0.000000
The average was 0.000000
0.000000 is average
0.000000 is average
0.000000 is average
0.000000 is average

A few corrected issues:
1)
numbers = (int*)malloc(n * sizeof(int));
Allocation of memory for int was replaced with the allocation for float.
Cast is not required.
numbers = malloc(n * sizeof(float));
2)
printf("%f\n", &numbers[i]);
The intention is not to print a pointer to number[i] but the number[i] itself.
printf("%f\n", numbers[i]);
This type of issue was corrected for a few other printing places.
3) Final prints was corrected, logically program required printing the numbers[i] not the average
if (numbers[i] < average)
printf("%f is less than the average\n" , numbers[i] );
else if (numbers[i] > average)
printf("%f is more than the average\n" , numbers[i] );
Corrected program:
#include <stdio.h>
#include <stdlib.h>
int main (){
int i,n;
float* numbers;
float sum, average;
sum = 0;
printf("How many numbers? ");
scanf("%d", &n);
numbers = malloc(n * sizeof(float));
printf("Enter %d decimal numbers:\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &numbers[i]);
printf("%f\n", numbers[i]);
sum = sum + numbers[i];
}
printf("%f\n", sum);
average = sum / n;
printf("The average was %f\n", average);
for(i = 0; i < n; i++)
{
if (numbers[i] < average)
printf("%f is less than the average\n" , numbers[i] );
else if (numbers[i] > average)
printf("%f is more than the average\n" , numbers[i] );
else
printf("%f is average\n" , average);
}
return 0;
}
OUTPUT:
How many numbers? Enter 4 decimal numbers:
2
10
5
8
2.000000
10.000000
5.000000
8.000000
25.000000
The average was 6.250000
2.000000 is less than the average
10.000000 is more than the average
5.000000 is less than the average
8.000000 is more than the average

The problem is here:
printf("%f\n", &numbers[i]);
You're printing a reference to numbers[i] instead of the value itself. Try:
printf("%f\n", numbers[i]);
Same thing for all the other places you print values (i.e. sum, average). You're getting 0's when you print it because when you take a pointer to one of those values and cast it to a float it is interpreting that as zero.
Perhaps someone else will be able to enlighten us an exactly why that is (i.e. I'm not sure if that is undefined behavior).
In case you're still confused: the reason you have to pass a reference (&) to the value to scanf, yet the value itself to printf, here's the reason: for scanf you're telling it "please get a float from the console and put it at this location I am specifying (i.e &numbers[i])". When you call printf, you are telling it "please print this value I am giving you (i.e. numbers[i])".

sum=0f;
Writing f so that it is interpreted as float constant instead of double.This doesn't matter much but is good practice and can help striking out a lot of problems.
numbers = (float*)malloc(n * sizeof(float));
Since you want a float array and not an integer array.
printf("%f\n",numbers[i]);
Use '&' only when you want to access the address of variable . To access the value stored in the variable simply use the variable name.
printf("Sum is : %f\n", sum);
Writing proper message in output is important.
for(i = 0; i < n; i++) { if (numbers[i] < average) printf("%f is less than the average\n" , numbers[i]); else if (numbers[i] > average) printf("%f is less than the average\n" , numbers[i]); else printf("%f is average\n" , numbers[i]); }
You need to print the value of number[i] instead of average.
And remember not to use & in printf unless you want to print a address

First fix the malloc
numbers = malloc(n * sizeof(float)); // Not 'int'
then fix the for and next printf
printf("%f\n", numbers[i]); // printf wants a value not an address
printf("%f\n", sum); // same
then
printf("The average was %f\n", average); // same
and the 3 next similar printf.

Related

Average arrays type double

#include <stdio.h>
int main()
{
int n, i;
double num[100], sum = 0.0, average;
printf("Enter the numbers of elements: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("Enter number %d: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %f", average);
return 0;
}
Hi, I have a problem with displaying the average, displaying numbers from space, how to fix it?
Correct format specifier for double would be (you will have to use this)
scanf("%lf", &num[i]);
For printf both %f or %lf will do. Note that when using scanf check the return value of scanf - in case of failure you will take necessary action. (Wrong input given or some other error).
Using the correct format specifier for double as stated by #coderredoc resolves it. Use %lf instead of %f.

Calculating the average of user inputs in c

disclaimer: I'm new to programming
I'm working on this problem
so far ive written this which takes user inputs and calculates an average based on them
#include <stdio.h>
int main()
{
int n, i;
float num[100], sum = 0.0, average;
for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
sum += num[i];
}
average = sum / n;
printf("Average = %.2f", average);
return 0;
}
I'd like the user to enter -1 to indicate that they are done entering data; I can't figure out how to do that. so if possible can someone explain or give me an idea as to how to do it
Thank you!
#include <stdio.h>
int main()
{
int i = 0;
float num[100], sum = 0.0, average;
float x = 0.0;
while(1) {
printf("%d. Enter number: ", i+1);
scanf("%f", &x);
if(x == -1)
break;
num[i] = x;
sum += num[i];
i++;
}
average = sum / i;
printf("\n Average = %.2f", average);
return 0;
}
There is no need for the array num[] if you don't want the data to be used later.
Hope this will help.!!
You just need the average. No need to store all the entered numbers for that.
You just need the number inputs before the -1 stored in a variable, say count which is incremented upon each iteration of the loop and a variable like sum to hold the sum of all numbers entered so far.
In your program, you have not initialised n before using it. n has only garbage whose value in indeterminate.
You don't even need the average variable for that. You can just print out sum/count while printing the average.
Do
int count=0;
float num, sum = 0;
while(scanf("%f", &num)==1 && num!=-1)
{
count++;
sum += num;
}
to stop reading at -1.
There is no need to declare an array to store entered numbers. All you need is to check whether next entered number is equal to -1 and if not then to add it to the sum.
Pay attention to that according to the assignment the user has to enter integer numbers. The average can be calculated as an integer number or as a float number.
The program can look the following way
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int sum = 0;
printf("Enter a sequence of positive numbers (-1 - exit): ");
for (unsigned int num; scanf("%u", &num) == 1 && num != -1; )
{
++n;
sum += num;
}
if (n)
{
printf("\nAverage = %llu\n", sum / n);
}
else
{
puts("You did not eneter a number. Try next time.");
}
return 0;
}
The program output might look like
Enter a sequence of positive numbers (-1 - exit): 1 2 3 4 5 6 7 8 9 10 -1
Average = 5
If you need to calculate the average as a float number then just declare the variable sum as having the type double and use the corresponding format specifier in the printf statement to output the average.

C - how to display the numbers in an array that are lower than the average value of the numbers in the array

#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
system("pause");
}
The code runs fine and gives the correct average of the integers entered but the values that are less than the average comes out as -858993460
You are trying to print out ray[i], but i is currently 20which is outside the index of your array. Did you mean to copy your for loop around that if statement?
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
average=(sum/20);
if (ray[i] < average)
{
printf("The followiing values are less than the average: %d", ray[i]);
}
}
printf("Average = %.2f", average);
system("pause");
}
This gives the "the following integers are below the average" part after each value that is lower than the then average, but I need it to show the values which are below the average together at the end.
The out-of-index issue
As the others have already pointed, your index is out of bounds.
That happens because you've iterated for (i=0; i < 20; i++), which means once you left the for statement you were at i == 20. Your array was allocated with 20 positions, so you can access it from index 0 to 19. The awkward value you get is given because you are accessing "trash", or in other words, invalid positions with unpredictable (or almost) values.
The algorithm issue
Ok, once you got that index thing right, you still need an algorithm that displays the numbers that are lower than the average. You can't just copy your if statement into the loop because you only know the true average value once you've iterated through all of the values (which you are doing just fine).
So what you want is another loop that iterates throughout the array and that if statement inside of it (well, there are other ways to do it without running all of the values again, like sorting the array)
So, this is the algorithm I'll propose you
#include <stdio.h>
#include <stdlib.h>
#define array_size 20
void main()
{
int i;
int ray[array_size];
int sum=0;
float average;
for (i=0; i<array_size; i++)
{
printf("Enter integer #%d: ",i+1);
scanf ("%d", &ray[i]);
sum += ray[i];
}
average=(sum/(float)array_size);
printf("Average = %.2f\n", average);
printf("The following values are less than the average: ");
for (i = 0; i < array_size; i++)
{
if (ray[i] < average)
{
printf("%d ", ray[i]);
}
}
system("pause");
}
This Part in Your Code:
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
//Now i = 20,that is why it left loop
average=(sum/20);
printf("Average = %.2f", average);
if (ray[i] < average) //You are saying if ray[20]<average
{
printf("The following values are less than the average: %d", ray[i]);
}
Now ray[20] is outside the scope because there are 20 elements and array index starts from 0 and goes on to 19, so ray[20] is out of bound access.
I highly recommend you to see this question for better understaning How dangerous is it to access an array out of bounds?.
Secondly You want to print all ray[i] where ray[i] < average so you should run a loop like
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i])
}
}
All That makes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i=0;
int ray[20];
float sum=0.00, average;
for (i=0; i<20; i++)
{
printf("Enter integer #%d",i+1);
scanf ("%d", &ray[i]);
sum=(sum+ray[i]);
}
average=(sum/20);
printf("Average = %.2f", average);
printf("The following values are less than the average:");
for(i = 0; i<20; i++) // i starts from 0 and increase with run of loop
// and loop stops when i>19 so you are not
// accessing forbidden area.
{
if (ray[i] < average){ //check if ray[i] is less than average
printf("%d\n", ray[i]);
}
}
system("pause");
}

global variables not output correctly

#include <stdio.h>
float aver(float*,int);
float max = 0, min = 0; // define global variables
int main()
{
int i;
float num[10]; //input number
for (i = 0 ; i < 10 ; i++)
scanf("%f", &num[i]);
printf("%.2f %.2f %.2f ", max, min, aver(num, i)); //output max ,min and aver
return 0;
}
float aver(float*num,int n)
{
max = min = num[0];
int i;
float sum=0;
for (i=0; i<n-1; i++) {
if (max < num[i])
max = num[i]; //find max
else if (min > num[i])
min = num[i]; //find min
sum += num[i];
}
printf("%.2f %.2f \n ",max,min); //output the max and the min in the array num
return sum/n;
}
Is is what i input and get.
1 2 3 4 5 6 7 8 9 10
9.00 1.00
0.00 0.00 4.50 Program ended with exit code: 0
Why the max and the min in the function aver can output correctly, but in the main function they are 0?
Order of evaluation of function arguments is unspecified. So your code may work as expected on some compilers while may give unexpected results on other compilers.
You should replace
printf("%.2f %.2f %.2f ",max,min,aver(num, i)); //output max ,min and aver
with
{
float average = aver(num, i);
printf("%.2f %.2f %.2f ",max,min, average); //output max ,min and aver
}
to make the code behavior well defined.
from C99 ยง6.5.2.2p10:
The order of evaluation of the function designator, the actual
arguments, and subexpressions within the actual arguments is
unspecified, but there is a sequence point before the actual call.
The order of evaluation of the arguments of printf is unspecified,i.e,max and min can be printed after or before evaluating aver function. In your case,aver is called after printing max and min and then, this function modifies the max and min variables.
To fix it, just call aver as an argument in another printf

C prog figuring out where the bug is

guys help i'm having a problem in getting all the product of odd nums, whenever i enter 1, 3, 2, 2, the product of all odd nums is 0, it's not executing 1*3 =3... can you please point it out why, Thanks in advance...
#include <stdio.h>
#include <conio.h>
int main()
{
int arr[2][2], r, c, sum=0, prod, sumD=0, count=0, count2=0, sumAveEven;
for (r=0; r < 2; r++)
{
for (c=0; c < 2; c++)
{
printf("Enter Numbers: ");
scanf("%d", &arr[r][c]);
if(r==c)
{
sumD = sumD + arr[r][c]; //sum of diagonal pattern
}
if(arr[r][c]%2==0)
{
sum = sum + arr[r][c]; //sum ofeven nums
count= count +1;
sumAveEven = sum / count;
}
else //(arr[r][c]%2 !=0)
{
prod = prod * arr[r][c]; //prod of odd nums
}
//printf("%d ", arr[r][c]);
}
// printf("%d\n", sum);
}
printf("The Sum of All Even Numbers is: %d \n", sum);
printf("The AVERAGE of All Even Numbers is: %d \n", sumAveEven);
printf("The product of All Odd Numbers is: %d \n", prod);
printf("The Sum of Elements in pattern Diagonal is: %d \n", sumD);
//printf("Counter: %d \n", count);
getch();
return 0;
}
prod is not initialized. You need to initialize it to 1
This may not be the only problem but prod is never initialised so
prod = prod * arr[r][c];
will always give unpredictable results. As noted in other answers, you should initialise it to 1 when it is declared.
int ... sum=0, prod=1, ...
You're not initializing prod, which means it could be anything. It was PROBABLY zero in your run, and since anything times zero is zero, that's what you were getting.
In actuality, prod = prod * arr[r][c]; is returning something unknown.
It looks like you probably want to initialize prod to 1 so you have a starting point when calculating your product.
You're not initializing prod. initialize it to 1
int arr[2][2], r, c, sum=0, prod=1, sumD=0, count=0, count2=0, sumAveEven;
You didn't initialize prod. Most of the time it will be set to 0...

Resources