Printing values of an array using a function in C language - arrays

I am pretty new to programming and I was working on printing arrays using functions and I ran to the following error.
Test.c: In function ‘main’:
Test.c:21:54: error: incompatible type for argument 1 of ‘theta’
21 | printf("The theta values are = %lf\n", x[i], theta(x[i]));
| ~^~~
| |
| double
Test.c:5:21: note: expected ‘double *’ but argument is of type ‘double’
5 | double theta(double x[N])
| ~~~~~~~^~~~
And here is the code.
#include <stdio.h>
#include <stdlib.h>
#define N 50
double theta(double x[N]);
int main(){
int i;
double x[i];
printf("The theta values are = %lf\n", x[i], theta(x[i]));
return 0;
}
double theta(double x[N]){
int i;
for(i = 0; i < 50; i++){
x[i] = (double)(i)/ ((double)(N) - 1.0);
}
return x[i];
}
I just want to print 50 values between 0 and 1. Just like linspace(0:1:50) in MATLAB.
Thanks for the help.

First, in declare function, you cannot set size of array.
change to
double theta(double* X)
Second, do double theta(double x[N]); in main function.
and this is compiler didn`t advise you but I found bug in your code.
First, i in theta is different with i in main
Second, use for to print
I think you want this code
#include<stdio.h>
#include<stdlib.h>
#define N 50
double* theta()
{
int i;
double x[N];
for(i = 0; i < N; i++){
x[i] = (double)(i)/ ((double)(N) - 1.0);
}
return x;
}
int main(){
int i;
double* x=theta();
for(i=0;i<N;i++){
printf("The theta values are = %lf\n", x[i]);
}
return 0;
}
And I like this code more
#include<stdio.h>
#include<stdlib.h>
#define N 50
int main(){
int i;
for(i=0;i<N;i++){
printf("%lf\n",i/(N-1.0));
}
return 0;
}

I found the solution. Here it is.
#include <stdio.h>
#include <stdlib.h>
#define N 50
double* theta(double x[], int nb_elements){
int i;
for(i = 0; i < nb_elements; i++){
x[i] = (double)(i)/ ((double)(nb_elements) - 1.0);
}
return &x[0];
}
int main(){
int i;
double x[N];
theta(x, N);
for(i = 0; i < N; i++){
printf("%lf\n", x[i]);
}
return 0;
}

Related

C: give 2D array to function but the identifier "a" is not defined

I want to create 2 matrices and fill them with reandom numbers 0-9.
I just don't understand why my function doesn`t work like this.
If I define a and b with e.g. #define a = 3 it works.
So the problem occurs at:
void fillM(int array[a][b])
and
void printM(int array[a][b])
Original code
#include <stdio.h>
#include <float.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
//fill random
void fillM(int array[a][b]) {
for (int x=0; x < a; x++) {
for (int y=0; y < b; y++) {
array[x][y] = rand()%10;
}
}
}
//print
void printM(int array[a][b]){
for (int x=0; x < a; x++){
for (int y=0; y < b; y++) {
printf("%d ", array[a][b]);
}
printf("\n");
}
}
int Main(){
//do I really need this?
srand (time(NULL));
//set size
int n;
printf("please set size of n x n Matrix: \n");
scanf("%d", &n);
int m = n;
//initialise
int m1[n][m];
int m2[n][m];
fillM (m1);
fillM (m2);
return 0;
}
Revised code
#include <float.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
//fill random
void fillM(size_t a, size_t b, int array[a][b]) {
for (int x=0; x < a; x++) {
for (int y=0; y < b; y++) {
array[x][y] = rand()%10;
}
}
}
//print
void printM(size_t a, size_t b, int array[a][b]){
for (int x=0; x < a; x++){
for (int y=0; y < b; y++) {
printf("%d ", array[a][b]);
}
printf("\n");
}
printf("\n");
}
int main(){
srand (time(NULL));
//set size
int n;
printf("please set size of n x n Matrix: \n");
scanf("%d", &n);
printf("\n");
int m = n;
//initialise
int m1[n][m];
int m2[n][m];
fillM (n, m, m1);
fillM (n, m, m2);
printM (n, m, m1);
printM (n, m, m2);
return 0;
}
But one more question. If I run the program now, it doesn´t fill the matrix with random numbers everywhere. It puts the same random number in every place. Do you know how to fix this?
At the point where you use a and b, they are not defined. You need something more like:
void fill(size_t a, size_t b, int array[a][b]
Your calls will pass the array size as well.
In your revised code, you get the same answer for every printed value because you attempt to print the same element of the array, array[a][b] — except that it isn't an element of the array but is a long way out of bounds because the array indexes run from 0..a-1 and 0..b-1. Use array[x][y] instead.

Wrong result after a division

In an exercice I have to give to a function an array and his size to get the average of his value.
So I've tried this :
#include <stdio.h>
#include <stdlib.h>
double average(double array[], double array_size);
int main()
{
double array[4] = {12.0, 20.0, 8.9, 14.7};
printf("The average of the array is : %lf\n", average(array, 4.0));
return 0;
}
double average(double array[], double array_size)
{
int array_average = 0, i = 0;
while(i < array_size)
{
array_average += array[i];
i++;
}
return array_average / array_size;
}
I clang the file and run the ./a.out and that return me 13.500000 instead of 13.9 when I do the average with the calculator.
I don't see where is the errors, thanks for your help !
If that can help someone later I post my final code
#include <stdio.h>
#include <stdlib.h>
double average(double array[], double array_size);
int main()
{
double array[4] = {12.0, 20.0, 8.9, 14.7};
printf("The average of the array is : %lf\n", average(array, 4.0));
return 0;
}
double average(double array[], double array_size)
{
double array_average = 0.0;
int i = 0;
while(i < array_size)
{
array_average += array[i];
i++;
}
return array_average / array_size;
}

Error when comparing float and element array of float

So I have a to create a program that creates an array and adds 6 grades to it, then it has to calculate the average in a different function, and then check what grades are above the average.
It all worked until this little operation started to throw an error like such:
main.c:29:18: error: invalid operands to binary < (have 'float (*)(float *)' and 'float')
#include <stdio.h>
#include <stdlib.h>
float media(float grades[]){
int sum = 0;
for(int i = 0; i < 5; i++){
sum += grades[i];
}
float media = sum/6;
printf("A media é %f", media);
return media;
}
int acimamedia(float media(float grades[]), float vetor[], int x){
for(int i = 0; i < 6;i++){
float z = vetor[i];
if(media < z){ // <<<<<<<<<<<<< [Error here]
x += 1;
}
}
return x;
}
int main(int argc, char** argv) {
float grades[6];
int acimadamedia;
printf("As notas sao: \n");
for(int i = 0; i < 6; i++){
grades[i] = rand()%100;
printf("Nota [%d] -- %f",i , grades[i]);
}
printf("Existem %d notas acima da media.", acimadamedia());
media is a function declaration:
float media(float grades[])
and z is a single float value
so you are trying to compare a function pointer to a float hence the error is exactly as what it says:
error: invalid operands to binary < (have 'float (*)(float *)' and 'float')
In addition your call of acimadamedia() is trying to treat an integer as a function.
If I kind of understand what you are trying to do and do the minimum of changes to your code:
#include <stdio.h>
#include <stdlib.h>
float media(float grades[]){
int sum = 0;
for(int i = 0; i < 5; i++){
sum += grades[i];
}
float media = sum/6;
printf("A media é %f\n", media);
return media;
}
int acimamedia(float media(float grades[]), float vetor[]){
int x = 0;
float avg = media(vetor);
for(int i = 0; i < 6;i++){
float z = vetor[i];
if(avg < z){
x += 1;
}
}
return x;
}
int main(int argc, char** argv) {
float grades[6];
int acimadamedia;
printf("As notas sao: \n");
for(int i = 0; i < 6; i++){
grades[i] = rand()%100;
printf("Nota [%d] -- %f\n",i , grades[i]);
}
acimadamedia = acimamedia(&media, grades);
printf("Existem %d notas acima da media.\n", acimadamedia);
return 0;
}
Will show the grades, the avg grade and the number of grades above the average
the acimamedia function for passing a function usally is specified as:
int acimamedia(float (*media)(float grades[]), float vetor[])

Finding minimal number in array

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));

