C K&R 1.7 power function - c

I'm teaching my C with K&R this book, and got confused by the power function from 1.7 example.
Well, when I wrote the code exactly from the example given by the book on Code::Block and ran it, an error occurred: undefined reference to 'power'.
The codes are as follow:
#include <stdio.h>
#include <stdlib.h>
int power(int m, int n);
main ()
{
int i;
for (i = 0; i < 10; ++i)
printf("%d %d %d\n", i, power(2, i), power(-3, i));
return 0;
}
Is power function a predefined function provided by library? Because program above didn't define the body part of power
If so, why did I run into error? Did I include the wrong library?

The error message says that function power is not defined. I am sure that somewhere in the book there is the definition of the function or there is an exercise that requires that you write the function yourself.
It can be written simply. For example for positive n the function can look like
int power(int m, int n)
{
int result = 1;
for ( ; n; --n ) result *= m;
return result;
}
You can modify the function such a way that it would accept negative n.:)
Take into account that it would be much better if the function had return type long long int
For example
long long int power(int m, unsigned int n)
{
long long int result = 1;
for ( ; n; --n ) result *= m;
return result;
}

There is nothing called power() defined in standard C library. If you want a power() function, you have to write your own before using it.
If you want a library function, it is called pow(), defined in math library. Include the header file math.h, without having need to forward define the prototype. Also, don't forget to link against the math library using -lm.

Is power function a predefined function provided by library?
Answer: No. Power function is not predefined.
"Because program above didn't define the body part of power"
I made the same mistake by not checking the next page. See next page,you will find its(power function) definition.
Complete code-
#include <stdio.h>
int power(int m, int n);
/* test power function */
int main(){
int i;
for(i = 0; i < 10; ++i)
printf("%d %2d %3d", i, power(2,i), power(-3,i));
return 0;
}
int power(int base, int n)
{
int i, p;
p=1;
for(i=1;i<=n;++i)
p=p*base;
return p;
}
About error(s):
In my case i tried exactly the same code(except this line#include <stdlib.h>) as yours in geany editor and got-
gcc -Wall -o "pfunc" "pfunc.c" (in directory: /home/anz)
Compilation finished successfully.
if i try to compile from terminal with cc pfunc.c i get error(power undefined)
May be compiler issue? Anyway, im trying know the exact reason. Once i know i will edit.

Related

Integer to Binary Conversion Program Fails for Some Inputs

I wrote code for getting binary form of an integer. It works well for inputs like 1 or 10. However, it is failing for inputs like 256. (It gives 0000000 s output and misses the one).
#include <stdio.h>
#include <math.h>
int number_of_binary_digits_required(int n){
return ceil(log(n))+1;
}
void print_array(int * a, int n){
int i = 0;
for (;i<n;i++){
printf("%d\t", a[i]);
}
}
int main(){
int num = 256;
int binary[100];
int n = number_of_binary_digits_required(num);
int bin_digits = n-1;
while (num){
int temp = num%2;
num = num / 2;
binary[bin_digits] = temp;
//printf("%d\n", bin_digits);
bin_digits--;
}
print_array(binary, n);
//printf("%d", number_of_binary_digits_required(num));
//for(bin_digits = 0;bin_digits < number_of_binary_digits_required(num);bin_digits++)
//printf("%d",binary[bin_digits]);
}
Why is the issue coming and how to resolve it?
Thanks you!
C's log function gives result with a base of e, not 2. This is why some numbers give unexpected result in your program since you calculate using that. There is a function log2 which is what you need i think.
Your use of a logarithmic function to compute the number of digits in conjunction with ceil will suffer due to floating point undershoot.
A more reliable way of calculating the number of binary digits is to divide by two repeatedly until zero is attained.
The first mistake is to use log(n), which calculates log of n base e.
Instead use log2(n)
Hope it helps. :-)

Sum of odd numbers from 1 - 100 using RECURSION in C

