Function will not call correctly, C - arrays

I am a beginner and am doing pretty bad in my class right now, I just can't get some of this stuff down. I am working on one of the final homeworks and can't figure out the problem with my code. It's probably really messy but the main thing I'm having trouble with right now is the getArea function. It won't run correctly when I call it and says 'expected expression before int'. Any help is greatly appreciated, thanks
//This program takes 18 numbers and puts it in a single dimensional array and a two dimensional array.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define COLMAX 3
#define ROWMAX 6
double triArea(double a, double b, double c);
double checkValidation(double a, double b, double c);
double func1(double values[][COLMAX], int);
int main(void)
{
unsigned int seed;
double tArea = 0.0;
int rand_int();
int loop;
int col;
int row;
int counter = 0;
srand(time(NULL));
int RandomArray[18];
int ArrayTwo[6][3];
printf("\nOne dimensional array\n");
for(loop = 0; loop < 18; loop++)
{
RandomArray[loop] = rand_int();
printf("%d ", RandomArray[loop]);
}
printf("\nTwo dimensional array\n");
for(row = 0; row < ROWMAX; row++)
{
for(col = 0; col < COLMAX; col++)
{
ArrayTwo[row][col] = RandomArray[counter];
counter++;
//int total = 0;
//total = total + array2[row][col];
printf("%d\t", ArrayTwo[row][col]);
getArea(ArrayTwo[row][col]);
//printf("The total is %d", total);
}
printf("\n");
}
printf("\n");
double total = 0.0;
double ArrayTwoTotal[ROWMAX][COLMAX];
total = func1(ArrayTwoTotal, ROWMAX);
printf("total is %.2lf \n", total);
system ("PAUSE");
return 0;
}
double checkValidation(double a, double b, double c)
//triangleValueA + triangleValueB >= triangleValueC) && (triangleValueB + triangleValueC >= triangleValueA) && (triangleValueA + triangleValueC >= triangleValueB
{
int count = 0;
//a = base, b = height, c = area
if ((a + b >= c) && (b + c >= a) && (a + c >= b))
{
}
}
//Calculate area of a triangle
double getArea(int[int][int])
{
double base, height, area;
area = base*height/2.0;
printf("The area is %.lf\n", area);
checkValidation(base, height, area);
return area;
}
//Function to get the totals of the 1 dimensional array
double func1(double ArrayTwoTotal[][COLMAX], int rows)
{
double sum = 0.0;
int i, j;
for(i = 0 ; i < rows ; i++)
{
for(j = 0 ; j < COLMAX ; j++)
{
sum += ArrayTwoTotal[i][j];
}
}
return sum;
}
//Function to find a random number
int rand_int()
{
int x = 0;
x = ((rand() % 100)+1);
return x;
}

There are a lot of things that you need to look at.
First getArea() function doesn't have any declaration. Please declare it first and in a correct way.

Related

Segmentation Fault During Matrix Multiplication

