I am trying to write a C program that calculates the min and max value from entered numbers. I managed find the min and max value, but for some reason i cannot print out the values outside the function. This is my code:
#include <stdio.h>
#include <stdlib.h>
void find_largest_smallest(int a[], int n, int *largest, int *smallest)
{
largest=smallest=a[0];
int i;
for(i=0; i<n; i++)
{
if (largest<a[i])
largest=a[i];
}
for(i=0; i<n; i++)
{
//printf("%d\n", a[i]);
if (smallest>a[i])
smallest=a[i];
}
printf("Largest is %d\n", largest);
printf("smallest is %d\n", smallest);
}
int main()
{
int elem;
int i;
int *x;
int *y;
printf("How many elements you want to store ?:");
scanf("%d", &elem);
int store[elem];
for(i=0; i<elem; i++)
{
printf("Enter a value to be stored:");
scanf("%d", &store[i]);
}
find_largest_smallest(store, elem, &x, &y);
printf("Largest value stored is %d and the smallest is %d.", *x, y);
return 0;
}
This:
largest=smallest=a[0];
Is wrong. You are assigning an integer to a pointer. What you should do is instead:
*largest = a[0];
*smallest = a[0];
Same goes for other assignments and reads:
if (*largest < a[i])
*largest = a[i];
/* ... */
if (*smallest > a[i])
*smallest = a[i];
/* ... */
printf("Largest is %d\n", *largest);
printf("smallest is %d\n", *smallest);
The declaration of x and y in main should just be int (not int *):
int x, y;
The call to printf in main is also wrong:
printf("Largest value stored is %d and the smallest is %d.", x, y);
// no asterisk needed here ----------^
The parameters largest and smallest have pointer types
void find_largest_smallest(int a[], int n, int *largest, int *smallest)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
So within the function you have to dereference the pointers to access pointed objects.
For example
void find_largest_smallest(int a[], int n, int *largest, int *smallest)
{
*largest = *smallest = a[0];
int i;
for ( i = 1; i<n; i++ )
{
if ( *largest<a[i] )
*largest=a[i];
}
for ( i = 1; i<n; i++ )
{
//printf("%d\n", a[i]);
if ( *smallest>a[i] )
*smallest=a[i];
}
printf("Largest is %d\n", *largest);
printf("smallest is %d\n", *smallest);
}
Pay attention to that you could find the largest and the smallest elements using only one loop. Apart this the function should calculates pointers to the largest and smallest elements instead of their values because in general the user can pass the size of the array equal to 0. In this case the function will have undefined behavior.
Also within main the variables x and y should have the type int. That is
int x;
int y;
//...
printf("Largest value stored is %d and the smallest is %d.", x, y );
Related
Problem: Write a program in C to get the largest element, smallest element, sum of all elements and multiplication of all elements of an array using the functions. (Make four different functions for four calculations and call them for one array given by user).
I think I'm getting error because of i and n.
I'm a beginner and I can't explain every thing line by line. Code:
#include <stdio.h>
// defined Max function int Max(int arr[], int);
// defined Min function int Min(int arr[], int);
// defined Sum function int Sum(int arr[], int);
// defined Mul function int Mul(int arr[], int);
int main() {
int i, n, arr[100];
printf("Input the number of elements to be stored in the array : ");
scanf("%d",&n);
printf("Input %d elements in the array: \n",n);
for (i=0; i<n; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}
n = Max( arr, n);
printf("The largest element in the array is : %d", n);
n = Min( arr, n);
printf("\nThe smallest element in the array is : %d", n);
n = Sum( arr, n);
printf("\nThe sum of all the elements in the array is : %d", n);
n = Mul( arr, n);
printf("\nThe multiplication of all the elements in the array is : %d", n);
return 0;
}
int Max(int arr[], int n)
{
int max = arr[0];
for (int i=0; i<n; i++)
{
if (max<arr[i])
max=arr[i];
}
return max;
}
int Min(int arr[], int n)
{
int min = arr[0];
for (int i=0; i<n; i++)
{
if (min>arr[i])
min=arr[i];
}
return min;
}
int Sum(int arr[], int n)
{
int sum = arr[0];
for (int i=0; i<n; i++)
{
sum += arr[i];
}
return sum;
}
int Mul(int arr[], int n)
{
int mul = arr[0];
for (int i=0; i<n; i++)
{
mul *= arr[i];
}
return mul;
}
As suggested in one comment, your for should start from 1, otherwise you use the element 0 twice, and thus producing always a wrong result. Here is how the for related to Mul function should appear, just apply the same for other ones:
int mul = arr[0];
for(int i=1; i<n; i++)
{
mul *= arr[i];
}
return mul;
In addition to the above, there is another bug in your code, which is the way you use the variable n.
As far as I see, that variable stores the number of elements of the array. It is a valid input for all the sub-routines, but you cannot re-assign it with the result of each of them. In this way, it's like you are invoking the sub-routines always with a different array size, and of course you get unexpected results.
So, one possible solution would be to define and use another local variable which holds the results from each sub-routines.
To help you with your issue, I fixed your code, it works fine now. There you go:
#include <stdio.h>
// defined Max function int Max(int arr[], int);
// defined Min function int Min(int arr[], int);
// defined Sum function int Sum(int arr[], int);
// defined Mul function int Mul(int arr[], int);
int main() {
int i, n, op_res, arr[100];
printf("Input the number of elements to be stored in the array : ");
scanf("%d",&n);
printf("Input %d elements in the array: \n",n);
for (i=0; i<n; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}
op_res = Max( arr, n);
printf("The largest element in the array is : %d", op_res);
op_res = Min( arr, n);
printf("\nThe smallest element in the array is : %d", op_res);
op_res = Sum( arr, n);
printf("\nThe sum of all the elements in the array is : %d", op_res);
op_res = Mul( arr, n);
printf("\nThe multiplication of all the elements in the array is : %d", op_res);
return 0;
}
int Max(int arr[], int n)
{
int max = arr[0];
for (int i=0; i<n; i++)
{
if (max<arr[i])
max=arr[i];
}
return max;
}
int Min(int arr[], int n)
{
int min = arr[0];
for (int i=0; i<n; i++)
{
if (min>arr[i])
min=arr[i];
}
return min;
}
int Sum(int arr[], int n)
{
int sum = arr[0];
for (int i=1; i<n; i++)
{
sum += arr[i];
}
return sum;
}
int Mul(int arr[], int n)
{
int mul = arr[0];
for (int i=1; i<n; i++)
{
mul *= arr[i];
}
return mul;
}
Hi, how can I find the closest number of average in this array?
Idk how to do this.
#include<stdio.h>
#include<stdlib.h>
int arraysum();
int main()
{
int n, A[100], i, b, sum;
float average;
printf("Enter number of elements in array: ");
scanf("%d", &n);
printf("\nEnter %d numbers: ", n);
for(i=0; i<n; i++)
scanf("%d", &A[i]);
printf("Numbers of this array: ");
for(i=0; i<n; i++)
printf("%d ", A[i]);
average=arraysum(A, sum, i, n)/n;
printf("\nAverage is: %.2f", average);
}
int arraysum(int A[], int sum, int i, int n)
{
sum=0;
for(i=0; i<n; i++)
sum+=A[i];
return sum;
}
Thanks in advance, guys!
:D
After finding the average, iterate looking for closest.
// Pseudo code
average=arraysum(A, sum, i, n)/n;
best = element 0
for (each element in the array [1...n-1])
if (|A[i] - average| < |A[best] - average|)
best = i
To cope with an average than is not exactly an integer and not use unnecessary floating point math ...
long long scaled_average = arraysum(A, sum, i, n);
best = element 0
for (each element in the array [1...n-1])
if (|n*A[i] - scaled_average| < |n*A[best] - scaled_average|)
best = i
Consider using long long for sum to avoid overflow.
Code simplification: no need to pass in sum.
long long arraysum(int A[], int i, int n) {
long long sum = 0;
for(i=0; i<n; i++)
sum+=A[i];
return sum;
}
First suggestion is to move the declaration of A[100]; from here
int n, A[100], i, b, sum;
To just after the scanf() statement, to create a VLA:
int n, i, b, sum;
...
printf("Enter number of elements in array: ");
scanf("%d", &n);
int A[n];
for(i=0; i<n; i++)
scanf("%d", &A[i]);
...creating an array just the right size for the need.
Once the array is populated, loop through it and use comparison operators to find the closest to the difference of array values and average. (pseudo code: fabs(a[i]-ave) < fabs(a[i+1]-ave)) tracking the array index of the array values closest.
Example:
average = arraysum(A, sum, i, n)/(n*(1.0));//divide by floating point
int closestIndex;
findClosest(int A, 100, average, &closestIndex);
printf("Index of value closest to %f is %d\nClosest value is: %d\n",
average, closestIndex, A[closestIndex]);
Where findClosest() is defined:
void findClosest(int A[], size_t size, double ave int *index)
{
int smallestIndex;
for(int i=0;i<size-1;i++)
{
smallestIndex = fabs((double)A[i]-ave) < fabs((double)A[i+1]-ave) ? i : i + 1;
}
*index = smallestIndex
}
I was given an assignment to write a code which takes in numbers as input from the user and provides the sum of it, specifically by the use of pointer arithmetic i.e. no array subscripting a[i] is allowed.
Below is the code that I wrote, which got compiled and even ran. But almost always it gives the sum of the input numbers as 0. I tried to fix it, but to no avail. Thus, I am asking for help, any help is greatly appreciated.
#include<stdio.h>
#define N 5
int sum_array( const int *p, int n)
{
int sum, a[N];
sum = 0;
for(p=&a[0]; p<&a[N]; p++)
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(i,N);
printf("the sum is %d\n", x);
return 0;
}
Beware, you are declaring array int a[N] in both main and sum_array. They are in different scopes, so they are different arrays (and the one from sum_array is never initialized so reading it invokes Undefined Behaviour).
The correct way is to pass the array along with its used length:
Here is a fixed version:
#include<stdio.h>
#define N 5
int sum_array( const int *a, int n) // a points to a array of at least n elements
{
int sum = 0; // initialize at definition time
for(const int *p=a; p<&a[n]; p++) // have the pointer p take all values from a
sum += *p;
return sum;
}
int main()
{
int a[N], *i,x;
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
scanf("%d", i);
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
Finally it is mainly a matter of taste, but I was too often burnt for trying to add an instruction in a for loop without braces, so I strongly recommend using always braces for loops:
for(i=a; i<a+N; i++) {
scanf("%d", i);
}
int sum_array( const int *p, int n)
{
int sum = 0, i = 0;
for(i = 0; i < n ; i++)
sum += *(p+i);
return sum;
}
int main(void)
{
int a[N], i = 0, x = 0;
printf("Enter %d Numbers: ", N);
for(i=0; i<N; i++)
scanf("%d", a+i);
// all the input values get scanned as i or the array a
x= sum_array(a,N);
printf("the sum is %d\n", x);
return 0;
}
In x= sum_array(i,N); i is the iterator of your loop so after the loop has finished it points to the first position after the array.
You should pass the original array instead x= sum_array(a,N);
In the sum function you just throw away the passed pointer and replace it with your local a[].
int sum_array( const int *p, int n)
{
int sum = 0;
int *end = &p[n]; // first element after the array.
for(; p<end; p++) // just use p because you don't need the reference to the start of the array
{
sum += *p;
}
return sum;
}
but as you said that array notation is not allowed you can change it as follows
#include "stdio.h"
#define N 5
int sum_array( const int *p, int n)
{
int sum = 0;
const int *end = p+n; // first element after the array.
for(; p<end; p++)
{
sum += *p;
}
return sum;
}
int main()
{
int *a, *i, x;
a = malloc(N * sizeof(*a));
if (a == NULL)
exit(-1);
printf("Enter %d Numbers: ", N);
for(i=a; i<a+N; i++)
{
scanf("%d", i);
}
// all the input values get scanned as i or the array a
x= sum_array(a,N); // pass the array address, not a pointer past last element
printf("the sum is %d\n", x);
return 0;
}
in general, when programming, the code should be kept as simple as possible while still being complete.
The program criteria shows no need to keep a number after it is applied to the sum of the numbers, So in the proposed code, the input number is only kept long enough to be applied to the sum, then it is discarded.
The following proposed code:
cleanly compiles
performs the desired functionality
is kept very simple
properly checks for; and handles any errors
And now the proposed code:
#include <stdio.h> // scanf(), printf(), fprintf(), stderr
#include <stdlib.h> // exit(), EXIT_FAILURE
#define N 5
int main( void )
{
int num = 0;
int sum = 0;
printf("Enter %d Numbers: ", N);
for(size_t i=0; i<N; i++)
{
if( scanf("%d", &num) != 1 )
{
fprintf( stderr, "failed to read number\n" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
sum += num;
}
printf( "the sum is %d\n", sum );
return 0;
}
I am writing a program that creates an array of ten integers. I have to define max 10 constant and use functions.getdata(ask user for numbers),displaydata(display)
displaylargest,smallest,average,range,and median.
I am stuck on average because soon as I added that function my largest displays a weird number but if I comment out the average function my largest displays correct answer. Can someone tell me where I went wrong?
#include <stdio.h>
#define MAX 10
int getdata(int array[]);
int displaylargest(int array[]);
int displaysmallest(int array[]);
int displayaverage(int array[]);
void displaydata(int array[]);
int main () {
int array[MAX];
int largest;
int smallest;
int average;
printf("\nEnter ten numbers \n\n");
getdata(array);
displaydata(array );
largest=displaylargest( array);
printf("\nThe largest %d\n", largest);
smallest=displaysmallest( array);
printf("\nThe smallest is %d\n", smallest);
average=displayaverage(array);
printf("\nThe average is %d\n", average);
return 0;
}
int getdata(int array[]) {
int x;
printf ("Enter a number\n ",x+1);
for(x=0;x<MAX;x++)
scanf ("%d",&array[x]);
}
int displaylargest(int array[]) {
int x, largest=array[x];
for (x=0; x<MAX; x++) {
if (array[x]>largest)
largest=array[x];
}
return(largest);
}
int displaysmallest(int array[]) {
int x, smallest=array[x];
for (x=0; x<MAX; x++) {
if (array[x]<smallest)
smallest=array[x];
}
return(smallest);
}
int displayaverage(int array[]) {
int x;
int sum=0;
int average;
for (x=0; x<MAX; x++) {
sum+=array[x];
}
{
average=sum/MAX;
}
return(average);
}
void displaydata(int array[]) {
int x;
for(x=0; x<MAX; x++) {
printf("%d, ",array[x]);
}
}
You need to initialize local variables in your functions especially when you are using that to access your array. Without that local variable can contain any value ,if you use that as index to your array, you might be accessing valid memory.
#include <stdio.h>
#define MAX 10
void getdata(int array[]);
int displaylargest(int array[]);
int displaysmallest(int array[]);
int displayaverage(int array[]);
void displaydata(int array[]);
int main() {
int array[MAX];
int largest;
int smallest;
int average;
printf("\nEnter ten numbers \n\n");
getdata(array);
displaydata(array);
largest = displaylargest(array);
printf("\nThe largest %d\n", largest);
smallest = displaysmallest(array);
printf("\nThe smallest is %d\n", smallest);
average = displayaverage(array);
printf("\nThe average is %d\n", average);
return 0;
}
void getdata(int array[]) {
int x;
printf("Enter a number\n " );
for (x = 0; x<MAX; x++) {
scanf("%d", &array[x]);
}
}
int displaylargest(int array[]) {
int x, largest = array[0];
for (x = 0; x<MAX; x++) {
if (array[x]>largest)
largest = array[x];
}
return(largest);
}
int displaysmallest(int array[]) {
int x, smallest = array[0];
for (x = 0; x<MAX; x++) {
if (array[x]<smallest)
smallest = array[x];
}
return(smallest);
}
int displayaverage(int array[]) {
int x;
int sum = 0;
int average;
for (x = 0; x<MAX; x++) {
sum += array[x];
}
{
average = sum / MAX;
}
return(average);
}
void displaydata(int array[]) {
int x;
for (x = 0; x<MAX; x++) {
printf("%d, ", array[x]);
}
}
In c if we have local variable without initialization ,then it will have some garbage value. And in many of the functions u are intializing somevalue = array(x) it is not correct. The location you are accessing on the array is not valid.Make those chages it will work correctlu
Local variables need to be used here. While defining
largest=array[x];
make sure that x=0, else x may contain garbage value and the array may try to access invalid memory locations, leading to either the conditions known as underflow or overflow.
Also, I see that you've declared getdata() of type int, though it is not returning any value. Please make it of type void, as is just used to insert the asked values into the array. Hope this helps!
So, my task is to let user fill one dimensional array A. This array has M number of groups and P members in each group. I need to fill array B with maximum values of each group in A array and display results of maximum values in each group after. I couldn't figure out any way to do it. I would really appreciate your help since I am a beginner programmer and doing my best to study. So my main problem in code is fillBArray function.
#include <stdio.h>
#include <stdlib.h>
int checkingvariable(int k, int a, int b);
void fillArray(int M, int P,int A[]);
void printArray(int M, int P,int A[]);
void fillBArray(int M, int P,int A[]);
int main()
{
int M, P;
printf("Enter M (the number of groups): ");
scanf("%d", &M);
M=checkingvariable(M, 1, 10);
printf("Enter P (the number of cars in one group): ");
scanf("%d", &P);
P=checkingvariable(P, 1, 10);
int i = P*M;
int A[i];
fillArray(M, P, A);
printArray(M, P, A);
fillBArray(M, P, A);
return 0;
}
void printArray(int M, int P,int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("%d ", A[i]);
printf("\n");
}
}
void fillArray(int M, int P, int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("Enter speed of car %d: ", i+1);
scanf("%d", &A[i]);
}
}
void fillBArray(int M, int P, int A[])
{
int c, k=0;
int maximum = A[0];
int B[M], group;
for (c = 0; c < P*M; c++)
{
if (A[c] > maximum)
{
maximum = A[c];
}
maximum = B[k];
printf("Maximum value for %d group is: %d", group, maximum);
}
}
int checkingvariable(int k, int a, int b)
{
if (k<a || k>b)
{
while(k<a || k>b)
{
printf("Enter correct value between %d and %d: ", a, b);
scanf("%d", &k);
}
}
return k;
}
One way is to replace one loop with two nested loops. The outer loop would iterate groups, while the nested loop would iterate members in each group.
One observation before you begin: members of a group g in the array A are located between indexes g*P, inclusive, and (g+1)*P, exclusive. Member m of a group is located at the index A[g*P + m].
Now it should be clear how to make your loops:
for (int g = 0 ; g != M ; g++) { // Groups
int max = A[g*P];
for (int m = 1 ; m != P ; m++) { // Members
... // Compute max
}
// Store max for group g in B[]
}
#include <stdio.h>
#include <stdlib.h>
int checkingvariable(int k, int a, int b);
void fillArray(int M, int P,int A[]);
void printArray(int M, int P,int A[]);
void fillBArray(int M, int P,int A[]);
int main()
{
int M, P;
printf("Enter M (the number of groups): ");
scanf("%d", &M);
M=checkingvariable(M, 1, 10);
printf("Enter P (the number of cars in one group): ");
scanf("%d", &P);
P=checkingvariable(P, 1, 10);
int i = P*M;
int A[i];
fillArray(M, P, A);
printArray(M, P, A);
fillBArray(M, P, A);
return 0;
}
void printArray(int M, int P,int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("%d ", A[i]);
printf("\n");
}
}
void fillArray(int M, int P, int A[])
{
int i;
for (i=0 ; i< M*P ; i++)
{
printf("Enter speed of car %d: ", i+1);
scanf("%d", &A[i]);
}
}
/*void fillBArray(int M, int P, int A[])
{
int c, k=0;
int maximum = A[0];
int B[M], group;
for (c = 0; c < P; c++)
{
if (A[c] > maximum)
{
maximum = A[c];
}
if (c < P)
{
group = 1;
maximum = A[c];
printf("Maximum value for %d group is: %d", group, maximum);
}
if (c < P*2)
{
group = 2;
k=1;
maximum = A[c];
printf("Maximum value for %d group is: %d", group, maximum);
}
}
}*/
void fillBArray(int M, int P, int A[])
{
int B[M], maximum = 0, m;
for (int g = 0 ; g != M ; g++)// Groups
{
int max = A[g*P];
for (m = 0 ; m != P ; m++) // Members
{
if (A[g*P + m] > maximum)
{
maximum = A[g*P + m];
}
}
B[g] = maximum;
printf("Maximum value for %d group is: %d", g+1, maximum);
printf("\n");
maximum = 0;
}
}
int checkingvariable(int k, int a, int b)
{
if (k<a || k>b)
{
while(k<a || k>b)
{
printf("Enter correct value between %d and %d: ", a, b);
scanf("%d", &k);
}
}
return k;
}
This is answer to my problem, check fillBArray.