Trying to figure out where I am going wrong in this code, I realize I keep getting 1 because that's what am I passing in the function but how else can I do this?
#include <stdio.h>
#include <stdlib.h>
int totalOdd();
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int n){
int odd = n;
if(odd >= 100){
return 0;
}
else{
totalOdd(odd+2);
}
return odd;
}
try this one
one :
#include <stdio.h>
#include <stdlib.h>
int totalOdd(int);
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int n)
{
int odd = n;
if(odd > 100){
return 0;
}
else{
return (n+totalOdd(odd+2));
}
}
in your code , addition was missing
#include <stdio.h>
#include <stdlib.h>
int totalOdd();
int main(){
printf("%d\n",totalOdd(1));
}
int totalOdd(int odd){
if(odd >= 100)
return 0;
return (odd + totalOdd(odd + 2));
}
Not a complete answer, because this sounds like homework, but here’s an example of how to write a very similar function, first recursively, and then a more efficient tail-recursive solution.
#include <stdio.h>
#include <stdlib.h>
unsigned long factorial1(const unsigned long n)
{
/* The naive implementation. */
if ( n <= 1U )
return 1; // 0! is the nullary product, 1.
else
return n*factorial1(n-1);
/* Notice that there is one more operation after the call to
* factorial1() above: a multiplication. Most compilers need to keep
* all the intermediate results on the stack and do all the multiplic-
* ations after factorial1(1) returns.
*/
}
static unsigned long factorial_helper( const unsigned long n,
const unsigned long accumulator )
{
/* Most compilers should be able to optimize this tail-recursive version
* into faster code.
*/
if ( n <= 1U )
return accumulator;
else
return factorial_helper( n-1, n*accumulator );
/* Notice that the return value is simply another call to the same function.
* This pattern is called tail-recursion, and is as efficient as iterative
* code (like a for loop).
*/
}
unsigned long factorial2(const unsigned long n)
{
return factorial_helper( n, 1U );
}
int main(void)
{
printf( "%lu = %lu\n", factorial1(10), factorial2(10) );
return EXIT_SUCCESS;
}
Examining the output of both gcc -O -S and clang -O -S on the above code, I see that in practice, clang 3.8.1 can compile both versions to the same optimized loop, and gcc 6.2.0 does not optimize for tail recursion on either, but there are compilers where it would make a difference.
For future reference, you wouldn’t solve this specific problem this way in the real world, but you will use this pattern for other things, especially in functional programming. There is a closed-form solution to the sum of odd numbers in a range. You can use that to get the answer in constant time. You want to look for those whenever possible! Hint: it is the sum, from i = 0 to 100, of 2 i + 1. Do you remember a closed-form formula for the sum of i from 0 to N? 0, 1, 3, 6, 10, 15, ...? The proof is often taught as an example of a proof by induction. And what happens to a sum from 0 to N when you multiply and add by constants?
As for my example, when I have had to compute a factorial function in a real program, it was for the purpose of computing a probability distribution (specifically, the Poisson distribution) for a simulation, and I needed to calculate the factorial of the same numbers repeatedly. Therefore, what I did was store a list of all the factorials I’d already calculated, and look up any number I saw again in that list. That pattern is called memoization.

Can someone please clarify this code?