I am new to C coding, and am trying to implement standard matrix multiplication. My code works fine for square matrices, but refuses to accept a column vector. Here is my attempt at the code. Any help would be much appreciated.
//---------------------------------------IMPORTING NECESSARY C PACKAGES AND DEFINING EXECUTION CONSTANTS-------------------------------------------//
#include <stdio.h> // Standard input output library
#include <math.h> // Mathematical function library
#include <stdlib.h> // General purpose standard library
#define true 1
#define false 0
typedef long double numeric; // Using the long double datatype to avoid overflows during computations
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------------FUNCTION DECLERATION-------------------------------------------------------------//
numeric **create_matrix(int x, int y); // To dynamically allocate memory and create a matrix
void input_matrix(numeric **matrix, int m, int n); // To accept a matrix
void print_matrix(numeric **l, int x, int y); // To print a matrix
numeric **standard_matrix_multiplication(int m, int n, int l); // To multiply two matrices
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------DRIVER CODE--------------------------------------------------------------------//
int main(int argc, char *argv[]) {
int m, n, l; int choice;
printf("Enter the matrix operation to be performed using the corresponding index number.\n");
printf("\n");
printf("1.\tMatrix Multiplication");
printf("\n");
scanf("%d", &choice);
switch(choice) {
case 1 :
printf("Enter the number of rows in the first matrix\n");
scanf("%d", &m);
printf("Enter the number of columns in the first matrix\n");
scanf("%d", &n);
printf("Enter the number of columns in the second matrix\n");
scanf("%d", &l);
printf("Enter both matrices.\n");
numeric **matrix_x;
matrix_x = create_matrix(m, l);
matrix_x = standard_matrix_multiplication(m, n, l);
print_matrix(matrix_x, m, l);
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------MATRIX MULTIPLICATION IMPLEMENTATIONS--------------------------------------------------//
numeric **standard_matrix_multiplication(int m, int n, int l) {
numeric **matrix_a; numeric **matrix_b; numeric **matrix_k;
matrix_a = create_matrix(m, n);
matrix_b = create_matrix(n, l);
matrix_k = create_matrix(m, l);
input_matrix(matrix_a, m, n);
print_matrix(matrix_a, m, n);
input_matrix(matrix_b, n, l);
for(int i = 0; i < m; i++) {
for (int j = 0; j < n; j ++) {
for (int k = 0; k < l; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
}
}
}
return matrix_k;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------HELPER FUNCTIONS------------------------------------------------------------------//
numeric **create_matrix(int x, int y) {
numeric **matrix = (numeric**)malloc(x * sizeof(numeric*)); // Dynamically creating an array of pointers
for (int i = 0; i < y; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric)); // Dynamically allocating memory for each columns of the matrix
}
return matrix;
}
void input_matrix(numeric **matrix, int m, int n) {
printf("Enter the elements of the matrix, row wise.\n"); // Instructing the user on matrix entry
printf("For example, to enter the matrix\n");
printf("\t\t1\t2\n");
printf("\t\t3\t4\n");
printf("enter 1, 2, 3, and 4 in that order.\n");
for (int i = 0; i < m; i++) { // Iterating through the rows and columns of the matrix
for (int j = 0; j < n; j++) {
scanf("%Lf", &matrix[i][j]); // Accepting each element
}
}
}
void print_matrix(numeric **l, int x, int y) { // To print a matrix
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
printf("%0.10Lf\t", l[i][j]); // Printing numeric type values
}
printf("\n");
}
printf("\n");
}
As of now, I have only written one switch case, and that is for matrix multiplication. So I chose 1. I gave 2, 1, 2 as my inputs for the number of rows in the first matrix, number of columns in the first matrix, and number of columns in the second matrix respectively. I have given a print statement in line 52, and it isn't executing it for the above input, giving a segmentation fault instead. Could someone please help me out?
Yes there are some issues with your code that gives segfault error during runtime.
The Matrix multiplication logic part of the code needs to be corrected as follows
for(int i = 0; i < m; i++) {
for (int j = 0; j < l; j ++) {
for (int k = 0; k < n; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
because k should iterate till the no of columns in 1st matrix which is n but not till l.
And there is a slight correction needed in create_matrix function.
You use y (i.e. no of columns in the matrix) in your for instead of x (no of rows in matrix).
If x < y, you end up outside of the memory you allocated.
If x > y, you end up with uninitialized pointers.
So change it as follows
for (int i = 0; i < x; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric));
After these corrections try executing the code, you should get the expected results without any segfault errors
Here is the complete working code
#include <stdio.h> // Standard input output library
#include <math.h> // Mathematical function library
#include <stdlib.h> // General purpose standard library
#define true 1
#define false 0
typedef long double numeric; // Using the long double datatype to avoid overflows during computations
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------------FUNCTION DECLERATION-------------------------------------------------------------//
numeric **create_matrix(int x, int y); // To dynamically allocate memory and create a matrix
void input_matrix(numeric **matrix, int m, int n); // To accept a matrix
void print_matrix(numeric **l, int x, int y); // To print a matrix
numeric **standard_matrix_multiplication(int m, int n, int l); // To multiply two matrices
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//------------------------------------------------------------------DRIVER CODE--------------------------------------------------------------------//
int main(int argc, char *argv[]) {
int m, n, l; int choice;
printf("Enter the matrix operation to be performed using the corresponding index number.\n");
printf("\n");
printf("1.\tMatrix Multiplication");
printf("\n");
scanf("%d", &choice);
switch(choice) {
case 1 :
printf("Enter the number of rows in the first matrix\n");
scanf("%d", &m);
printf("Enter the number of columns in the first matrix\n");
scanf("%d", &n);
printf("Enter the number of columns in the second matrix\n");
scanf("%d", &l);
printf("Enter both matrices.\n");
numeric **matrix_x;
matrix_x = create_matrix(m, l);
matrix_x = standard_matrix_multiplication(m, n, l);
print_matrix(matrix_x, m, l);
break;
}
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//----------------------------------------------------------MATRIX MULTIPLICATION IMPLEMENTATIONS--------------------------------------------------//
numeric **standard_matrix_multiplication(int m, int n, int l) {
numeric **matrix_a; numeric **matrix_b; numeric **matrix_k;
matrix_a = create_matrix(m, n);
matrix_b = create_matrix(n, l);
matrix_k = create_matrix(m, l);
input_matrix(matrix_a, m, n);
print_matrix(matrix_a, m, n);
input_matrix(matrix_b, n, l);
//print_matrix(matrix_b, n, l);
for(int i = 0; i < m; i++) {
for (int j = 0; j < l; j ++) {
for (int k = 0; k < n; k++) {
matrix_k[i][j] += matrix_a[i][k] * matrix_b[k][j];
}
}
}
return matrix_k;
}
//-------------------------------------------------------------------------------------------------------------------------------------------------//
//---------------------------------------------------------------HELPER FUNCTIONS------------------------------------------------------------------//
numeric **create_matrix(int x, int y) {
numeric **matrix = (numeric**)malloc(x * sizeof(numeric*)); // Dynamically creating an array of pointers
for (int i = 0; i < x; i++) {
matrix[i] = (numeric*)malloc(y * sizeof(numeric)); // Dynamically allocating memory for each columns of the matrix
}
return matrix;
}
void input_matrix(numeric **matrix, int m, int n) {
printf("Enter the elements of the matrix, row wise.\n"); // Instructing the user on matrix entry
printf("For example, to enter the matrix\n");
printf("\t\t1\t2\n");
printf("\t\t3\t4\n");
printf("enter 1, 2, 3, and 4 in that order.\n");
for (int i = 0; i < m; i++) { // Iterating through the rows and columns of the matrix
for (int j = 0; j < n; j++) {
scanf("%Lf", &matrix[i][j]); // Accepting each element
}
}
}
void print_matrix(numeric **l, int x, int y) { // To print a matrix
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
printf("%0.10Lf\t", l[i][j]); // Printing numeric type values
}
printf("\n");
}
printf("\n");
}
You are not allocating enough memory for matrix_k. You are allocating memory for m rows and l columns, but you are trying to access m rows and n columns. You need to allocate memory for m rows and n columns. You can do this by changing the line
matrix_k = create_matrix(m, l);
to
matrix_k = create_matrix(m, n);
This is the same problem you had in your other question.

Error when passing 2D array to function in c

I am writing a program to calculate matrix multiplication but it does not work. When I debug and check each value of the array a and b in function printMatrixMultiplication (which are entered by user), GDB prints out "cannot perform pointer math on incomplete type try casting". (I have searched for it but I still don't get it.) The function only works when the input is predefined in main.
This is my code
#include <stdio.h>
void input(int m, int n, double a[m][n]);
void output(int m, int n, double a[m][n]);
void printMatrixMultiplication(int row_a, int col_a, double a[row_a][col_a], int row_b, int col_b, double b[row_b][col_b]);
int main()
{
int row_a, col_a, row_b, col_b;
// get value of matrix a
printf("row_a = ");
scanf("%d", &row_a);
printf("col_a = ");
scanf("%d", &col_a);
double a[row_a][col_a];
input(row_a, col_a, a);
// output(row_a, col_a, a);
// get value of matrix b
printf("row_b = ");
scanf("%d", &row_b);
printf("col_b = ");
scanf("%d", &col_b);
double b[row_b][col_b];
input(row_b, col_b, a);
// output(row_b, col_b, a);
printMatrixMultiplication(row_a, col_a, a, row_b, col_b, b);
//test
// double a[2][2]={1,2,3,4};
// double b[2][3]={1,2,3,4,5,6};
// printMatrixMultiplication(2,2,a,2,3,b);
return 0;
}
void input(int m, int n, double a[m][n])
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
scanf("%lf", &a[i][j]);
}
}
}
void output(int m, int n, double a[m][n])
{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
{
printf("%.2f ", a[i][j]);
}
printf("\n");
}
}
void printMatrixMultiplication(int row_a, int col_a, double a[row_a][col_a], int row_b, int col_b, double b[row_b][col_b])
{
if (col_a != row_b)
{
return;
}
double res[row_a][col_b]; //this matrix store results
for (int i = 0; i < row_a; i++) //the values be stored line by line, this
{ //operation is controled by i and j loops.
for (int j = 0; j < col_b; j++) //the k loop helps calculate dot_product.
{
double dot_product = 0;
for (int k = 0; k < col_a; k++)
{
dot_product += a[i][k] * b[k][j]; //ERROR HERE
}
res[i][j] = dot_product;
}
}
output(row_a, col_b, res);
}
So, where does the error come from and how to fix it?
Irrelevant, but the function is not well implemented so if possible, I would really appreciate if anyone gives me a hint to improve it.
I am using GCC version 6.3.0.
It's typo in your code when reading matrix b.
Just replace:
input(row_b, col_b, a);
with
input(row_b, col_b, b);

