Nested function in c? - c

The aim was to implement a c function, that takes two unsingned int n and m and computes the non-negative result m^n. It also said to ignore possible overlows.
So here is the solution given out by the lecturer:
unsigned int power(unsigned int m, unsigned n) {
int power(int x, int y) {
int result = 1;
while(m > 0) {
result *= n;
--m;
}
return result;
}
While i understand the algorithm itself, i fail to get why he chose to use a nested function. And also why there is a curly bracket missing.
I would have simply written something like this:
unsigned int power(unsigned int m, unsigned n) {
int result = 1;
while(m > 0) {
result *= n;
--m;
}
return result;
}
Could somebody please explain, why he chose the nested one and why that's better?

Looks like the int version was a copy/paste left over error: there are no references to either x or y.
unsigned int power(unsigned int m, unsigned n) {
int power(int x, int y) { /* copy/paste left overs */
int result = 1;
while(m > 0) {
result *= n;
--m;
}
return result;
}

Nested functions are not supported in standard C and there is a extension in GNU C which supports it but is not a standard.
The code what you have written is good and there is a mistake in the code your lecturer has given you.
To know about nested functions you can look here:
https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

There is probably a mistake in the solution the lecturer gave you. Your code seems correct.

C language does not support defining functions inside functions. You can however declare a function inside a function.
gcc has an extension that supports nested functions. See this.

Related

How can I deal with compiler error c2660 in recursive function and iterative function?

#include <stdio.h>
double recursive(int n);
double iterative(int n);
int n;
double ans1, ans2;
int main(int n) {
do {
printf("input:");
scanf("%d", &n);
ans1 = recursive(n);
ans2 = iterative(n);
printf("%f", ans1);
printf("%f", ans2);
} while (n != 0);
return 0;
}
double recursive(int n) {
double result = 0.0;
result += (1 / n);
return recursive(n);
}
double iterative(int n) {
int i;
double result = 0.0;
for (i = 0; i < n; i++) {
result += (1 / n);
}
return result;
}
Visual studio says that recursive function and iterative function has c2660 error. I think I used one arguments each when declaring the function and using the function. How can I fix this problem?
The big issue here is in your recursive function. Every recursive function needs a base case. That is, there must be some condition that, when true, does not cause a recursive call. Also, unless that condition is based on some global variable (which is not a good idea), you need to change the parameter(s) with which you call the function as otherwise it'll just do the same thing every time and never reach the base case. As you have it, no call to recursive will ever return since it always ends up calling itself with the same argument.
Without understanding the purpose of the function, it's difficult to know what that condition should be.

Is this factorial function from a C tutorial wrong?

I have a little programming experience in Python, and for the sake of curiosity I started to learn C, at least the very basics. In a tutorial, I found an example function for calculating a factorial, which is this:
int factorial(int x)
{
int i;
for(i=1; i < x; i++)
{
x *= i;
}
return x;
}
I also added these lines in order to see the output:
#include <stdio.h>
int main()
{
int val;
val = factorial(5);
printf("%d\n",val);
return 0;
}
Then I compiled the code with gcc factor.c -o factor.out, run and... ooops, the result is -1899959296, clearly there's something wrong.
After a couple of tries, using printf() to print both i and x, I figured out what went wrong (I think): since the condition of the for loop checks if the counter is less than x, and at each step x gets bigger and bigger, i is always less than x, so the loop keeps going on, presumably stopping when the value of x is too big (which should be related to int, I'm not very familiar yet with the various data types).
So, to "solve" the problem, I rewrote the function like this:
int factorial(int x)
{
int counter = x;
int number = x;
int i;
for (i=1; i < counter; i++)
{
number *= i;
}
return number;
}
I compiled the program, run, and the value printed is 120, which is correct.
I searched a little bit for examples of factorial functions in C, and found many solutions much better than mine, taking into account negative numbers and formats like long and whatnot, but all of them, in a way or another, seem to rely on two "main" variables, much like my solution.
So, the final question: is the example proposed wrong, or am I missing something? This really bothers me, because if such a simple example is blatantly wrong, I should question the credibility of the rest.
Yes, indeed. The original factorial function is wrong for exactly the reason you've identified. You can't use x as both the accumulator and loop limit.
In your version, one improvement I'd suggest is to get rid of counter. Since you're no longer modifying x, you don't need to save off a copy of it.
int factorial(int x)
{
int number = x;
int i;
for (i=1; i < x; i++)
{
number *= i;
}
return number;
}
You could do this without additional variables if you reverse the loop.
int factorial(int x)
{
int i;
for (i = x - 1; i > 1; i--)
{
x *= i;
}
return x;
}
I wouldn't write it this way, though. Modifying an input parameter is poor style.
I think by putting loop condition i<=x and using another variable to store factorial will correct it.
Here is the example:
int factorial(int x)
{
int i;
int fact = 1; //store factorial
for (i = 1; i <= x; i++)
{
fact *= i;
}
return fact;
}
Or you can use recursive function
int factorial(int x) {
if (x == 1)
return 1;
else
return x * factorial(x - 1);
}

factorial of number using argument recursion(as in function call within argument list)

My question is regarding finding factorial of a number by using ternary operator in c. My code below suggests using recursion, in not the function definition, but the argument list. Is this valid in c ?
[Note : 0 factorial is handled by a seperate piece of code]
The function prototype for fact is :
int fact(int);
The definition would be :
int fact(num=(num>1)?num*fact(num-1):1)
{
return num;
}
My question is, just like recursion where a different instance of the same function is called within the function, can it be true for arguments too ?
This is not a valid syntax, the compiler will complain about this because you are writing code implementation inside the argument area. The implementation has to be inside the curly brackets scope that follows the function signature
Example of valid syntax:
long factorial(int n);
// some code
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
Reference: http://www.programmingsimplified.com/c-program-find-factorial
You want this:
int fact(int num)
{
return num > 1 ? num*fact(num-1) : 1;
}
Here are a few ways to do it [they will compile to pretty much the same--except the non-recursive version]:
// this is as close as you can come
int
fact(int num)
{
return ((num>1) ? num*fact(num-1) : 1);
}
// this also works
int
fact(int num)
{
if (num > 1)
num = num * fact(num-1);
return num;
}
// this also works
int
fact(int num)
{
if (num > 1)
num *= fact(num-1);
return num;
}
// non-recursive version
int
fact(int num)
{
int i;
int fac;
fac = 1;
for (i = 2; i <= num; ++i)
fac *= i;
return fac;
}
I should mention that the non-recursive version will execute faster. Ignoring that a large factorial might overflow an int (i.e. long long might be a better choice), try fact(100000000) on a recursive version and you'll most likely segfault due to a stack overflow. But, the non-recursive one will handle that fine.

how to make negative numbers into positive

I am having the negative floating point number as:
a = -0.340515;
to convert this into positive number I used the abs() method as:
a = abs(a);
the result is a = 0.000000;
But I need the result as 0.340515.
Can anyone tell me how to do this.
abs() is for integers only. For floating point, use fabs() (or one of the fabs() line with the correct precision for whatever a actually is)
You have to use: abs() for int fabs() for double fabsf() for float Above function will also work but you can also try something like this.
if(a<0)
{
a=-a;
}
Use float fabsf (float n) for float values.
Use double fabs (double n) for double values.
Use long double fabsl(long double) for long double values.
Use abs(int) for int values.
Well, in mathematics to convert a negative number to a positive number you just need to multiple the negative number by -1;
Then your solution could be like this:
a = a * -1;
or shorter:
a *= -1;
a *= (-1);
problem solved. If there is a smaller solution for a problem, then why you guys going for a complex solution. Please direct people to use the base logic also because then only the people can train their programming logic.
floor a;
floor b;
a = -0.340515;
so what to do?
b = 65565 +a;
a = 65565 -b;
or
if(a < 0){
a = 65565-(65565+a);}
#include <iostream>
using namespace std;
int makePositiveSUM(int a,int b);
int main() {
int t;
cin>>t;
while(t--){
int x,y;
cin>>x>>y;
cout<<makePositiveSUM(x,y)<<endl;
}
return 0;
}
int makePositiveSUM(int a,int b){
if(a>b){
return a-b;
}
else {
return b-a;
}
}
enter code here
enter code here
enter code here
this is the only way i can think of doing it.
//positive to minus
int a = 5; // starting with 5 to become -5
int b = int a * 2; // b = 10
int c = a - b; // c = - 5;
std::cout << c << endl;
//outputs - 5
//minus to positive
int a = -5; starting with -5 to become 5
int b = a * 2;
// b = -10
int c = a + b
// c = 5
std::cout << c << endl;
//outputs 5
Function examples
int b = 0;
int c = 0;
int positiveToNegative (int a) {
int b = a * 2;
int c = a - b;
return c;
}
int negativeToPositive (int a) {
int b = a * 2;
int c = a + b;
return c;
}
Why do you want to use strange hard commands, when you can use:
if(a < 0)
a -= 2a;
The if statement obviously only applies when you aren't sure if the number will be positive or negative.
Otherwise you'll have to use this code:
a = abs(a) // a is an integer
a = fabs(a) // a is declared as a double
a = fabsf(a) // a is declared as a float (C++ 11 is able to use fabs(a) for floats instead of fabs)
To activate C++ 11 (if you are using Code::Blocks, you have to:
Open up Code::Blocks (recommended version: 13.12).
Go to Settings -> Compiler.
Make sure that the compiler you use is GNU GCC Compiler.
Click Compiler Settings, and inside the tab opened click Compiler Flags
Scroll down until you find: Have g++ follow the C++ 11 ISO C++ language standard [-std=c++11]. Check that and then hit OK button.
Restart Code::Blocks and then you are good to go!
After following these steps, you should be able to use fabs(a) for floats instead of fabsf(a), which was used only for C99 or less! (Even C++ 98 could allow you to use fabs instead of fabsf :P)

How to output a float product of int multipliers?

I am trying to calculate the exponent of a number. When I do everything as int I get the correct result, but the output must be float, when I try to convert with %f in printf() I get 0, when I use %d I get the correct result. I cannot change the main() portion of the program, I can only alter the *powerArgs() function. The program input is 3, 5.
Full disclosure, this is part of a school assignment. I am not asking for complete code. I would appreciate a more general answer showing me what I am forgetting, possibly what area I should study more to find the answer myself.
#include <stdio.h>
#include <stdlib.h>
int *powerArgs(int *pA, int *pB);
/* MAIN */
int main(int argc, char **argv)
{
if (argc != 3)
{
printf("?Invalid number of arguments\n");
system("pause");
exit(1);
}
int parmA = atoi(argv[1]);
int parmB = atoi(argv[2]);
int idx;
/* Part C: Raise parmA to the power of parmB. Return pointer to the result */
/* Reset the original values after we print the result */
printf("%d raised to the %d power is %0.1f\n", parmA, parmB, *powerArgs(&parmA, &parmB));
printf("\n");
system("pause");
exit(0);
}
int *powerArgs(int *pA, int *pB)
{
int idx, result = *pA;
for (idx = 1; idx < *pB; idx++)
{
result *= *pA;
}
return &result;
}
float and int convert automatically in C - you can assign either one to the other, and the only thing to watch out for is that if you assign too large a float to an int, then you get undefined behavior (or possibly an unspecified result, I forget. Either way it's not good).
So, your powerArgs function can just be:
float powerArgs(float a, int b) {
// do some stuff and return a value
}
Then you can call it as powerArgs(parmA, parmB), even though parmA is an int.
Edit: if you can't change the call parameters, you can do this instead
float powerArgs(int *a, int *b) {
float base = *a;
int exponent = *b;
...
}
If your professor has really set you code where the function is called as *powerArgs(int *a, int *b), then your professor is a menace. There is no earthly reason why an exponentiation function should return a pointer to a float. There's an ugly workaround you could use:
float *powerArgs(int *a, int *b) {
static float result;
...
result = /* the result of the calculation */;
return &result;
}
The problem with this is, all calls to powerArgs share the same object result. static stops it from ceasing to exist at the end of the call, but the sharing will introduce problems in the long run. It is not good practice to do this, but it might be the best solution to the problem you've been set.
C++ sneaky solution:
struct FloatWrapper {
float value;
float operator*() {
return value;
}
FloatWrapper(float f) : value(f) {}
};
FloatWrapper powerArgs(int *a, int *b) {
...
float result = /* whatever */;
...
return result;
}
This returns an object of class FloatWrapper, by value, and FloatWrapper overloads the * operator. This means that *powerArgs(...) evaluates to the float that the function should have returned by value in the first place, without needing a pointer to any special storage place.
By the way, you might want to check what your function does when parmB is 0.
First, your int *powerArgs(int *pA, int *pB) function returns the address of a local variable, which results in undefined behavior. Use the following instead:
int powerArgs(int *pA, int *pB)
{
int idx, result = *pA;
for (idx = 1; idx < *pB; idx++)
{
result *= *pA;
}
return result;
}
Next, if you want to convert to float, you shouldn't do that in the call to printf(), but rather convert the value to float before the call like so:
printf("%d raised to the %d power is %0.1f\n", parmA, parmB, (float)powerArgs(&parmA, &parmB));
When a function terminates, all its local variables cease to exist (and their addresses point to garbage). To please your teacher who came up with that very awkward interface, you have to find a way to keep an object alive after the function exists.
You have, at least, 3 options:
a) reuse one of the input parameters
b) use a global variable
c) use a static variable
option a)
int *powerArgs(int *pA, int *pB) {
/* calculate */
*pA = CALCULATED_VALUE;
return pA;
}
option b)
int global_power;
int *powerArgs(int *pA, int *pB) {
/* calculate */
global_power = CALCULATED_VALUE;
return &global_power;
}
option c)
int *powerArgs(int *pA, int *pB) {
static int static_power;
/* calculate */
static_power = CALCULATED_VALUE;
return &static_power;
}
Neither of these "solutions" is good; the least bad is option c)

Resources