I would like to write a program which finds the minimal number of 5 inputted numbers. I'm stuck at the point when I want to use function getMinNum, but there is an error saying: expected expression before ']' token
I understand it has a connection with pointers, however I would like to do it without them if it is possible of course.
#include <stdio.h>
#include <stdlib.h>
float getMinNum(float a[], int x);
int main()
{
int n = 5;
int i;
float z[n];
for(i=0; i<n; i++){
scanf("%f", &z[i]);
}
printf("%6.2f", getMinNum(z[], n));
return 0;
}
float getMinNum(float a[], int x)
{
int i, min = a[0];
for(i=0; i<x; i++){
if(min > a[i+1]){
min = a[i+1];
}
}
return min;
}
You shouldn't append '[]' to the variable name.
Instead of:
printf("%6.2f", getMinNum(z[], n));
do:
printf("%6.2f", getMinNum(z, n));
Your a[i+1] will be using values outside the array, so use a[i] instead.
So the code should look like
float getMinNum(float a[], int x){
int i;
float min = a[0]; // Min needs to be a float
for(i=1; i<x; i++){ // Do not need to check a[0]
if(min > a[i]){
min = a[i];
}
}
return min;
}
And call it as
printf("%6.2f", getMinNum(z, n));
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;
}
#include <stdio.h>
void avg_sum(double a[], int n, double *avg, double *sum)
{
int i;
sum = 0;
printf("%f", *sum);
for(i=0; i<n; i++)
*sum += a[i];
*avg = *sum/n;
}
int main()
{
double arr[2] = {0.0,1.0};
double *sum;
double *avg;
int n = 2;
avg_sum(arr, n, avg, sum);
printf("...Done...\n");
return 0;
}
Tried using both GCC(https://www.tutorialspoint.com/compile_c_online.php) and clang(from repl.it) online compilers
double *sum;
This creates a pointer to a double but it has an arbitrary value and therefore points at no dedicated memory.
In addition, in the called function, you set the sum pointer to zero (the null pointer) then try to use that pointer to dereference memory - that's a big non-no.
I'd also be wary of for(i=0; i<n-2; i++) for summing the values in the array. It's not going to include the final two which, since n is two, means it won't accumulate any of them.
The correct way to do this would be with:
void avg_sum(double a[], int n, double *avg, double *sum) {
int i;
*sum = 0; // set content, not pointer.
for(i=0; i<n; i++) // do all elements.
*sum += *(a+i);
*avg = *sum/n;
}
int main(void) {
double arr[2] = {0.0,1.0};
double sum; // ensure actual storage
double avg; // and here
int n = 2;
avg_sum(arr, n, &avg, &sum); // then pass pointers to actual storage
printf("Sum=%f, Avg=%f\n", sum, avg);
return 0;
}
This gives you, as expected:
Sum=1.000000, Avg=0.500000
Easy. In line 6 you assign 0 to sum but sum is not the actual sum but a pointer to it. When you try to print it you access invalid memory.
Edit:
BTW if you try compling with -fanalyzer you will get a warning and an explanation.
https://godbolt.org/z/W6ehh8
My issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped.
I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max.
It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.
Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3, ]"
#include <stdlib.h>
#include <stdio.h>
int getRandom(int min, int max);
void fillArray(int data[], int size, int min, int max);
void printArray(int data[], int size);
int main(int argc, char *argv[]) {
int a;
int b;
if (argc>=3){
a = atoi(argv[1]);
b = atoi(argv[2]);
int arr[10];
printf("\t An array with random values from 0 to 100 \n");
fillArray(arr,10 ,a, b);
printArray(arr, 10);
} else {
printf("Incorrect number of arguments - please call with assignment min max\n");
}
return 0;
}
int getRandom(int min, int max) {
int result = 0;
int low = 0;
int high = 0;
if (min<max) {
low = min;
high = max+1;
} else {
low = max + 1;
high = min;
}
result = (rand() % (high-low)) + low;
return result;
}
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){
data[i] = getRandom(min,max);
}
}
void printArray(int data[], int size){
int i;
printf("[");
for(i=0; i<size; i++){
printf("%d,", data[i]);
}
printf("]");
}
I agree with #Steve Friedl that the main problem with your program lies in the fillArray function. There i should run from 0 to size.
As for your second question, testing whether you're printing the last number helps to suppress the unwanted comma:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", data[i]);
if (i < size - 1)
printf(",");
}
printf("]");
}
If you prefer a more compact solution (although with an optimizing compiler there's not really a difference), you could write it as:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d%c", data[i], i < size-1 ? ',' : ']');
}
}
Also, in your main function, you should include a and b in your printing:
printf("\t An array with random values from %d to %d \n", a, b);
I believe this is blowing things up for you:
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){ // <-- HERE
data[i] = getRandom(min,max);
}
}
The calling function allocates 10 items in the arr array, and that's passed as the size parameter, but you're not using that parameter to limit filling up the array. If the max value is 100, then it's trying to fill one hundred slots instead of just ten.
for (i = 0; i < size; i++)
data[i] = getRandom(min,max);
should fix at least this issue.
EDIT: The comma thing, I prefer to add commas before the items unless this is the first. In this case it doesn't matter much, but it's more general, especially for variable-length lists where you don't know you're at the end until you get there. Augmenting the helpful response from #JohanC :
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
if (i > 0) printf(",");
printf("%d", data[i]);
}
printf("]");
}
I have written a program which generates a random array and sorts it by using both the insertion and quicksort algorithms. The program also measures the runtime of each function. The size of the array is defined in the preamble as a parameterised macro L. My question is:
How can I test both sorting algorithms with arrays of various sizes in a single execution?
I want my program to sort arrays of size L=10, 100, 1000, 5000 and 10000 in one execution. My program code is detailed below.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//Random Array Length
#define MAX 100
#define L 10
void naive_sort(int[]);
void smarter_sort(int[],int,int);
void swap(int[],int,int);
int choose_piv(int[],int,int);
int main(){
int i, a[L], b[L];
clock_t tic, toc;
//Generate an array of random numbers
for(i=0; i<L; i++)
a[i]= rand() % (MAX+1);
//Define b identical to a for fair comparison
for(i=0; i<L; i++)
b[i]=a[i];
//Unsorted Array
printf("\nUnsorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);
//Insertion Sort (1e)
tic = clock();
naive_sort(a);
printf("\nInsertion Sort: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);
toc = clock();
printf(" (Runtime: %f seconds)\n", (double)(toc-tic)/CLOCKS_PER_SEC);
//Quicksort (1f)
tic = clock();
smarter_sort(b,0,L-1);
printf("Quicksort: ");
for(i=0; i<L; i++)
printf("%d ", b[i]);
toc = clock();
printf(" (Runtime: %f seconds)\n", (double)(toc-tic)/CLOCKS_PER_SEC);
return 0;
}
void naive_sort(int a[]){
int i, j, t;
for(i=1; i < L; i++){
t=a[i];
j=i-1;
while((t < a[j]) && (j >= 0)){
a[j+1] = a[j];
j--;
}
a[j+1]=t;
}
}
void smarter_sort(int a[], int l, int r){
if(r > l){
int piv = choose_piv(a, l, r);
smarter_sort(a, l, piv-1);
smarter_sort(a, piv+1, r);
}
}
void swap(int a[], int i, int j){
int t=a[i];
a[i]=a[j];
a[j]=t;
}
int choose_piv(int a[], int l, int r){
int pL = l, pR = r;
int piv = l;
while (pL < pR){
while(a[pL] < a[piv])
pL++;
while(a[pR] > a[piv])
pR--;
if(pL < pR)
swap(a, pL, pR);
}
swap(a, piv, pR);
return pR;
}
I would appreciate any feedback.
EDIT: I modified the code as suggested, and it worked for the small values. But for the quicksort case L=100 and beyond it, I don't get any output:
and as you can see, the few outputs I get are zero. What's wrong with the code?
/*
* Task 1, question h
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//Random Array Length
#define MAX 100
void perf_routine(int);
void naive_sort(int[],int);
void smarter_sort(int[],int,int);
void swap(int[],int,int);
int choose_piv(int[],int,int);
int main(){
perf_routine(10);
perf_routine(100);
perf_routine(1000);
perf_routine(5000);
perf_routine(10000);
return 0;
}
void perf_routine(int L){
int i, a[L], b[L];
clock_t tic, toc;
printf("Arrays of Length %d:\n", L);
//Generate an array of random numbers
for(i=0; i<L; i++)
a[i]= rand() % (MAX+1);
//Define b identical to a for fair comparison
for(i=0; i<L; i++)
b[i]=a[i];
//Insertion Sort (1e)
tic = clock();
naive_sort(a, L);
toc = clock();
printf("Insertion Sort Runtime: %f seconds\n", (double)(toc-tic)/CLOCKS_PER_SEC);
//Quicksort (1f)
tic = clock();
smarter_sort(b,0,L-1);
toc = clock();
printf("Quicksort Runtime: %f seconds\n", (double)(toc-tic)/CLOCKS_PER_SEC);
}
void naive_sort(int a[], int L){
int i, j, t;
for(i=1; i < L; i++){
t=a[i];
j=i-1;
while((t < a[j]) && (j >= 0)){
a[j+1] = a[j];
j--;
}
a[j+1]=t;
}
}
void smarter_sort(int a[], int l, int r){
if(r > l){
int piv = choose_piv(a, l, r);
smarter_sort(a, l, piv-1);
smarter_sort(a, piv+1, r);
}
}
void swap(int a[], int i, int j){
int t=a[i];
a[i]=a[j];
a[j]=t;
}
int choose_piv(int a[], int l, int r){
int pL = l, pR = r;
int piv = l;
while (pL < pR){
while(a[pL] < a[piv])
pL++;
while(a[pR] > a[piv])
pR--;
if(pL < pR)
swap(a, pL, pR);
}
swap(a, piv, pR);
return pR;
}
I would, in each function gives the length of the array in parameters and make sure you don't try to reach element outside of array, for example swap would become:
int swap(int *a, int length, int i, int j)
{
if(i>=length || j>=length)
return -1;
int t=a[i];
a[i]=a[j];
a[j]=t;
return 0;
}
Also note the return -1 or 0 to indicates a failure. Apply that to the rest of the code and you'll have something that can be applied to any array.
When arrays are passed to functions, they are passed as (or "decay into") pointer to their first element. There is no way to know about the size of the array.
It is therefore very common to pass the actual length as additional parameter to the function. An example of your naive sort with three arrays of different size if below.
Of course, one must take care to keep the array and length in sync. Passing a length that is too big may result in undefined behaviour. For example, calling fill(tiny, LARGE) in the example below may result in disaster.
(Aside: An array may have a maximum length or capacity and an actual length. For example if you want to read up to ten numbers from a file, you must pass an array of length 10, but if there are only four numbers read, you are dealing with two additional parameters here: the possible array length, 10, and the actual length, 4. That's not the case here, though.)
Well, here goes. All three array functions have the same signature: They take an array and its length.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void sort(int a[], size_t len)
{
size_t i, j;
for (i = 1; i < len; i++) {
int t = a[i];
j = i - 1;
while (j >= 0 && t < a[j]) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = t;
}
}
void fill(int a[], size_t len)
{
size_t i;
for (i = 0; i < len; i++) {
a[i] = rand() / (1.0 + RAND_MAX) * 100;
}
}
void print(int a[], size_t len)
{
size_t i;
for (i = 0; i < len; i++) {
if (i) printf(", ");
printf("%d", a[i]);
}
puts("");
}
#define TINY 3
#define MEDIUM 10
#define LARGE 15
int main(void)
{
int tiny[TINY];
int medium[MEDIUM];
int large[LARGE];
srand(time(NULL));
fill(tiny, TINY);
fill(medium, MEDIUM);
fill(large, LARGE);
print(tiny, TINY);
print(medium, MEDIUM);
print(large, LARGE);
sort(tiny, TINY);
sort(medium, MEDIUM);
sort(large, LARGE);
print(tiny, TINY);
print(medium, MEDIUM);
print(large, LARGE);
return 0;
}
as you can tell by the title I need to write a function that returns a pointer to the largest number in an array, the functions gets a pointer to a double array and it's size. In addition I need to write a main function that will use this function.
Here is the code that I wrote:
#include <stdio.h>
#include <stdlib.h>
void BigEl(double* arr, double arrSize);
void BigEl(double* arr, double arrSize)
{
int i;
double maximum, *x;
maximum = arr[0];
for (i = 1; i < arrSize; i++)
{
if (arr[i]>maximum)
{
maximum = arr[i];
}
}
*x = maximum;
}
void main()
{
double myarr[10];
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%d", &myarr[i]);
}
BigEl(myarr, 10);
}
I get this error:
Error 1 error C4700: uninitialized local variable 'x' used
I don't understand what I did wrong because I did initialized x.
Any kind of help is appreciated, in addition, tell me if the idea of my code was right because Im not sure if I understood the question correctly.
You did not initialize the variable x. You merely wrote to the the location pointed to by x, here:
*x = maximum;
when x was uninitialized, which is what the compiler is complaining about.
You want something like:
double *
BigEl(double* arr, size_t arrSize)
{
size_t i;
double *max = arr;
for (i = 1; i < arrSize; i++)
if (arr[i] > *max)
max = &arr[i];
return max;
}
Things I've changed:
Use size_t for the array size and the counter, not a double and an int.
Retain a pointer to the maximum element, not the maximum element's value.
Return the pointer to the maximum element.
Remove superflous braces.
You're not returning anything. Also, it might be good to take into consideration the case when the array size is 0. Moreover, the size should be passed as a constant. No other answer has mentioned this.
double* BigEl(double* arr, const size_t iSize)
{
if(iSize == 0)
return 0;
double max = arr[0], *x = &arr[0];
for(unsigned int i=1;i<iSize;++i){
if(arr[i] > max){
max = arr[i];
x = &arr[i];
}
}
return x;
}
Your assignment to *x is incorrect - you are saying "assign to the location pointed to by x, without first saying where that is. Aside from that, there are a couple of other issues:
#include <stdio.h>
#include <stdlib.h>
// return pointer to location from function
double * BigEl(double* arr, double arrSize)
{
int i;
// initialise both variables
double maximum = arr[0], *max_pos = arr;
for (i = 1; i < arrSize; i++)
{
if (arr[i]>maximum)
{
maximum = arr[i];
// assign address here
max_pos = &arr[i];
}
}
// return address
return max_pos;
}
int main()
{
double myarr[10];
double * max_pos;
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%lf", &myarr[i]);
}
// use return value here
max_pos = BigEl(myarr, 10);
return 0;
}
//function that returns a pointer to the largest number
double *BigEl(double* arr, int arrSize)
{
int i;
double *maximum;
maximum = &arr[0];
for (i = 1; i < arrSize; i++)
{
if (arr[i] > *maximum)
{
maximum = &arr[i];
}
}
return maximum;
}
int main(void)
{
double myarr[10];
int i;
printf("Please insert 10 numbers to the array\n");
for (i = 0; i < 10; i++)
{
scanf("%lf", &myarr[i]);
}
printf("%f\n", *BigEl(myarr, 10));
return 0;
}
I need to write a function that returns a pointer to the largest
number in an array
I think you need the follwoing
#include <stdio.h>
double * largest_element( const double *a, int n )
{
const double *largest = a;
int i;
for ( i = 1; i < n; i++ )
{
if ( *largest < a[i] ) largest = a + i;
}
return ( double *)largest;
}
#define N 10
int main(void)
{
double a[N];
int i;
printf("Please insert %d numbers to the array: ", N );
for ( i = 0; i < N; i++ )
{
scanf( "%lf", &a[i] );
}
printf( "\nThe largest element of the array is %lf\n", *largest_element( a, N ) );
return 0;
}
If to enter for example
2.2 1.5 5.2 1.8 3.9 5.9 7.7 6.8 2.9 0.8
then the program output will be
The largest element of the array is 7.700000