C.find an error in a very small program.Calculating the sum of the first k numbers of the sequence

Calculating the sum of the first k numbers of the sequence a[0] = 1, a[k] = k*a[k-1] +1/k ( k = 1, 2, ... ).
UPD
There is still a problem with the recursive function ...What is the error?
#include <stdio.h>
#include <stdlib.h>
float m(float n){
float k=1;
float sum=k;
int i;
for (i=1; i<n;i++){
k = (i*k+1.0/i);
sum = sum+k;
}
return sum;
}
float Fn(float n)
{
if (n==0) {
return 1;}
return ((n*Fn(n-1)+1.0/n)+Fn(n-1));
}
int main(int argc, char *argv[]) {
float k;
printf("input k : ");
scanf("%f",&k);
printf("res %f \n",Fn(k));
return 0;
}
There were several issues in your code:
Integer division: 1/n = 0
There was a confusion between the term value Fn and the sum value
An iterative solution is simpler here than a recursive one
Here is a code, with both iterative and recursive implementations:
#include <stdio.h>
#include <stdlib.h>
float sum_fn(int n){
float Fk = 1;
float sum = Fk;
for (int i = 1; i <= n; i++){
Fk = i*Fk + 1.0/i;
sum += Fk;
}
return sum;
}
float sum_recursive(int n, float *sum){
if (n == 0) {
*sum += 1.0;
return 1.0;
}
float Fn = n * sum_recursive(n-1, sum) + 1.0/n;
*sum += Fn;
return Fn;
}
int main(int argc, char *argv[]) {
int k;
printf("input k : ");
scanf("%d", &k);
printf("k = %d\tsum = %f\n", k, sum_fn(k));
float sum = 0;
sum_recursive(k, &sum);
printf("k = %d\tsum = %f\n", k, sum);
return 0;
}

