I am a learner and new to C language. While I was creating a function which will give power of two numbers using for loop I encounter that using int declaration before loop starts and also in the loop changes the output of my program. Why is this so?
Code using 'int' declaration once with correct output;
# include<stdio.h>
int main()
{
int x, y;
int r = 1;
int k;
printf("Enter base number:");
scanf("%d", &x);
printf("Enter power");
scanf("%d", &y);
for (k = 1; k <= y; k++)
{
r = r * x;
}
printf("Power is %d", r);
return 0;
}
Correct output:
Enter base number:7
Enter power3
Power is 343
Incorrect code 2:
# include<stdio.h>
int main()
{
int x, y;
int r = 1;
int k;
printf("Enter base number:");
scanf("%d", &x);
printf("Enter power");
scanf("%d", &y);
for (k = 1; k <= y; k++)
{
int r = r * x;
}
printf("Power is %d", r);
return 0;
}
Incorrect output:
Enter base number:7
Enter power3
Power is 1
Can you please tell me why is this so.