Function does not update value of variable - c

I'm trying to write a program that multiplies two different complex numbers (b*c), stores the result in a prints out the result. For the purposes of keeping it simple here I've only decided to use 10 numbers and set all the imaginary and real values for b and c to the numbers 0 through 9.
First I create arrays that will contain the real and imaginary parts of the complex numbers a, b and c. Next I declare the real and imaginary part of a to be zero since I don't know these yet. To find these, I have a function named multiply that computes the real and imaginary parts of a.
Finally, in my main method I loop through all the arrays, generate values 0-9, use multiply to populate the arrays of a (as_re and as_im) containing the real and imaginary values of a, then simply printing all of these entries out.
However I only get: The product is 0 + 0i on every iteration. This has to mean that my multiply function does not update the values of a_re and a_im. Can anyone help me understand why?
My code is below:
#include <stdio.h>
#include <stdlib.h>
void multiply(int c_re, int c_im, int a_re, int a_im, int b_re, int b_im);
int as_re[10];
int as_im[10];
int bs_re[10];
int bs_im[10];
int cs_re[10];
int cs_im[10];
int a_re = 0;
int a_im = 0;
int main(){
for (int i = 0; i < 10; i++){
bs_re[i] = i;
bs_im[i] = i;
cs_re[i] = i;
cs_re[i] = i;
multiply(cs_re[i], cs_im[i], as_re[i], as_im[i], bs_re[i], bs_im[i]);
as_re[i] = a_re;
as_im[i] = a_im;
printf("The product is %d + %di\n", as_re[i], as_im[i]);
}
}
void multiply(int c_re, int c_im, int a_re, int a_im, int b_re, int b_im){
a_re = c_re * b_re - c_im * b_im;
a_im = c_re * b_im + c_im * b_re;
}

You don't need to pass global variables as parameters. If you declare a parameter or local variable with the same name as the global variable then it will hide the global variable in that function.
Removed the global variables which were included as parameters for your function.
#include <stdio.h>
#include <stdlib.h>
void multiply(int c_re, int c_im, int b_re, int b_im);
int as_re[10];
int as_im[10];
int bs_re[10];
int bs_im[10];
int cs_re[10];
int cs_im[10];
int a_re = 0;
int a_im = 0;
int main(){
for (int i = 0; i < 10; i++){
bs_re[i] = i;
bs_im[i] = i;
cs_re[i] = i;
cs_re[i] = i;
multiply(cs_re[i], cs_im[i], bs_re[i], bs_im[i]);
as_re[i] = a_re;
as_im[i] = a_im;
printf("The product is %d + %di\n", as_re[i], as_im[i]);
}
}
void multiply(int c_re, int c_im, int b_re, int b_im){
a_re = c_re * b_re - c_im * b_im;
a_im = c_re * b_im + c_im * b_re;
}

Related

How to concatenate 2 numbers using bit-wise operator, leaving initial values of variables intact?

I can not use sprintf, or any other function that puts everything together in a string n, I can not really use any libc function, it's part of a challenge I'm trying to solve
Given:
int x=5;
int y=2;
Expected Output:
res = 52;
This is one posible solution:
#include <stdio.h>
int main()
{
int x= 342;
int y= 224;
int aux = y;
while( aux ) {
aux /= 10;
x*= 10;
}
x+= y;
printf("x= %d\r\n", x); // prints 342224
}

How to calculate an answer in a function and then print it from the main() function?