how to return two values in one function without using struct?

#include <stdio.h>
#include <stdlib.h>
double calculate(int ar[], int npts, int *gtr);
int main()
{
int ar[4] = {1,2,3,0};
double result;
result = calculate(ar,4, &ar);
printf("%lf ",result );
return 0;
}
double calculate(int ar[], int npts, int *gtr)
{
double total =0;
int i = 0;
double average;
for(i=0; i<npts; i++)
{
total = total + ar[i];
}
average = total / npts;
return average;
for(i=0; i<npts; i++)
{
if(average < ar[i])
{
*gtr++;
}
}
return *gtr;
}
when i call function calculate i want to return both average and *gtr value
but avergage only average value return. *gtr is for counting how many numbers greater than average numbers in arrary.
from what i understand,you want to return the average,and somehow get the value of gtr.you can return the average value,and save the gtr value to another variable by using a pointer.
int main()
{
int ar[4] = {1,2,3,0};
double result;
int gtr = 0;
result = calculate(ar,4,&gtr);
printf("%lf\n",result );
printf("gtr : %d\n",gtr);
return 0;
}
double calculate(int ar[], int npts, int *gtr)
{
double total = 0 , average;
int i = 0;
for(i=0; i<npts; i++)
{
total = total + ar[i];
}
average = total / npts;
for( i = 0 ; i < npts ; i++ )
{
if(average < ar[i])
{
*gtr += 1;
}
}
return average;
}
You made the function almost right, it's the call that must be done differently.
First, don't return *gtr from the function; return average. Do it at the end, though, not in the middle.
Then, change the call to
int gtr;
result = calculate(ar,4, &gtr);
printf("%lf %d\n",result, gtr);
Make sure that you set *gtr to zero before the second loop, otherwise it would remain uninitialized.
For return both value you can do this:
double calculate(int ar[], int npts, int *gtr)
{
double total =0;
int i = 0;
double average;
for(i=0; i<npts; i++)
{
total = total + ar[i];
}
average = total / npts;
return average;
for(i=0; i<npts; i++)
{
if(average < ar[i])
{
*gtr++;
}
}
return avergage;
}
so, returning avergage you have the first variable, and using the puntator value of gtr you can have that value.

