Calculating the mean of an array - c

#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
int j, sum = 0;
for (j = 0; j < i; j++)
{
sum = arr[j] + sum;
}
return (float)sum/i;
}
int main()
{
int arr[100] = { NULL };
int i, n, sum = 0;
printf("How many numbers would you like to enter?");
scanf_s("%d", &n);
while (n > 100 || n < 0)
{
printf("Amount of numbers should be less than 0 and more than 100\n");
scanf_s("%d", &n);
}
for (i = 0; i < n; i++)
{
scanf_s("%d", &arr[i + 1]);
}
printf("%f", mean(i-1, arr[i]));
system("pause");
}
When I run the code it gives me a read access error. The problem is with the mean() function I created but I don't know what's wrong. Help?

When I run the code it gives me a read access error. The problem is with the mean() function
Although the mean() function produces read access error, the actual problem is here:
printf("%f", mean(i-1, arr[i]));
You are not passing an array to your function, but its element (it is one past the end of what was written, too, so even the value that you pass is undefined).
You need to pass i for the length, because your mean() treats it as an exclusive upper limit, and you also need to pass arr for the array:
printf("%f", mean(i, arr));
Indexing problem when reading the data also needs to be fixed - you need to remove + 1:
scanf_s("%d", &arr[i]);
// ^

Try this:
#include<stdio.h>
#include<stdlib.h>
double mean(int i, int arr[])
{
int j, sum = 0;
for (j = 0; j < i; j++)
{
sum = arr[j] + sum;
}
return (float)sum/i;
}
int main()
{
int arr[100] = { 0 };
int i, n, sum = 0;
printf("How many numbers would you like to enter?");
scanf("%d", &n);
getchar();
while (n > 100 || n < 0)
{
printf("Amount of numbers should be more than 0 and less than 100\n");
scanf("%d", &n);
getchar();
}
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
getchar();
}
printf("%lf", mean(n, arr));
getchar();
}
Your call to the mean function was wrong. You have to pass the entire array, not just one element. Change arr[i] to arr.
Other minor modifications are what I did to make it run on my system. If it works for you otherwise, then great.

Related

Unexpected output - Choosing the lowest number from an array

