Syntax error with multiple declarations in for loop - c

#include <stdio.h>
#include <math.h>
#include <conio.h>
#include <locale.h>
int main()
{
setlocale(LC_ALL, "Rus");
float arr[25];
int i;
double x;
int a, b, c, e, f;
double y = a * pow(x, 2) + b * x + c;
printf("a: ");
scanf_s("%d", &a);
printf("b: ");
scanf_s("%d", &b);
printf("c: ");
scanf_s("%d", &c);
printf("e: ");
scanf_s("%d", &e);
printf("f: ");
scanf_s("%d", &f);
double interval = (f - e) / 25.0 ;
for (int i = 0, double x = e; i < 25; i++, x += interval)
{
printf("%f", y);
x++;
}
system("pause");
}
I get [Error] expected identifier or '(' before 'double'. How can i fix it? It doesnt seem like i really need to change something in
for (int i = 0, double x = e; i < 25; i++, x += interval)
or maybe im wrong and dont know how to write multiple conditions.

Yeah, you can't do that.
By the way, those are declarations, not conditions. Only the middle part of a for loop is a condition.
You can declare multiple variables in the first part of a for loop, but only if they have the same base type (e.g. int):
for (int x = 1, y = 2, z = 3; ...; ...)
The workaround in your case is to declare at least one of the variables outside of the loop:
{ // this outer block limits the scope of x
double x = e;
for (int i = 0; i < 25; i++, x += interval)
{
printf("%f", y);
x++;
}
}
That said, your code doesn't really make sense. Your loop doesn't use x, so there's no point in setting it. On the other hand, the value you're printing 25 times (y) doesn't change in the loop. It's set at the top of your main function, computed from a different x variable that is uninitialized.
You should move the declaration and initialization of y into the loop and delete the outer x. See also https://stackoverflow.com/a/53238897/1848654.