Problems with parameters passing

Given the following code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define NPOINTS 200
#define NMEASURES 50
#define PI 3.1415f
double mcIntSingleExp1(int);
double mcIntSingleExp1(int n){
int i, countIn = 0;
double x,y, integral1, integral2;
srand(time(NULL));
for(i = 0; i < n; i++){
x = ((double)rand()/(double)RAND_MAX)*PI;
y = (double)rand()/(double)RAND_MAX;
if(y <= sin(x))
countIn++;
}
integral1 = (PI * (double)countIn)/(double)n;
countIn = 0;
for(i = 0; i < n; i++){
x = ((double)rand()/(double)RAND_MAX) + PI;
y = ((double)rand()/(double)RAND_MAX) -1;
if(y >= sin(x))
countIn++;
}
integral2 = (PI * (double)countIn)/(double)n;
return integral1 - integral2;
}
double mcIntSingleExp2(int);
double mcIntSingleExp2(int n){
int i;
double x, sum = 0;
srand(time(NULL));
for(i = 0; i < n; i++){
x = ((double)rand()/(double)RAND_MAX) + 2*PI;
sum += sin(x);
}
return (1/(double)n) * sum;
}
void mcIntMultExp1(int, double [], int);
void mcIntMultExp1(int k, double res1[], int n){
int i;
for(i = 0; i < k; i++)
res1[i] = mcIntSingleExp1(n);
}
void mcIntMultExp2(int, double [], int);
void mcIntMultExp2(int k, double res2[], int n){
int i;
for(i = 0; i < k; i++)
res2[i] = mcIntSingleExp2(n);
}
double mean(double [], int);
double mean(double v[], int size){
int i;
double sum = 0;
for(i = 0; i < size; i++)
sum += v[i];
return sum/(double)size;
}
double stdDev(double [], int);
double stdDev(double v[], int size){
int i;
double avg, std_dev = 0;
avg = mean(v,NMEASURES);
for(i = 0; i < size; i++)
std_dev += (v[i]-avg)*(v[i]-avg);
return sqrt(std_dev/(double)size);
}
int main(){
double measure, deviation, res1[NMEASURES], res2[NMEASURES];
mcIntMultExp1(NMEASURES, res1, NPOINTS/2);
mcIntMultExp2(NMEASURES, res2, NPOINTS);
measure = mean(res1, NMEASURES);
deviation = stdDev(res1, NMEASURES);
printf("\nIntegral 1 = %.14lf\nStandard Deviation 1 = %.14lf\n",measure,deviation);
measure = mean(res2, NMEASURES);
deviation = stdDev(res2, NMEASURES);
printf("\nIntegral 2 = %.14lf\nStandard Deviation 2 = %.14lf\n",measure,deviation);
return 0;
}
In the stdDev function I noticed that each element of the vector v is equal to avg (v [0] = v [1] = ... = avg), so the standard deviation is zero! In fact, the elements of v should be those of res1 or res2. I do not understand what is wrong!
Your code probably runs quickly enough that time(NULL) will usually always return the same value. After doing an srand with a given seed, the following calls to rand will return the same values each time.
We usually only execute srand(time(NULL)) once at the beginning of a program.

Resources