When I compile this simple code the output is the above error.
So how to declare finalTotal outside while loop?
while (total<endn)
{
int finalTotal = (total + total/3 - total/4);
}
printf("no of years is %i\n", finalTotal)
NOTE:total and endn are part of the total code but not necessary for the question.
You can simply move the declaration of finalTotal as an int to before the loop.
int finalTotal = 0; // declare and initialize to 0 in case while loop does not run
while (total<endn)
{
finalTotal = (total + total/3 - total/4);
}
printf("no of years is %i\n", finalTotal)
This does look like an infinite loop though, as neither total nor endn seems to change.
You need to read up on scope. Variables can only be accessed within their scope. Since you declare int finalTotal inside of the while loop, only other statements inside of the while loop can access it.
Instead you need to declare your variable in the outer scope, so that the following printf can access it.
For example:
int finalTotal; // Declared outside of the while loop.
// You may want to consider initializing it
// with some value in case the while-loop
// never executes. (Such as -1 or something
// to signal an invalid number of years).
while (total<endn) // NOTE: This may infinite loop. Perhaps a typo?
{
// This scope has access to `finalTotal` since it was declared
// by an outer scope.
finalTotal = (total + total/3 - total/4);
}
// Now `finalTotal` can be accessed here, since it's within the same
// level of scope and not stuck inside the scope of the while-loop
// curly braces.
printf("no of years is %i\n", finalTotal)
As mentioned by others, another problem is that the while loop may never terminate since total and endn are not changing inside of the while loop. So it will potentially iterate forever.
Perhaps this was intended to be while (finalTotal < endn).
Related
I want to create a recursive function "rec" which is given a variable "var".
The variable is then used in a calculation like
var = 3 * var
the function is then supposed to call itself
to repeat that process.
But now i only want that process repeated a certain number of times
for Example the recursion is supposed to repeat itself 12 times.
How do i do that.
I tried using a new variable "i" that would be incremented each recursion.
after the 12th recursion the function should return the variable "var" and not call itself again.
This did not work though, the function "rec" just returned the value it was given without actually looping or incrementing i.
Is the solution with new variable "i" even valid or did i just somehow mess it up.
if it is not doable that way, are there any other solutions to define how deep the recursion should go?
(i know that doing this process with a loop is easier but i want to understand
recursion a bit more and understand why this doesnt work.)
Exemplementary codeCODE:
int rec(int var){
int i = 0;
if(i = 12){
return var;
}else{
i++;
if(i % 2 == 0){
var = 3 * var;
}
}
return rec(var);
}
This question already has answers here:
For Loops and stopping conditions
(4 answers)
Closed 2 years ago.
While studying for my exam I saw a question which is as shown below can someone please explain to me that does the ';' means at the end of the for loop and can I also put it in a while loop? And what is the difference between the Compile-time error and the Compilation error?
#include <stdio.h>
int main(){
int value;
for ( value = 1; value <= 15; value+=3);{
printf("%d", value);
}
return 0;
}
This is probably a mistake; it is syntactically correct, but actually would be read by the compiler like this:
for (value = 1; value <= 15; value+=3);
// Unrelated block!
{
printf("%d", value);
}
This means that the loop will execute, then run four more times, but not actually do anything, then the block will execute once.
Where the loop and the block following it are completely separate and unrelated.
The semicolon ; terminates the definition of the loop body. In this case there are no statements in the body of the loop, hence the only affect of the loop is to modify the value of the counter variable, value.
The statement following the semicolon has it's own scope thanks to the curly braces, but it has no real affect in this case.
The printed result will be the value of value after the (empty) loop has executed, i.e. 16.
You could not do the same with a while loop because the variable would need to be incremented within the body of the loop and the value tested at each iteration to decide whether to continue looping.
Of course, you could avoid any loop by initialising value to 16.
I am in process of rewriting my CS50 credit solution to use functions.
Stumbled upon error when defining readCardNumber().
long long readCardNumber()
{
do
{
long long result = get_long_long("Enter card number to verify: \n");
if (result < 0)
{
printf("Retry: \n");
}
}
while (result < 0);
return result;
}
I am using the CS50.h https://reference.cs50.net/cs50/get_long_long to get number. I cannot compile this solution because of :
error: use of undeclared identifier 'result'
Can someone experienced please explain whats the issue here? I did declare function at beginning of my code and declared and initialised result in function.
What would be a better way to validate that number?
https://docs.cs50.net/2018/x/psets/1/credit/credit.html - Spec for solution I am trying to rework.
The result variable is declared inside of the do...while block. It is not visible outside of the block, which includes the condition of the while.
You need to move the variable definition outside of the loop:
long long result;
do
{
result = get_long_long("Enter card number to verify: \n");
if (result < 0)
{
printf("Retry: \n");
}
}
while (result < 0);
It is a matter of scopes. In C, a scope is defined by { and }. A variable ceases to exist at end of the scope it is declared within. (Well, static variables don't but they get unaccessible. Unless you have pointers to them.)
What you need to do is to move the declaration outside the loop.
I do however want to emphasize that it is a VERY good practice to declare variables within the scope that they are used. It reduces the risk of bugs significantly. If a variable is only used inside a loop, then declare it inside the loop. It is basically the same reason as why you should not use globals unless necessary.
You do return result; when result is out of scope. But your code contains redundancy: you test result < 0 twice. I would recommend changing the structure to avoid this, with bonus side-effect of fixing the original problem:
long long readCardNumber(void)
{
for (;;)
{
long long result = get_long_long("Enter card number to verify: \n");
if (result >= 0)
return result;
printf("Retry: \n");
}
}
This is one of those inconvenient or even "unnatural" things about do/while statement: everything you declare inside the cycle body will not be visible to the condition in the while portion of the statement. The scope of those identifiers ends at the } before the while portion.
This often forces the user to declare the variable(s) before the cycle
long long result;
do
{
result = get_long_long("Enter card number to verify: \n");
if (result < 0)
printf("Retry: \n");
}
while (result < 0);
The price to pay for this solution is
unnecessary extension of result's scope beyond the cycle
it is no longer possible to meaningfully initialize the variable at the point of declaration
For many of us this is so unpleasant that we prefer to switch to the do/while(1) approach with break in the middle to terminate the cycle
do
{
long long result = get_long_long("Enter card number to verify: \n");
if (result >= 0)
break;
printf("Retry: \n");
}
while (1);
This is also not perfect, obviously. Chose for yourself, which approach you like better.
In the latter case do/while(1) serves as an "idiomatic" way to express a cycle with exit from the middle. Other people might prefer for (;;) or while(1) for that purpose, thus avoiding do/while statement altogether.
What is the difference when we declare variable before using in loop and when define variable in loop.
I am talking about this situation
int i;
for(i=0; i<100; i++);
and
for(int i=0; i<100; i++);
In the former case, you can access i outside the for-loop. This can be advantageous if you have a conditional break in your loop, for example:
int i = 0;
for (i = 0; i < 100; i++) {
if (someUnexpectedConditionHappens()) {
break;
}
// do something
}
printf("The loop has been executed %d times", i);
In the first case it is supposed that variable i will be used also after the loop as for example
int i;
for(i=0; i<100; i++);
printf( "i = %d\n", i );
Nevertheless it would be much better to write the following way
int i = 0;
for( ; i<100; i++);
printf( "i = %d\n", i );
In this case we will get a valid readable code without a need to bother what is done within the loop as for example
int i = 0;
/* some loop used i */
printf( "i = %d\n", i );
That is even if the variable will not be changed (assigned) in the loop or in some other code instead of the loop (usually each code has a tendency to be changed) nevertheless we will get a valid result.
In the second case it is supposed that variable i will be used only within the loop
for(int i=0; i<100; i++);
We need not its value outside the loop. So in this case the life of the variable is limited by the body of the loop. Outside the loop it will be invisible and not alive.
It's the "scope". In the second case, you can only use the variable within the for loop. In the first case - in the entire containing block.
In the first case, i can be accessed outside the loop within the current block. In C89, you cannot declare variables in the loop so you'll have to stick to this method.
In the second case, i cannot be accessed outside the loop. Declaring variables in the loop is a C99 feature.
When you do it before the loop, the variable is then available outside the loop as well.
Whereas when you do it inside it, it is a local variable that can only be used inside the loop.
Also, you can declare a variable inside a loop when using C99 standard. But it does not work for example for C90. So be careful with that.
In the first case, i is accessible outside the for loop.
In the second case, the scope of i is restricted to the for loop body.
Arguably the second case gives you better program stability since the use of i outside the for loop is often unintentional.
In the below code, variable i has been declared globally as well as locally in the for loop . Due to high precedence of local variable, i will be initialized with the value 10 . But in the first occurrence of the loop, due to i++in the for loop, value of i will become 11, so should it not exit the loop after the first instance only?
#include<stdio.h>
int main(){
int i;
for(i=0;i<5;i++){
int i=10;
printf(" %d",i);
i++;
}
return 0;
}
P.S: The answer is 10 10 10 10 10
Precedence is not just about initialization. The variable i inside the loop body is a different variable from the one outside. It "shadows" the outer i, making it inaccessible in the loop body.
The loop control statement is outside the loop body. Its i is the outer i, and nothing done to the inner i has any effect on it, so it starts at 0 and counts up to 5. At each loop iteration, the inner i is re-initialized to 10, and that's the one that gets printed.
The reason it always prints is because the inner i shadows the outer i. For the same reason the i++; inside the loop increments the inner i, not the i that's used as the for loop counter.
But the i that controls the loop gets incremented after the scope of the inner i is over and has no relation to i++; done inside the loop. It's completely independent of the inner i and thus the loop runs 5 times.
GCC provides an option to warn about such shadowing: -Wshadow.
Yet another answer because there is one aspect missing so far. If you change your code slightly:
#include<stdio.h>
int main(){
int i;
for(i=0;i<5;i++){
static int i=10;
printf(" %d",i);
i++;
}
return 0;
}
You will get a more "expected" result:
10 11 12 13 14
A variable inside a block stops to exist after the block (read: pair of curly braces) is left (and it is left here after every step to execute the control statements of for) ... so with your original code, you get a new inner i each time. Declaring the inner i static still doesn't change the scope (it is only visible inside the loop body), but makes the variable survive and still be available when the same block is entered again.
Yes the answer is correct.
As loop iterates 5 times and for every iteration i inside loop is set to 10 and outer one is overshadowed by inner one. After i=10 its value is printed therefore 5 times 10 is output.