Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include <stdio.h>
int main()
{
int x = 1, y = 1;
for(;y;printf("%d%d\n",x,y))
y = x++ <= 5;
return 0;
}
I'm confused about the structure of the for construct in the code snippet above. It's taken form a book on programming in C.
The correct output is the following according to the book.
2 1
3 1
4 1
5 1
6 1
7 0
Can someone explain how and why this is the output?
To understand what the for loop does, here is the equivalent while loop:
while (y) {
y = x++ <= 5;
printf("%d%d\n",x,y);
}
The transformation goes like this:
for (INIT; COND; INC) {
BODY;
}
->
INIT;
while (COND) {
BODY;
INC;
}
Note that in C the expression y is equivalent to y != 0 if y is an int.
The construct becomes easy to understand if you expand it.
I reckon the trick here is in understanding that the suffix incrementation of x happens after the comparison.
Another concept shown in your example is the fact that in C all comparisons return a boolean value (1 for true and 0 for false).
#include <stdio.h>
int main()
{
int x = 1, y = 1;
printf("first version:\n");
for(;y;printf("%d%d\n",x,y))
y = x++ <= 5;
printf("second version:\n");
x = 1;
y = 1;
while (y != 0)
{
if (x <= 5)
y = 1;
else
y = 0;
x = x + 1;
printf ("%d%d\n",x,y);
}
return 0;
}
I hope this answers your question.
To summarize how for loop works in C:
for(initialization; condition; expression) {
//statements
}
1. initialization is executed before the first evaluation of the condition
2. expression is evaluated after every iteration of the loop. 3. The loop will only be entered when the condition is true.
In your code, please note that in the line,
y = x++ <= 5;
' x ' is compared with the number 5 before its value is incremented. For example, on the 5th iteration x=5 is checked against (<=5), then it is incremented to 6. After that the statement
printf("%d%d\n",x,y)
is executed printing "61".
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
gdb compiler is showing an error to the code below. why did the error occur and how to fix it.
#include <stdio.h>
int s(int n);
int main(){
int n;
printf("enter a number");
scanf("%d",&n);
printf("%d",s(n));
return 0;
}
int s(int n){
s(1) = 1; //error: lvalue required as left operand of assignment
s(2) = 1; //error: lvalue required as left operand of assignment
s(n) = s(n-1) + s(n-2); //error: lvalue required as left operand of assignment
return s(n);
}
You are doing wrong, as #paulsm4 pointed out, you cannot assign value to a function. Change your s function to this:
int s(int n){
if(n <= 2){
return 1;
}
return s(n-1) + s(n-2);
}
I think what you meant to write was the equivalent of
fib(1) = 1;
fib(2) = 1;
fib(n) = fib(n - 1) + fib(n -2);
In C, you can't assign a value to the result returned by a function. So something like
foo(1) = 1;
is incorrect code. To explain the compiler error, you need to understand what an lvalue is. To put it simplistically, an lvalue is something to which you can assign a value and take its address. One way to think of it is that lvalue usually appears on the left hand side of an expression. So for something like
int x = 2;
x is an lvalue since you are assigning to it and you can take the address of x (using &x). This isn't true for the value returned by a function.
Coming to your original problem
int s(int n){
s(1) = 1;
s(2) = 1;
s(n) = s(n-1) + s(n-2);
return s(n);
}
As discussed above statements like s(1) = 1 etc. are incorrect code. So fib(1) = 1 should translate to a function that returns the value of 1. Similarly for 2. For any general n you need to write the function that uses these base cases and then return the actual value.
So something like
int s(int n){
if(n == 1 || n == 2) { //Base case
return 1;
}
return s(n-1) + s(n-2); //Recursion
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I want to generate x number of random numbers and everything works except it gives me sequenced numbers, not random numbers.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
int x;
printf("How many elements do you want?\n");
scanf("%d", &x);
int *array = (int *)malloc(x * sizeof(int));
srand(time(NULL));
for(int y = 0; y < x; y++){
*(array + y) = 2 + rand() % 99;
}
for(int y = 0; y <x; y++){
printf("Array element %d: %d\n", y, (*array+ y));
}
return 0;}
It gives the numbers like: 27 28 29 30 31, only the first number is random in each execution, others are sequential.
Most likely you're printing a wrong value.
You need to change (*array+ y) to *(array+ y) in printf() statement, otherwise, you end up printing the value of the first random number, plus the iteration counter (which explains the output you get).
Just to add some opinionated view: The array indexing operator [] is there, some chose to prefer using it to avoid mistakes just like this. Your statements can be easily re-written to make use of that, like
for(int y = 0; y < x; y++){
array[y] = 2 + rand() % 99;
}
for(int y = 0; y <x; y++){
printf("Array element %d: %d\n", y, array[y]);
}
That said,
Please see do I cast the result of malloc?
Always check for the success of the called function before using the return value. Check against NULL return of the malloc() call, otherwise you may end up dereferencing NULL, which invokes undefined behavior
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am trying to learn C but my code is not running properly.It always gives fatal error.I think there is a problem in for loop.How can i fix it?
#include<stdio.h>
int main( void )
{
int a ;
int b = 1 ;
int i = 0 ;
printf("Enter a number:");
scanf("%d",&a);
if(a=0)
printf("Factorial=1");
else if (a > 0){
for(i=1 ; i<=a ;i++){
b = 1;
b *= i;
}
printf("Factorial=%d",b);
}
else
printf("FATAL ERROR");
return 0;
}
if(a==0) Not assignment use comparison.
You wanted to use the comparison but you ended up using assignment.
if(a=0) is same as if(0) so else part is executed.1
But that part also looks for a>0 which is not the case.
So it prints FATAL ERROR.
1. This happens because the result of an assignment expression is the value of the expression
What do I need to do to calculate factorial?
fact(0)=1
fact(1)=1
fact(n)=n*fact(n-1);
so you will do something like
for(int i=1;i<=a;i++)
b*=i;
You don't need that b=1 part because it is making everything 1. So your calculated value is not retained.
So the complete corrected code will be
#include<stdio.h>
int main()
{
int a;
int b = 1 ;
int i = 0 ;
printf("Enter a number:");
scanf("%d",&a);
if(a=0)
printf("Factorial=1");
else if (a > 0){
for(i=1 ; i<=a ;i++){
b *= i; // don't overwrite value of b with 1
}
printf("Factorial=%d",b);
}
else
printf("FATAL ERROR");
return 0;
}
There are two major issues.
First being your use of if(a=0) which results in assignment in place of comparison which is achieved by if(a==0).
Secondly
for(i=1 ; i<=a ;i++)
{
b = 1;
b *= i;
}
This piece of code is faulty too. You are making b=1 after every iteration which overwrites the intermediate results Hence resulting in incorrect answer. As you have already initialized b to 1 in your code, you do not need this line at all.
for(i=1 ; i<=a ;i++)
{
b *= i;
}
Also it is worth mentioning that the reason you are always getting fatal error is because of what you are doing in the if condition. Due to if(a=0), variable a is assigned value 0 . Hence not satisfying both if and else if conditions and resulting in the execution of else block every time.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm writing a function that tries to get the square of a root.
I guess it's easier with an example:
I want to give a number to that function, say 1024 and the function should tell me 12. So always looking for the x here: 1024 = 2^x.
If I gave 255 to the function it should return 7.
Now I guess my maths is pretty okay, but I get an Error saying I didn't use a Variable in Line 6. Could you have a look?
int log_base2(int num)
{
int x = 2;
int count = 0;
for(; x <= num; x * 2 )
{
count++;
}
return count;
}
Error is in line 6 ( for(....))
for(; x <= num; x * 2 )
Here x * 2 calculates its value, and then throws the result out. What you want is probably:
for(; x <= num; x *= 2 )
The error message is perhaps because the compiler optimizes the variable x away as it's useless.
You are not modifying x anywhere. If you want x to become 2 * x in the next iteration you have to change this
for(; x <= num; x * 2 )
to
for(; x <= num; x = 2 * x )
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
If i have length of 20 2d array
of length 5 integers represented as bits
int bitsval[6];
and the array looks like for example bitsval = {0,0,1,0,1,0}
and i want the decimal value so something like
(2^0 x 0) + ( 2^1 x 1) + (2^2 x 0)... and eventually return the final value as 10
can some one help write a function a function like this
This looks like a homework question, so I'll help, but not give you the code
What you need to do is have a 'total' variable, and a 'current bit worth' variable.
Start with the 'current bit worth' variable equal to 32 (2 ^ 5)
Then, have a loop going through the array, adding the bit worth on to the total if that bit is '1'
Each time you go to the next element in the array you need to half the 'current bit worth' value
[Edit]
OK - if it's not homework, try this:
total = 0;
bitvalue= 32;
for (i = 0; i < 6; i++) {
if (bitsval[i]) total += bitvalue;
bitvalue /= 2;
}
This should work I guess.
#include<math.h>
#include<stdio.h>
void main()
{
int a[]={1,0,0,1,0};
int sum=0;
for(int i=0; i<sizeof(a)/2; i++)
{
if(a[i]==1)
sum+=pow(2,(sizeof(a)/2)-i-1);
}
}
Without going into any kind of binary, and working of off of purely your explanation here is something that should work:
#include <stdio.h>
#include <math.h>
int main(){
int number[6] = {0,0,1,0,1,0}, result = 0;
for (int x = 5; x >= 0; --x){
result += (number[x] * (int) pow(2, 5-x));
}
printf("Final result: %d\n", result);
return 0;
}
You will off course have to massage it to fit