You can't define variables with multiple types with the comma:
for(int i = 0, double x...
Instead:
x = e;
for (int i = 0; i<...
and the x is already defined above.

You could embedded them into a struct. I do not recommend it because IMO it is not a good coding practice as it is not easy to understand (at first sight)…
typedef struct {int i; double x;} S;
for (S yourStruct = {0,e}; yourStruct.i < 25 ; yourStruct.i++, yourStruct.x += interval)
{
printf("%f", y);
yourStruct.x++;
}

It is not really a matter of the for loop:
void f(void)
{
int x, y; // legal - and you can do the same in a for loop's initialization section
int z, double d; // can't do that either, even outside for loop...
};
All variables that you declare in a single expression need to have the same (base!) type, be it within for loop, function body or global. 'Base type': Well, because you legally can do stuff like int x, *p;, with x and p being of different type, but base/underlying type in both cases is int.

Related

Trying to create a line with a function and then print it with another function

guys. I'm a beginner and have to create a function that returns a line of output type Line from inputs y intercept and slope, and create another function that prints it. When I run the functions, it mostly prints right, but x prints as 0.00. I need it to print as an x variable because I will later be making a function that finds the intercept of two lines.
Here's the create function:
Line createLine (double m, double b) {
Line y;
double x;
y.m = m;
y.b = b;
//y = y.m * x + y.b; get an error saying the types dont match so I stopped using this
return y;
The print function:
void displayLine (Line a){
double x;
printf("y = %lf * %lf + %lf\n", a.m, x, a.b);
And the struct:
typedef struct line_struct{
double m;
double b;
} Line;
I also have a point struct if it matters.
You're assuming the variable x will get printed as the output, but the way you've desired won't work. The x is an identifier name and hence, it can't be used to print its name itself.
Thus, you don't need to use any other stuff here at all. Just simply print x in the printf() statement and you're done.
Also, note that, as per of your requirement, we've used int datatype here rather than using double, the double is only required when you need to show a very large floating point value which can't be held by the float itself.
You may try this way to achieve:
#include <stdio.h>
struct line_struct {
int m;
int b;
} Line;
Line createLine(int m, int b) {
Line y;
y.m = m;
y.b = b;
return y; // returning the initialized struct to the function correctly
}
void displayLine (Line a){
printf("y = %dx + %d\n", a.m, a.b); // displaying a simple 'x'
}
int main(void) {
Line l;
l.b = 3;
l.m = 4;
displayLine(l);
return 0;
}
This will give you the desired output:
y = 4x + 3
If all you want is to print the line y = 4x + 3, you don't need a variable called x at all. This will suffice:
printf("y = %lf x + %lf\n", a.m, a.b);
I think the error is in the createLine function.
I hope it works this way.
Line createLine (double m, double b) {
Line y;
double x;
y.m = m*x;
y.b = b;
return y;
}

Write a C function to evaluate the series // sin(x) = x-(x3 /3!)+(x5 /5!)-(x7 /7!)+... // up to 10 terms

#include <stdio.h>
#include<math.h>
int series(float,float);
int main()
{
float x,n,series_value;
printf("Enter the value of x: ");
scanf("%f",&x);
printf("\nEnter the value of n: ");
scanf("%f",&n);
series_value=series(x,n);
printf("\nValue of series sin (%.2f) is: %f\n",x,series_value);
return 0;
}
int series(float x,float n)
{
int i,sum=0,sign=-1;
int j,fact=1,p=1;
for (i=1; i<=(2*n)-1; i+=2)
{
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
sign=-1*sign;
sum=sum + sign*p/fact;
}
return (sum);
}
Output:
Enter the value of x: 5
Enter the value of n: 10
(lldb)
and this message
Thread 1: EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)
![Thread 1 Queue : com.apple.main-thread (serial)
]1
Why is this message coming? and what is wrong in the program as answer is not coming right
There is a few problems with your code. As #PaulHankin said, when fact overflows and becoms zero, you will have a division by zero, and "weird things" happen.
Your factorial and power calculation is also wrong. You are recalculating it in each iteration of the outer loop without reseting fact and p first:
fact = 1; // You need to reset fact and p to its start value here
p = 1;
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
Your third problem is that for your function calculate the correct value for sin, which is not an integer value, you need to use float, or even better double, when calculating sum. So sum must be declared float, and the division p/fact must use float division. By also declaring p and fact as float, you will solve both the overflow issue, and use the correct division. Naturally your function must also return a float
float series(float x,float n)
{
int i,sign=-1;
int j,
float sum = 0;
float fact = 1;
float p = 1;
for (i=1; i<=(2*n)-1; i+=2)
{
fact = 1;
p = 1;
for (j=1; j<=i; j++)
{
p=p*x;
fact=fact*j;
}
sign=-1*sign;
sum=sum + sign*p/fact;
}
return (sum);
}
This code still has a minor problem. By having an inner loop, it is slower than necessary. Since this probably is homework, I am not getting rid of that loop for you, just giving you a hint: You don't have to recalculate fact from scratch on each iteration of the outer loop, just try to find out how fact changes from one iteration to the next. The same goes for p.
//Series of Sinx
#include<stdio.h>
#include<math.h>
#define ACCURACY 0.0001
int factorial(int n);
int main()
{
float x,sum,term;
int i,power;
printf("Enter value of X: ");
scanf("%f",&x);
i=1;
power=3;
sum=x;
term=x;
while(term>=ACCURACY)
{
term = pow(x,power) / factorial(power);
if(i%2==1)
{
sum -= term;
}
else
{
sum += term;
}
power+=2;
i++;
}
printf("sin(%f) = %.6f\n",x,sum);
return 0;
}
int factorial(int n){
int i=n,fact=1;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
return fact;
}
plenty bugs. To do not caclulate the fact values all the time they are in the lookup table
#include <stdio.h>
#include <math.h>
double series(double,int);
long long fact[] = { 1, 2, 6, 24,
120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600,
6227020800, 87178291200, };
double mypow(double x, unsigned p)
{
double result = x;
while(p && --p)
result *= x;
return result;
}
int main()
{
for(double x = 0; x <= M_PI + M_PI / 60; x += M_PI / 30)
printf("Value of series sin (%.2f) is: %f\n",x,series(x, 5));
fflush(stdout);
}
double series(double x,int n)
{
double sum = x;
int i,sign=1;
for (i=3; i<=(2*n)-1; i+=2)
{
sign=-1*sign;
sum += sign*(mypow(x, i)/fact[i -1]);
}
return (sum);
}
https://godbolt.org/z/U6dULN
maybe its due to floating-point exception as u have declared that the function should return int type value
int series(float,float);//hear
so u can try editing the return type of this function as float
Note:-also u need to change at function definition and the datatype of
int i,sum=0,sign=-1;
int j,fact=1,p=1;
to float as it is returning the value (sum) which should also be float

macro equation giving bogus value?

When I run my code, for Y I am consistently getting the value -2147483648, regardless of what value y was fed into my equation.
Here is my code.
#define MAX 1000
#define EQ(y) ((2*(pow(y, 4)))+1)
int check(int value);
int main()
{
int i, y, x;
for(y = 1; y < MAX; y++)
{
i = EQ(y);
if(check(i))
printf("combination found: x = %d, y = %d", sqrt(i), y);
}
}
int check(int value)
{
int x = sqrt(value);
if ((x*x) == value)
return 1;
else
{
return 0;
}
}
After reviewing my code, I realized my problem was with my "int x = sqrt(value)". Aside from the problem with the "value" variable being an int, of course, a bogus value was still being returned due to the fact that the purpose of check is to evaluate whether or not (2*(pow(y, 4)))+1) returned a perfect whole square for any given value of y, and this was not possible due to variable x in check(double value) being datatype integer.
UPDATE: I rewrote my code as follows. I still don't get any correct returns
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
/*
* the solution I implemented basically involved dropping x from the equation, solving for y, checking to see if it has a
* perfect square root. if it does, then x = the squareroot of y in the function EQ.
* original problem: for equation x^2 - 2y^4 + 1 = 0, find all possible solutions up to arbitrary maximum
*/
#define MAX 100000
#define EQ(g) (((pow(g, 4.0)))+1)
int check(double value);
int main()
{
int y, x;
double i;
for(y = 1; y < MAX; y++)
{
i = EQ(y);
if(x = check(i) > 0)
printf("combination found: x = %d, y = %d\n", y, x);
}
}
int check(double value)
{
double x = sqrt(value);
int n = (int) x;
printf("%d\n%f\n%f\n", n*n, value, x);
if (n*n == value)
return n*n;
else
return 0;
}
Read the comments are the top of my code, and the purpose for this selection should be pretty obvious.
You don't have a prototype for double pow(double, double); so the compiler implicitly assumes its signature is int pow(int, int);. Not good!
The solution is to #include the appropriate header at the top of your .c file.
#include <math.h>
Make sure you enable warnings, and if they're already enabled, pay attention to them! Your compiler should warn you about the missing prototype. (It should also spit out a similar warning for printf.)
pow() returns double and you are using integer i to store the return value.
Due to type promotion during expression evaluation the expression:
((2*(pow(y, 4)))+1)
will give a double value and you are storing this in integer type which will give unexpected results.
In reference to your updated question, this line:
if(x = check(i) > 0)
needs to be parenthesized:
if((x = check(i)) > 0)
This is the declaration of pow:
double pow(double x, double y)
Which means it operates in double. By using int instead, variable y is overflowing.

Simple calculation inside a function

I'm trying to do the calculation inside a function, but i'm not sure why it's not working:
int calculate(int x){
x = x + 2;
return x;
}
int main(){
int x = 0;
int i;
for(i=0;i<10;i++){
calculate(x);
}
printf("i = %d, x = %d\n", i, x);
}
I understand that x is 0 every time it passes through the function. But how do I fix it?
Supposedly i should return 10, and x should return 20.
You can actually pass the pointer of that integer you want to change, not the value itself. In that case, the new (increased) integer will be stored in the original level of scope (actually at the exact same memory spot), where it was defined, which is in this case is your main function. So your code, should look like this:
void calculate(int *x)
{
*x += 2;
}
int main(void)
{
int x = 0;
for (int i=0; i<10; i++)
{
calculate(&x);
printf("i=%d, x=%d\n", i, x);
}
return 0;
}
OUTPUT:
i=0, x=2
i=1, x=4
i=2, x=6
i=3, x=8
i=4, x=10
i=5, x=12
i=6, x=14
i=7, x=16
i=8, x=18
i=9, x=20
Variables can shadow each other. You don't have to ensure that you never, ever use i anywhere else in fear of messing with the i in your for loop, because a new scope will get a new copy of the same name (like when two different people have the same name).
To fix this, you can return the value from your calculate function. I named it x2 to clearly differentiate it from your original x:
int calculate(int x2){
x2 = x2 + 2;
return x2;
}
int main(){
int x = 0;
int i;
for(i=0;i<10;i++){
x = calculate(x);
}
printf("i = %d, x = %d\n", i, x);
}
If you want x to change, you need to pass it by reference, not by value.
void calculate(int *x){
*x = *x + 2;
}
int main(){
int x = 0;
int i;
for(i=0;i<10;i++){
calculate(&x);
}
printf("i = %d, x = %d\n", i, x);
}
You're passing x by value, so calculate only changes a local copy. When calculate returns, the result is lost. You need to return the modified value from calculate and assign it to something in main.
You're passing in x as a value (ie. it is copied). So x inside the calculate function is not the same as x outside of it. Thus, when you change its value, the change is not reflected in the x that is in main.
The following would be preferable. Note that you need to return a value from the calculate function, and then assign what it returns to some value.
int calculate(int x){
return x + 2; /* CHANGED */
}
int main(){
int x = 0;
int i;
for(i=0;i<10;i++){
x = calculate(x); /* CHANGED */
}
printf("i = %d, x = %d\n", i, x);
}
Change:
for(i=0;i<10;i++){
calculate(x);
}
to:
for(i=0;i<10;i++){
x = calculate(x);
}
Your function returns a value, thus you need to store it somewhere.
In the function you can just change one thing and iguess it will work
Int calculate(int &x)
And keep rest other things same
Basically u can use "alias"

Void Function Error?

So I had to write a program that used the Pythagorean Threes concept where if you entered a number it would give you all the combinations less than that number that would produce a correct a^2 + b^2 = c^2 output.
Not sure if I explained the assignment well, but basically I understand the logic or at least I think I do I was wondering if you guys could help me find out why I am getting this error....
For the last line of my code it gives me, "warning: control reaches end of non-void function [-Wreturn-type]," As the error any idea what I am doing wrong?
#include <stdio.h>
int main(void){
int x = 0, y = 0, z = 0, n;
int count = 0;
printf("Please Enter A Positive Integer: \n");
scanf("%d", &n);
while(z <= n){
while(y < z){
while(x < y){
if(x * x + y * y == z * z)
printf("%d: \t%d %d %d\n", ++count, x, y, z);
x += 1; }
y += 1; }
z += 1;
}
}
int main(void){
Your function header indicates that you're looking to return an int. To fix this, return a number (0 usually indicates a normal termination) at the end of your function.
To break it down a little,
int indicates the return type,
main is the method name, and
void indicates that there are no parameters for this method.
Your main function is declared to return an int, but you don't return anything.
put return 0; before the closing brace of your main.
int main( void )
{
// ... code ...
return 0;
}

Resources