Oh i am going to explain step by step when you explain me why your main receives an agrument ?main is supposed to get no arguments or it can get two arguments to handle command line but let this for now.So declare the variable n and switch main to void like this
Code:
int main(void)
{unsigned int n;
....
}
A suggestion i have to make is that in most cases the prototypes of the functions are before main(declaration),then comes the main and then there are the definition of the functions.For instance
Code:
int foo(void);/*declaration*/
void bla(int n);/*declaration too*/
int main(void)
{
...
return 0;
}
int foo(void)/*definition*/
{
/*body of the function*/
}
void bla(int n)/*definition*/
{
/*body of the function*/
}
Also i would suggest you to read the input,with scanf,before passing n as an argument.In code
Code:
int foo(int n);
int main(void)
{
printf("calculate n(log2n)\n");
printf("Type your number:\n");
scanf("%d", &n);
foo(n);
...
return 0;
}
int foo(int n)
{
...
}
The goal is to have tiny functions that two one job.This way you give your program a real boost(escpecially when its large).
Actually you could even create a function that read the data!And why not another one that would print the result?Let foo be the function that does all the computations..Check this example
Code:
#include<stdio.h>
int input(int n);
int foo(int n);
int main(void)
{
int n;
int result;
n=input(n);
result=foo(n);
print(result);
return 0;
}
int input(int n)
{
printf("calculate n(log2n)\n");
printf("Type your number:\n");
scanf("%d", &n);
return n;
}
int foo(int n)
{
int m;
int logn = -1;
for (m = n; m>0; m = m>>1 ) logn++;
if (logn == -1) {
printf("ERROR: Zero and Negative number is illegal, undefined.\n");
exit(1); /*i do not like this.you may write return -1
and have in mind to check in main if the functions returns -1.If so then an error has occured(actually logn is equal to -1)
}
return logn;
}
int print(int n)
{
printf("log2 is %d\n", k);
}
and actually i think that is a nice idea to split the input function in two functions.One that print the welcome messages and another that actually reads the data!
Code:
void printWelcomeMessages(void)
{
printf("calculate n(log2n)\n");
printf("Type your number:\n");
}
int input(int n)
{
scanf("%d", &n);
return n;
}
int getInput(int n)
{
printWelcomeMessages();
return input(n);
}
Also i have to display an example about the return -1 thing i told(i suggest you to use it instead of exit(1)).One reason that comes to mind,is that in my way you are able to handle the error your own
Code:
#include <stdio.h>
int input(int n);
int getInput(int n);
int main(void)
{
int n;
/*Let's say that you want to have a positive variable n*/
printf("Please,input a positive number\n");
if(getInput(n) == -1 )
{
/*do error handle here*/
printf("Number is going to set to zero.\n");
n=0;
}
return 0;
}
int getInput(int n)
{
n=input(n);
if(n<=0)
{
return -1;
}
else
{
return n;
}
}