#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
printf("Enter number :-");
scanf("%d" , &num);
int D = 2 ;
while(D > 1)
{
int denom ;
denom = (num%D);
if(denom == 0)
{
break;
}
D++;
}
printf("GCD of your input is %d" , D);
}
What this program is all about?
Basically, I am trying to divide the user input by an already stored number. If the remainder (denom
) is 0 then the loop will break and the printf
call will be executed. Otherwise, the already stored number will be increased by 1, and the process continues until the remainder is 0.
What is my problem?
My problem is that if I declare num
inside the loop then I get an error saying “num undeclared”. If I declare it before the loop then the program works perfectly.
Why is this happening?
13
C identifiers are valid from the point they were defined (or declared) to the end of the enclosing block. Something like the “drawing” below.
#include <stdio.h>
#include <stdlib.h>
int main()
{ // valid identifiers
int num; // num enclosing block |
printf("Enter number :-"); // num |
scanf("%d" , &num); // num |
int D = 2 ; // num D |
while(D > 1) // num D |
{ // num D |
int denom ; // num D denom | |
denom = (num%D); // num D denom | |
if(denom == 0) // num D denom | |
{ // num D denom | |
break; // num D denom | |
} // num D denom | |
D++; // num D denom | |
} // num <------/ |
printf("GCD of your input is %d" , D); // num |
} // <--------------------/