We have a little bit of oopsidaisies. As laserlight said, you want to pass the address of x and n. (That let's scanf modify their values). I did the simplest fix on your loop (and then had to remove the semicolon because it was an infinite loop otherwise). I came up with
Code:
#include <stdio.h>
int main()
{
int x,n,ans;
printf("input two positive values\n");
scanf("%d" "%d",&x,&n);
ans=x;
while(n>0)
{
ans=ans*x;
n=n--;
}
printf("%d\n",ans);
}
And I ran it:
Code:
input two positive values
2 3
16
Oopsies. Change line 7 to read ans = 1;
Code:
#include <stdio.h>
int main()
{
int x,n,ans;
printf("input two positive values\n");
scanf("%d" "%d",&x,&n);
ans=1;
while(n>0)
{
ans=ans*x;
n=n--;
}
printf("%d\n",ans);
}
Prior to that your code was computing x^(n+1). I have some more thoughts. One, this isn't recursive, it's actually iterative. So when you turn it in it will compute correctly and still be wrong because it's not what they asked for. I won't post the code of the solution, but take it as a hint that there is an inductive definition of power(a, b):
power(a, 0) = 1
power(a, n) = a * power(a, n-1)
Second, do you understand now how scanf works? The idea is you put in a format string, then you follow that with a list of the references of the variables you would like to put the read values into. So let's say I'd like to read an int and then a string:
scanf("%d %s", &myInt, myStr); // myStr is a reference already, so &myStr would be wrong, in fact it will seg fault:
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
char str = malloc(sizeof(char)*16);
scanf("%d %s", &x, &str); // Oops, wrong to take address of str as str is already and address
printf("%d, %s", x, str);
free(str);
}
Output:
Code:
./a.out
2 34lk
Segmentation fault
Reason why: scanf will attempt to write the string I enter into a pointer value which is wrong, because it's not in my address space:
Code:
valgrind ./a.out
==2378== Invalid read of size 1
==2378== at 0x4E777AA: vfprintf (vfprintf.c:1614)
==2378== by 0x4E7E6F9: printf (printf.c:35)
==2378== by 0x400643: main (foo.c:9)
==2378== Address 0x68 is not stack'd, malloc'd or (recently) free'd
==2378==
==2378==
==2378== Process terminating with default action of signal 11 (SIGSEGV)
==2378== Access not within mapped region at address 0x68
==2378== at 0x4E777AA: vfprintf (vfprintf.c:1614)
==2378== by 0x4E7E6F9: printf (printf.c:35)
==2378== by 0x400643: main (foo.c:9)