# Thread: Plz help with this loop problem,Thanks!

1. ## Plz help with this loop problem,Thanks!

Hi,
Im pretty much a beginner. Encountered this problem while practising
Really appreciate it if you could help=).

Im trying to compute (x^k) using a seperate function.

Code:
1 #include<stdio.h>
2 #include<math.h>
3
4 int main(void)
5
6
7 {
8     double x;
9     int k;
10     double power(double x,int k);
11
12     printf("enter any real no.:\n ");
13     scanf("%lf", &x);
14     printf("enter any non-negative no.:\n");
15     scanf("%i", &k);
16
17     printf("result=%.3f\n",power(x,k));
18     return 0;
19
20
21  }
22
23
24  double power(double x, int k)
25  {
26      double result;
27      int loop;
28      for (loop=1; loop<=k; loop++)
29          result *= x;
30          return result;
31  }
while executing, there is no error msg generated,
However, the output is really huge and obviously wrong.
Have spent the whole afternoon trying to figure out=(.

2. result is not initialized, so it contains random garbage that's multiplied loop times.
If you're using Windows, I would suggest using Visual Studio since it automatically catches these types of errors.

3. problem solved!
thanks Elysia=)

4. ## Hai your code would be...

Following code with Little modification:-

Code:
#include<stdio.h>
#include<math.h>

int main(void)

{
double x;
int k;
double power(double x,int k);

printf("enter any real no.:\n ");
scanf("%lf", &x);
printf("enter any non-negative no.:\n");
scanf("%i", &k);

printf("result=%.3f\n",power(x,k));
return 0;

}

double power(double x, int k)
{
double result=1;
int loop;
for (loop=1; loop<=k; loop++)
result *= x;
return result;
}

5. what a strange indentation you have...

Code:
#include<stdio.h>
#include<math.h>

int main(void)
{
double x;
int k;
double power(double x,int k);

printf("enter any real no.:\n ");
scanf("&#37;lf", &x);
printf("enter any non-negative no.:\n");
scanf("%i", &k);

printf("result=%.3f\n", power(x,k));
return 0;
}

double power(double x, int k)
{
double result=1.0;
int loop;
for (loop=1; loop<=k; loop++)
{
result *= x;
}
return result;
}