Sum of array in C

I'm working on a small program for school and can't get my array of doubles to sum properly. The specific error I'm getting is
warning C4244: 'return': conversion from 'double' to 'int', possible loss of data
on the line where sum is returned. And the sum displayed is gibberish.
The code is intended to:
fill an array of doubles with user input,
print the doubles on the screen in a column,
add up all the doubles in the array, and
print the sum onto the screen.
Code
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAX_SIZE 15
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
SumArray(double a[], int *i);
int main()
{
double input[15];
int input_size;
double sum;
FillArray(input, &input_size);
PrintArray(input, input_size);
sum = SumArray(input, &input_size);
printf("The sum is %f\n", sum);
return 0;
}
void FillArray(double a[], int *i)
{
int k;
printf("Filling an array of doubles\n");
printf("How many doubles do you want to enter (<15)\n");
scanf(" %d", i);
for (k = 0; k <*i; k++)
{
printf("Enter double:\n");
scanf("%lf", &a[k]);
}
}
void PrintArray(double a[], int i)
{
int k;
printf("Printing an array of integers:\n");
for (k = 0; k<i; k++)
{
printf("%f\n", a[k]);
}
printf("\n");
}
SumArray(double a[], int *i)
{
int k;
double sum = 0;
for (k = 0; k<*i; k++);
{
sum +=a[k];
}
return (sum) ;
}
You need to specify double SumArray(...) instead of merely SumArray(...) where you declare and define the function. If you do not specify a return type, int is assumed. Specifically:
void FillArray(double a[], int *i);
void PrintArray(double a[], int i);
double SumArray(double a[], int *i);
/*^^^^^^-- add return type*/
int main()
and
double SumArray(double a[], const int numElements)
/*^^^^^^- same deal*/ /* also ^^^^^ ^^^^^^^^^^^ */
{
int k;
double sum = 0.0; /* Edit 3: 0.0 rather than 0 for clarity */
for (k = 0; k < numElements; ++k) /* no ; here! --- Edit 3: ++k for speed and good practice */
{ /* ^^^^^^^^^^^ */
sum +=a[k];
}
return (sum) ;
}
Edit Also, you can use const int numElements instead of int *i in SumArray. You don't need to modify the value inside SumArray, so you don't need the * and you can specify const. And it's a good practice to give your variables descriptive names, e.g., numElements instead of i. That will help you understand your own code when you have to maintain it later! (Ask me how I know. ;) )
To use this, you also need to change the call in main to remove the &:
sum = SumArray(input, input_size);
/* ^ no & here */
Edit 2 As #BLUEPIXY pointed out, the trailing ; on the for loop was misplaced. As a result, the {} block ran once, after the loop had completed. That would be a significant cause of the "gibberish" you saw: the effect was to set k=numElements and then set sum=a[numElements], which was a non-existent element. So the sum was being set to whatever random memory contents happened to be after a.

Resources