I'm trying to create a program which will calculate a number based on a set of pre-set numbers. I've managed to do it, however, I need the printf part which displays the answer to be in the main() function rather than being in the function which does the calculation, and i'm not quite sure how to do it.
I've tried to just move the printf underneath main, but it says that the variables are not defined. I've also tried to put a main() after the equation calculation is done, but this doesn't work either.
The code below does what I want it to do, apart from the fact that print if is located in the equation function, rather than in the main, which is what i'm not quite sure on how to do.
My code:
#include <stdio.h>
void equation(double Rstar, double fp, int ne, double f1, double
fi, double fc, int L)
{
int N = Rstar * fp * ne * f1 * fi * fc * L;
printf("N=%d, Rstar=%.1f, fp=%.1f, ne=%d, f1=%.1f, fi=%.1f, fc=%.1f, L=%d",N,Rstar,fp,ne,f1,fi,fc,L);
}
int main(int argc, char **argv)
{
equation(1.0,0.2,1,1.0,1.0,0.1,1000);
return 0;
}
You should have your function return the result like so:
int equation(double Rstar, double fp, int ne, double f1, double
fi, double fc, int L)
{
int N = Rstar * fp * ne * f1 * fi * fc * L;
return N;
}
int main(int argc, char **argv)
{
int N = equation(1.0,0.2,1,1.0,1.0,0.1,1000);
printf("N: %d\n", N);
return 0;
}
Note that function return type is changed from void to int.
Make your function return the calculated result and prin t the returned value in the main:
#include <stdio.h>
int equation(double Rstar, double fp, int ne, double f1, double
fi, double fc, int L)
{
int N = Rstar * fp * ne * f1 * fi * fc * L;
return N;
}
int main(int argc, char **argv)
{
int N = equation(1.0,0.2,1,1.0,1.0,0.1,1000);
printf("N=%d, Rstar=1.0, fp=0.2, ne=1, f1=1.0, fi=1.0, fc=0.1, L=1000",N);
return 0;
}
I would, however, recommend on defining a struct which would hold all the input parameters, and then the function equation would get pointer to that struct instead of 7 parameters.
Example:
#include <stdio.h>
typedef struct equ_input_t
{
double rStart;
double fp;
int ne;
double f1;
double fi;
double fc;
int L;
} equ_input_t;
int equation(const equ_input_t *input)
{
int N = input->rStart * input->fp * input->ne * input->f1 * input->fi * input->fc * input->L;
return N;
}
int main(int argc, char **argv)
{
equ_input_t param = {.rStart = 1.0,
.fp = 0.2,
.ne = 1,
.f1 = 1.0,
.fi = 1.0,
.fc = 0.1,
.L = 1000 };
int N = equation(&param);
printf("N=%d, Rstar=%.1f, fp=%.1f, ne=%d, f1=%.1f, fi=%.1f, fc=%.1f, L=%d",
N, param.rStart, param.fp, param.ne, param.f1, param.fi, param.fc, param.L);
return 0;
}
You can declare the equation() function to be of type int, and return N. main() can then say X = equation ... and printf() from there.

returning a value from a two arrays and a count integer C language

int main()
{
double dUnitPriceM[]={19.99, 50.50, 2.10};
long lOrderQuantityM[] = {10, 2, 4};
int iItemCount = 3;
double dTotalCost;
dTotalCost = calculateTotalCost(dUnitPriceM, lOrderQuantityM, iItemCount);
printf("Total cost is %10.2lf\n", dTotalCost);
}
// code for calculateTotalCost function ??
double calculateTotalCost(double dUnitPriceM[], long lQuantityM[],
int iItemCount)
{
}
I am a beginner for coding C language and I am having trouble understanding how to use Arrays. I came up with the logic of creating a pseudocode but I cant code it.
All I know is that I have to start from the value of i =1; as i <= Item count, i++.
then assign i the result of the UnitPriceM[0] * QuantityM[0], increment them to the next array until it has reached its last value. Then sum the total of all the i's for example if i1= 100 + i2 = 120 + i3 =45 return them as the total cost.
#include <stdio.h>
double calculateTotalCost(double unitPrice[], long quantity[],int itemCount){
int i;
double totalCost=0.0;
for(i=0;i<itemCount;i++){
totalCost +=unitPrice[i] * quantity[i];
}
return totalCost;
}
void main() {
int i;
double dUnitPriceM[]={19.99, 50.50, 2.10};
long lOrderQuantityM[] = {10, 2, 4};
int iItemCount = 3;
double totalCost =0.0;
totalCost= calculateTotalCost(dUnitPriceM, lOrderQuantityM, iItemCount);
printf("Total cost is %f ", totalCost);
}
Here it is the basic logic of looping through all and doing the operation required.
double calculateTotalCost(double dUnitPriceM[], long lQuantityM[],
int iItemCount)
{
double sum=0;
for(int i=0;i<iItemCount;i++)
{
sum=sum+dUnitPriceM[i]*lQuantityM[i];
}
return sum;
}

Avoid using global variables when using recursive functions in C