I have a doubt in the very basics of C .
I have written the following code. Here in the add() function, I'm not returning anything and so I expected that the output will be some junk value or something, but it didn't happen like that. Can anyone explain to me why it was happening like that? Please excuse me if I have written something wrong in the code.
To my understanding, I thought the memory for variable add1 will be from stack and hence once the add() is done , all the memory allocated will be freed, thus some junk value will be displayed.
My clear doubt is without returning anything, how can it print the correct value?
Code sample:
main() {
int x = 4, sum;
int n;
printf(" enter a number \n");
scanf("%d", &n);
sum = add(x, n);
printf(" total sum = %d\n", sum);
}
add(int x, int n) {
int add1 = 0;
add1 = x + n;
//return(add1);
}
This is undefined behavior.
When you don't specify what a function returns, it will default to int. Then when you don't have a return statement, it will be undefined what happens. So in principle anything may happen.
For gcc, it will on many system just return some "random" value. In your case it just happens to be the sum. Simply by "luck".
Always turn warnings on during compilation, e.g. gcc -Wall and always treat warnings as if they were errors.
Your code should look something like:
#include <stdio.h>
int add(int x,int n); // Corrected
int main(void) // Corrected
{
int x=4,sum;
int n;
printf(" enter a number \n");
scanf("%d",&n);
sum = add(x,n);
printf(" total sum = %d\n",sum);
return 0; // Corrected
}
int add(int x,int n) // Corrected
{
int add1=0;
add1 = x+n;
return add1; // Removed the // to uncomment and removed unnecessary ()
}
As stated before, this is undefined behavior, and you shouldn't rely upon it.
However, there is some logic behind what is going on. The return value for a function is, by convention, stored in the eax register on x86, or the rax register on x86_64. It just happens that your compiler is also using the eax or rax register for storing the calculated value. Also, since the return type of add() is not specified, it is implicitly defined as int.

redefinition of ‘main’

As I am new to programming, I was trying to write a simple code using functions which will give me the addition of three numbers. Here's the code!
/* Your includes go here */
#include <stdio.h>
int addThreeNumbers(int a, int b, int c)
{
int d;
d = a + b + c;
return(d);
/* Complete this function only
DO NOT write main function.
*/
}
int main()
{
int x, y, z, sum;
printf("Enter the three numbers: ");
scanf(" %d %d %d", &x, &y, &z);
sum = addThreeNumbers(x, y, z);
printf("The sum is %d", sum);
return 0;
}
And the error was as follows:
solution.c:30:5: error: redefinition of ‘main’
solution.c:15:9: note: previous definition of ‘main’ was here
You have another main function in the code somewhere. Post the complete code and I will take a closer look. But that is the only way you can receive this error
In modern C, empty argument parentheses mean that the type and number of arguments is unknown.
Although this segment runs fine with most compilers, yours might be picky. Try declaring main with zero arguments explicitly, like this:
int main(void) {
//code
}
Pretty sure this is one of the online coding sites' question. They put in the main function themselves by appending it to the code, you don't have to explicitly write it. Delete the main function you have written and check if that works out.

C language cygwin compiler, not sure why this is happening

My job is to prove fermats theory incorrect using c. so what i did was have nested loops, its pretty easy to read.
here is the code:
#include <stdio.h>
#include <math.h>
quadtest(unsigned long long int a, unsigned long long int b, unsigned long long int c, unsigned int n)
{
if ((pow(a,n)+pow(b,n))==pow(c,n))
return 1;
else
return 0;
}
main()
{
unsigned long long int a;
unsigned long long int b;
unsigned long long int c;
unsigned int n;
//a=1; b=1; c=1; n=1;
for(n=2; n<100; n++)
{
printf("\nn=%d",n);
for(c=1; c<500; c++)
{
printf("\ntrying now c=%d and n=%d",c,n);
for(b=1; b<500; b++)
{
if (quadtest(a,b,c,n)) break;
//printf("\nb=%d, n=%d",b,n);
}
for(a=1; a<500; a++)
{
if (quadtest(a,b,c,n)) break;
//printf("\na=%d, n=%d",a,n);
}
}
printf("\nthe right values to prove fermats theory wrong are n=%d,c=%d,b=%d,a=%d",n,c,b,a);
}
}
after being compiled, im getting "trying c=random number, n=0. n always equals 0 for some reason even though its never supposed to be 0.
im also getting something like "the right values to prove fermats theory wrong are n=99,c=500,b=0,a=500"
which once again, neither a, b, c, or n are supposed to be 0. not sure what the problem is
There are two clear problems with your code:
You define several variables, and each is initialised except for a. You call a function using a uninitialised. This is undefined behaviour and could explain your problem.
Secondly, you are using the incorrect specifier in printf. %d is used for int; %llu is for unsigned long long. Using the wrong specifier can lead to incorrect values being output.

Resources