I want to find the smallest number from the numbers in an array entered by the user.
The output I am getting for the program is a vague number -858993460. This is generally because of a type mismatch but they seem alright here. Not able to think of a solution. Thanks for the help!
```
//
#include<stdio.h>
int main()
{
int a;
int i;
int num[25];
printf("Enter the 25 numbers:");
for (i = 0; i <= 24; i++)
{
scanf("%d", &num[i]);
}
for (i = 0; i <= 24; i++)
{
a = num[i];
if (a < num[i+1])
{
a = a;
}
else
a = num[i+1];
}
printf("Lowest number is %d\n", a);
return 0;
}
Hope this will work for you. Just remove the else statement and bring a=num[i] inside if statement and consider the first element is the minimum element by doing this a = num[0]
#include<stdio.h>
int main()
{
int a;
int i;
int num[25];
printf("Enter the 25 numbers:");
for (i = 0; i <= 24; i++)
{
scanf("%d", &num[i]);
}
a = num[0];
for (i = 0; i <= 24; i++)
{
if (num[i] < a)
{
a = num[i];
}
}
printf("Lowest number is %d\n", a);
return 0;
}
Your problem is the i+1 statement. When on i = 24, the next index is out of bounds. Instead of throwing an error, C lets you access that part of memory, giving you whatever garbage data was stored there. That's why you're getting such a random result.

Solving using function in c

Problem is:Write a function that returns the average value of the elements in the array.
This is a solved problem, however I need to solve it via function, and not sure how to do it..Can anyone help please?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[20], num, i; //array declaration
double avg = 0, sum = 0; //variable declaration
printf("Enter the numbers of average: ");
scanf("%d", &num); //get inpur from user to numberof elements
printf("Enter the numbers: \n");
for (i = 1; i <= num; i++)
{ //loop for get input numbers
scanf("%d", &arr[i]);
}
for (i = 1; i <= num; i++)
{
sum = sum + arr[i]; //loop for calculating sum
avg = sum / num; //calculate average
}
printf("Average of entered numbers are: %f", avg);
getch(); //display result on the screen
return 0;
}
A function like this should help:
double calc_average(const int *array, size_t num_elements)
{
double sum = 0.0;
size_t i;
for(i = 0; i < num_elements; i++)
{
sum += array[i];
}
return (sum / num_elements);
}
with this prototype:
double calc_average(const int *array, size_t num_elements);
which you can call with:
avg = calc_average(arr, num);
but you'll need to fix your input loop in main() to start at 0:
for (i = 0; i < num; i++)
and also in main() you should make sure you don't overrun the bounds of your array:
if(num > 20)
{
fprintf(stderr, "Error: too many numbers\n");
return 1;
}
This is simple code. Hopefully, I didn't make any simple mistakes.

Couldn't get the reason for the fault in the code

This is a program to print the smallest value and its position in an array (defined by user).
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[n];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<=n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
But upon running it, it shows following error:
Segmentation fault (core dumped)
What can be the possible reason(s) for it?
First error, as stated in one of the comments, is declaring an array of size n before even knowing how much n is.
Second mistake is for loop in your main function that goes from 0 to n, i.e. index of an array is out of bounds.
Try this:
int main() {
int n = 0, j = 0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for (j = 0; j < n; j++) {
printf("a[%d] = ", j + 1);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
If this solved your problem, please mark it.
First of all:
int n, j;
both uninitialized. Initialize them otherwise you will get garbage values.
int n = 0, j = 0;
What happens if n by chance (very likely) is 0 in following line?
int a[n];
You allocate 0 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will get segmentation fault in for() loop below because your loop is trying to put 10 elements where you allocated no memory at all.
What happens if uninitialized n by chance (very likely) is 2^32 * 4 bytes (ints max)?
int a[n];
You allocate 2^32 bytes for array a[]. You then enter 10 in following line
scanf("%d", &n);
You will not get segmentation fault but you will allocate 2^32 * 4 bytes of memory for your program and you will use only 10
Second if that is not enough:
for (j = 0; j <= n; ++j)
scanf("%d", arr[n];
will access 11th element of array which is undefined behavior, and you might even get segmentation fault there. As you know arrays in C arrays are indexed from 0 to n - 1 (if n is size of array).
Third your loop inside function:
for(i=0; i<=n-1; i=i+1)
is the same as:
for(i=0; i < n; ++i)
And finally, you have a bug in your code, I believe:
if(a[i]<a[0])
should be:
if (a[i] < smallest)
because it is most likely that you would like compare other number to already smallest element not to a[0]. Here is my code
#include <stdio.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i = 0, k=0;
for(i=0; i<n; ++i) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int a[n];
for(j=0; j<n; ++j) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
The version above is legit for C99 and up standards. If you are using C89 and earlier compilers you are stack with fixed size as mentioned in #Saurabh's answer or preferably use malloc().
Here is malloc() version:
#include <stdio.h>
#include <stdlib.h>
int position_smallest(int a[],int n) {
int smallest = a[0];
int i=0,k=0;
for(i=0; i<=n-1; i=i+1) {
if(a[i]<smallest) {
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main() {
int n=0, j=0;
printf("Enter the size of the array: ");
scanf("%d", &n);
int *a = malloc(sizeof(int) * n);
for(j=0; j<n; j=j+1) {
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
return 0;
}
Use this one:
#include <stdio.h>
int position_smallest(int a[],int n)
{
int smallest = a[0];
int i,k;
for(i=0; i<=n-1; i=i+1)
{
if(a[i]<a[0])
{
smallest = a[i];
k = i;
}
}
printf("The smallest value is %d\n", smallest);
printf("It's position is %d\n", k);
return 0;
}
int main()
{
int n,j;
int a[100];
printf("Enter the size of the array: ");
scanf("%d", &n);
for(j=0; j<n; j=j+1)
{
printf("a[%d] = ", j);
scanf("%d", &a[j]);
}
position_smallest(a,n);
}
Specify the size of the array anything but run the loop according to user's input.
And there is some problems in your function position_smallest. So if you want correct it then take a look at #Gox's answer.

value of an integer changes out of nowhere

I am trying to run the code below whilst using the debugger. At the end of the following loop "for (i=0;i<n;i++) pin[i]=0;", n's value changes from the value I've given it and becomes 0. I can't understand why that happens, so your help as to why it happens would be greatly appreciated. Oh, and one other thing. If I ignore it and as soon as I've given n a value, I assign that value to another integer, in order to be able to use it when n becomes 0, my program crashes. It's a crash of the type you get when, for example, you're using a variable you've not assigned a value to.
main()
{
int i,j,k,n,pin[n];
printf("Give the size of the array:\n");
scanf("%d", &n);
do{
printf("Give the number of the iterations:\n");
scanf("%d", &k);
}while (k<1||k>n);
for (i=0;i<n;i++)
pin[i]=0;
for (j=0;j<k;j++){
for (i=0;i<n;i++){
if (i%j==0){
if (pin[i]==0)
pin[i]=1;
else
pin[i]=0;
}
}
}
for (i=0;i<n;i++)
printf("%d ", pin[i]);
}
You must not divide by 0 and define pin[n] where n is initialized.
#include <stdio.h>
int main() {
int i, j, k, n;
printf("Give the size of the array:\n");
scanf("%d", &n);
int pin[n];
do {
printf("Give the number of the iterations:\n");
scanf("%d", &k);
} while (k < 1 || k > n);
for (i = 0; i < n; i++)
pin[i] = 0;
for (j = 0; j < k; j++) {
for (i = 0; i < n; i++) {
if (j != 0 && i % j == 0) {
if (pin[i] == 0)
pin[i] = 1;
else
pin[i] = 0;
}
}
}
for (i = 0; i < n; i++)
printf("%d ", pin[i]);
}
Test
Give the size of the array:
3
Give the number of the iterations:
2
1 1 1
Test 2
Give the size of the array:
5
Give the number of the iterations:
4
1 1 0 0 0

C Program Help: Unexpected Output

School project for Computer Science. I need to make a program where the user declares a size for an array, then fills the array in numerical, nondecreasing order, then declares a value, x. X is then assigned to the appropriate spot so the entire array is in numerical, nondecreasing order. The array is then output.
The code builds properly with no errors, but the output is messed up.
#include <stdio.h>
int main (void) {
//Local Declarations
int size;
int ary[100];
int x;
int i;
int j;
//Statements
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("\nEnter digits to fill the array, in numerical order: ");
for (i = 0; i < size; i++) {
scanf("%d", &ary[i]);
}
size++;
printf("\nInput x, the value to add to the array: ");
scanf("%d", &x);
while(i=0 <= x && x > ary[i]){
i++;
j = size - 1;
while(j >= i) {
ary[j++] = ary[j];
j--;
}
}
for(i = 0; i < size; i++) {
printf("%d,", ary[i]);
}
return 0;
} //main
Example Output:
Enter the size of the array: 5
Enter digits to fill the array, in numerical order: 1
2
3
4
5
Input x, the value to add to the array: 6
1,2,3,4,5,1630076519,
Process returned 0 (0x0) execution time : 8.585 s
Press any key to continue.
It's always the last value that messes up to that huge number. I cannot for the life of me figure out why. The project is due by midnight EST.
For the while loop, can you try this instead,
i = 0;
while (i < x && x > ary[i]) {
i++;
j = size - 1;
while (j >= i) {
j++;
ary[j] = ary[j]; // Equivalent to ary[j++] = ary[j];, yet easier to read
j--;
}
}
Try this:
#include <stdio.h>
int main (void) {
//Local Declarations
int size;
int ary[100];
int x;
int i;
int j;
int temp1,temp2;
//Statements
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("\nEnter digits to fill the array, in numerical order: ");
for (i = 0; i < size; i++) {
scanf("%d", &ary[i]);
}
printf("\nInput x, the value to add to the array: ");
scanf("%d", &x);
for(i=0;i<size;i++)
{
if(ary[i]>x)
{
temp1 = ary[i];
ary[i] = x;
break;
}
}
if(i==size)
{
ary[i]= x;
}
else
{
for(j=i+1;j<size+1;j++)
{
if(j==size) //Last element of the new array
{
ary[j] = temp1;
break;
}
temp2 = ary[j];
ary[j] =temp1;
temp1 = temp2;
}
}
for(i = 0; i < size+1; i++) {
printf("%d,", ary[i]);
}
return 0;
} //main

Resources