The code below uses a recursive function called interp, but I cannot find a way to avoid using global variables for iter and fxInterpolated. The full code listing (that performs N-dimensional linear interpolation) compiles straightforwardly with:
gcc NDimensionalInterpolation.c -o NDimensionalInterpolation -Wall -lm
The output for the example given is 2.05. The code works fine but I want to find alternatives for the global variables. Any help with this would be greatly appreciated. Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int linearInterpolation(double *, double **, double *, int);
double ** allocateDoubleMatrix(int, int);
double * allocateDoubleVector(int);
void interp(int, int, double *, double *, double *);
double mult(int, double, double *, double *);
/* The objectionable global
variables that I want to get rid of! */
int iter=0;
double fxInterpolated=0;
int main(int argc, char *argv[]){
double *fx, **a, *x;
int dims=2;
x=allocateDoubleVector(dims);
a=allocateDoubleMatrix(dims,2);
fx=allocateDoubleVector(dims*2);
x[0]=0.25;
x[1]=0.4;
a[0][0]=0;
a[0][1]=1;
a[1][0]=0;
a[1][1]=1;
fx[0]=1;
fx[1]=3;
fx[2]=2;
fx[3]=4;
linearInterpolation(fx, a, x, dims);
printf("%f\n",fxInterpolated);
return (EXIT_SUCCESS);
}
int linearInterpolation(double *fx, double **a, double *x, int dims){
double *b, *pos;
int i;
b=allocateDoubleVector(dims);
pos=allocateDoubleVector(dims);
for (i=0; i<dims;i++)
b[i] = (x[i] - a[i][0]) / (a[i][1] - a[i][0]);
interp(0,dims,pos,fx,b);
return (EXIT_SUCCESS);
}
void interp(int j, int dims, double *pos, double *fx, double *b) {
int i;
if (j == dims){
fxInterpolated+=mult(dims,fx[iter],pos,b);
iter++;
return;
}
for (i = 0; i < 2; i++){
pos[j]=(double)i;
interp(j+1,dims,pos,fx,b);
}
}
double mult(int dims, double fx, double *pos, double *b){
int i;
double val=1.0;
for (i = 0; i < dims; i++){
val *= fabs(1.0-pos[i]-b[i]);
}
val *= fx;
printf("mult val= %f fx=%f\n",val, fx);
return val;
}
double ** allocateDoubleMatrix(int i, int j){
int k;
double ** matrix;
matrix = (double **) calloc(i, sizeof(double *));
for (k=0; k< i; k++)matrix[k] = allocateDoubleVector(j);
return matrix;
}
double * allocateDoubleVector(int i){
double *vector;
vector = (double *) calloc(i,sizeof(double));
return vector;
}
Thanks for the comments so far. I want to avoid the use of static. I have removed the global variable and as suggested tried parsing with the iter variable. But no joy. In addition I am getting a compile warning: "value computed is not used" with reference to *iter++; What am I doing wrong?
void interp(int j, int dims, double *pos, double *fx, double *b, int *iter) {
int i;
if (j == dims){
fxInterpolated+=mult(dims,fx[*iter],pos,b);
*iter++;
return;
}
for (i = 0; i < 2; i++){
pos[j]=(double)i;
interp(j+1,dims,pos,fx,b,iter);
}
}
There are two approaches I would consider when looking at this problem:
Keep the state in a parameter
You could use one or more variables that you pass to the function (as a pointer, if necessary) to keep the state across function calls.
For instance,
int global = 0;
int recursive(int argument) {
// ... recursive stuff
return recursive(new_argument);
}
could become
int recursive(int argument, int *global) {
// ... recursive stuff
return recursive(new_argument, global);
}
or sometimes even
int recursive(int argument, int global) {
// ... recursive stuff
return recursive(new_argument, global);
}
Use static variables
You can also declare a variable in a function to be preserved across function calls by using the static keyword:
int recursive(int argument) {
static int global = 0;
// ... recursive stuff
return recursive(argument);
}
Note that because of the static keyword, global = 0 is only set when the program starts, not every time the function is called, as it would be without the keyword. This means that if you alter the value of global, it would keep this value the next time the function is called.
This method can be used if you only use your recursive function once during your program; if you need to use it multiple times, I recommend that you use the alternative method above.
A solution is to use statics and then to reset the variables on the first call, via a flag that I call initialise. That way you can choose to have the variables reset or not.
double interp(int j, int dims, double *pos, double *fx, double *b, int initialise) {
static double fxInterpolated = 0.0;
static int iter = 0;
int i;
if (initialise){
fxInterpolated = 0.0;
iter = 0;
}
.....
......
}

Why variables sum returns multiplication?

in the following code:
void fusioneArray(int v[], int vL, int w[], int wL[], int *fusione)
{
int i,j,temp;
int k=0;
printf("%d",wL+vL);
for(i=0;i<vL;i++)
{
fusione[k]=v[i];
k++;
}
for(j=0;j<wL;j++)
{
fusione[k]=w[j];
k++;
}
}
int main()
{
int v[5]={1,2,3,4,5};
int w[5]={5,4,3,2,1};
int i=0;
int fusione[10];
fusioneArray(v,5,w,5,fusione);
}
can u explain me why vL+wL returns * instead of +? (25 instead of 10)...
Because wL is a pointer in your code, thus you're doing pointer arithmetics instead of a standard integer arithmetics :
wL+vL = wL + vL*sizeof(int)
Since a int is 4-bytes on most platforms your wL+vL becomes 5+5*4 = 25, which is the result you get. Simply replace int wL[] with the correct int wL and you'll have the desired behavior.

Resources