Can anyone help me understand what's wrong with this code? [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
int m[1000]; //declaring global array
int added(int input){
for(int i=1;i<= input; i++){
if(i>0 && input % 2) // checking if the numbers are even...
m[i]= input; //array implementation
return m[i];
}
}
int main()
{
for(int j=2;j<54;j++){
printf("%d",m[i]);
putchar('\n');
}
return 0;
}
I'm trying to return array from a function. why isn't it working?
Implemented array in for loop.

Your main function has a for loop iterating on a variable called j, but the body of the loop is trying to use an undefined variable called i.
Your main function also never even calls your added() function.
Moreover, your added() function is kind of problematic too.
int added(int input){
for(int i=1;i<= input; i++){
if(i>0 && input % 2) // checking if the numbers are even...
m[i]= input; //array implementation
return m[i];
}
}
I code in several different languages, so I'm not sure if this is actually an issue here or not, but your return statement is within a for loop. In many languages, this won't compile because your added() function doesn't have a return statement for every possible execution path. What happens if you send added() an argument <1? added(0) or any negative int will never enter the for loop, so added() gets to the end of the function without a return statement.
Moreover, with your return within the for loop and outside the if statement, you're guaranteed to only return the result of the first for loop, so you may as well just do a nested if statement or something.
Then there's your if statement. if(i>0 && input % 2). The && returns true when both halves also return true (and that's the only time your if statement is executed). In this case, i>0 returns true every time i is a non-zero positive integer. No problem here. Meanwhile, input % 2 doesn't return a boolean. It will return an int, and in this case, it will return 0 or 1. It will return 0 on even numbers and 1 on odd numbers. And as it turns out, the integer 0 is evaluated as a boolean false here and non-zero integers are evaluated as boolean true so this is probably doing the opposite of what you want. You need to change input % 2 to ((input % 2) == 0) probably.
And finally, if m[] is declared globably, you don't actually need to return anything. main() and added() can both see the variable perfectly fine. You can modify your function to look like this:
void added(int input){
for(int i=1;i<= input; i++){
if(/*i will always be >0 in this for loop*/(input % 2) == 0)
m[i]= input;
}
return;
}
Then all you have to do is actually call added() from main and it will correctly modify the array.

You use i in main but you meant to use j, I suspect.

You are not returning an array from added(), you are returning an element m[1] from the array. The function will return m[1] at the first iteration of the for loop.
At the first iteration of the for loop i = 1, so m[1] will be whatever the input is and the function will return m[1] at return m[1].
Another problem in main(), you are using m[i] but i is not defined in main().

You never called added, you never initialized int m[1000]; hence by default the entire array has 0 - you are indexing with i in main instead of j. Return is inside the for loop.

Related

Do while loop not working inside a function in C [duplicate]

In the following code, would anything be returned?
#include <stdio.h>
int try_this (int in);
int main (void)
{
try_this (5);
}
int try_this (int in)
{
int i = 1;
for (i = 0; i < in; i = i + 2) {
return i;
}
return i;
}
Since there's a return in the for loop, would the code just return nothing since there's nothing after the function is called? Or would i be returned as a number, like 1(because of the declaration in try_this) or 6(because of the loop)?
Thank you!!:)
When the first return statement is encountered, the function will return. It's easy to see that the function will start the loop and while i=0 it will return i. So each time you call try_this you'll get 0
Also, return 0; from main...
When you enter the for loop for the first time, i is 0 and less than the 5. Then it execute the statement return i; in for loop, which will finish executing the try_this() funciton.
What you are basically asking is that if the function will return something even though there is no code after the function call.
The answer is yes, it will return. It doesn't matter if there is code later or not. The function will return (in this case 0) It's just that there's nobody to catch it.
The function try_this() always returns 0:
i is initially set to 1
then i is set to 0 in the initial clause of the for statement
if i < in, the loop body is executed and the value of i is returned, namely 0.
otherwise the loop is skipped and the next statement is return i; so 0 is returned too.
Regarding the main function: it ignores the return value of try_this(5) and reaches the end of its body without a return statement. This is bad style and would trigger undefined behavior for any other function, but since C99 the behavior is defined as a special case for the main function and the value 0 is returned to the startup code, which exits back to the system with a termination status of 0, which means successful execution.
if you want to store the value of 'I' i would recommend you to use "while loop"
int i = 0;
while(i < in)
{
i++;
}

While performing recursion why the last number is getting added twice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
While performing recursion to find the sum of first 25 natural numbers, to see which all numbers getting added I used printf to see but it shows 25 only once.
#include <stdio.h>
int sum_of_numbers(int);
int main(){
int sum, num1 = 1;
sum = sum_of_numbers(num1);
printf("\nSum of first 25 natural numbers is %d.", sum);
}
int sum_of_numbers(int n1){
int sum;
if(n1 <= 25){
printf("%d ", n1);
sum = n1 + sum_of_numbers(++n1);
}
else
return 0;
}
Let's begin by looking at this function:
int sum_of_numbers(int n1){
int sum;
if(n1 <= 25){
printf("%d ", n1);
sum = n1 + sum_of_numbers(++n1);
}
else
return 0;
}
For the moment, ignore the fact that this is a recursive function. In fact, let's replace the recursive call with one that isn't recursive:
int sum_of_numbers(int n1){
int sum;
if(n1 <= 25){
printf("%d ", n1);
sum = n1 + some_other_mystery_function(++n1);
}
else
return 0;
}
Based on experience, when you're first learning recursion, it's often helpful to pretend the recursive calls are to different functions. Many errors in recursion are really simpler errors in function call and return that get overlooked because you're focusing too much on the recursive bit.
With that change made - do you notice anything unusual about this function? Specifically, what value gets returned if you pass in a value n1 that's less than or equal to 25? In that case, the function reaches the end without ever returning anything. Specifically, we enter the if statement, execute the printf, make the call to some_other_mystery_function, then fall off the end of the function with nothing returned. In C, that's undefined behavior, and the value that gets returned is essentially up to the whim of the compiler, the OS, and the alignment of the planets.
This leads to general transferable skill 1: make sure, when writing recursive functions, that you always return a value. That's true about most functions, but especially in the case of recursion.
There's also something else a bit suspicious here. Notice that you set the sum variable equal to some value, but sum is a local variable that's never referenced later in the function. That should trigger some alarm bells - why are we setting a local variable without reading it?
I think what you meant was something more like this:
int sum_of_numbers(int n1){
if(n1 <= 25){
printf("%d ", n1);
return n1 + some_other_mystery_function(++n1);
}
else
return 0;
}
This always returns a value, and never writes to a local variable that isn't read.
There's another issue here, though. Look at this line:
return n1 + some_other_mystery_function(++n1);
Here, you're reading from n1 at one point in the expression, and writing ++n1 in another. That's a Bad Thing, because there isn't a way to guarantee whether the first use of n1 evaluates to "what n1 used to be before the ++n1 was evaluated" or "the new value of n1 after we did ++n1." Then again, notice that this statement is a return statement, so after this line executes there's never going to be another chance to touch n1 again. I think you meant something like this?
return n1 + some_other_mystery_function(n1 + 1);
This more clearly means "pass n1 + 1 as the argument to the function."
That leads to general, transferable skill number 2: avoid using ++, +=, -=, etc. as parameters to functions. In some cases this will work correctly, but in many cases it introduces errors. Instead, pass value + 1, value + 137, value - 271, etc.
And finally, transferable skill number 3 - the compiler can warn you about all of these issues. Most compilers these days, when you crank the warning settings up, will warn you about writing to local variables that aren't read, or falling off the end of a function without returning anything, or incrementing a variable used elsewhere in an expression. I would recommend enabling those settings, since that would likely have tipped you off that something wasn't quite right here. You might not have understood what the warnings were all about, and that's fine! If that happens, feel free to post your code and the warning message in a separate question on the site, and other folks can take a look at it.
Two problems.
In the event n is less than or equal to 25, you never explicitly return. This can cause weird things to happen.
Also, there's no reason to use ++n1 in this case when you can just use n1 + 1 since you're passing by value. The ++ operators can be useful, but the prefix ++ isn't doing what you probably think it is in this case.
First of all, you are not returning the value from the body of the recursive function, though my GNU g++ compiler is not complaining about it and doing the work, but you cannot assume it to work.
Second, you are incrementing the variable ++n1 which is also increasing the value for n1 in the calling statement. So what you are actually doing is adding 2 to 26, not 1 to 25. You can use n1 + 1 instead, you don't need to change the variable and you should not. You can change your code to following to address the issues:
#include <stdio.h>
int sum_of_numbers(int);
int main() {
int sum, num1 = 1;
sum = sum_of_numbers(num1);
printf("\nSum of first 25 natural numbers is %d.", sum);
}
int sum_of_numbers(int n1){
int sum;
if (n1 <= 25) {
printf("%d ", n1);
sum = n1 + sum_of_numbers(n1 + 1);
return sum;
}
else {
return 0;
}
}

C - return value at index: control reaches end of non-void function

First of all: I just recently started programming in C (my first programming language) and this may be a stupid/simple question, but I was trying to implement a function which returns the value at index in an array/list. I always get this error from the compiler: "error: compiler reaches end of non-void function" even though I am returning values of type int. Thanks in advance:
int list_get(int list[], int length, int index) {
if(index <= CAPACITY){
for(int i = 0; i <= CAPACITY; i++){
if(i == index)
return list[i];
}
}
else{
printf("Index is out of range. \n");
return 0;
}
}
The compiler sees, both the return statements are under some sort of conditional block, so it tries to warn you. Nothing wrong, as such.
Consider the flow,
index <= CAPACITY is true,
for none of the iterations, i == index is true.
for loop is exited.
In that case, there's nothing to be returned....
To avoid, just move the return 0; statement out of else block. be aware of the possible side effect, if i == index check fails, it will return 0.
For starters the function does not make sense. The parameter length is not used within the function. Also there is no need to include a loop that to check that index is less than or equal to the magic value CAPACITY.
The compiler issues a message because it is unable to determine that this condition
if(i == index)
will be always true provided that this condition
if(index <= CAPACITY){
is also true.
Also it is not clear how to distinguish 0 from a valid value in the array at the index.
your else statement is out of for loop.so when your for loop exits it execute statement of else and there you have written "return 0". so it won't return any value.

C program for calculating factorial

i have written a small function which calculates factorial for a number in C
as follows:
int factNnumbers(int n)
{
if(n == 1)
return 1;
else
return (n*factNnumbers(--n));
}
I call the function shown above as:
factNnumbers(takeInputN());
where the function to take the input (takeInputN) is defined as:
int takeInputN()
{
int n;
printf("\n\nHow many numbers ?? \n ");
scanf("%d", &n);
return n;
}
If I change one line in my factorial code as shown below , my program works perfectly. Otherwise with the above code it prints the factorial of the number input -1 (example if number input is 5, it will print the factorial of 4). Why is this happening?.
int factNnumbers(int n)
{
if(n != 1)
return (n * factNnumbers(--n));
}
The problem is that you're both reading and modifying n in the same expression:
n * factNumbers(--n)
The evaluation of the n argument to * and of the --n subexpression are unsequenced, which gives your code Undefined Behaviour.
The easiest solution (and also, IMO, more expressive), is to say n - 1 where you mean it:
n * factNumbers(n - 1)
Your "improved" code in the bottom of the question is actually even more wrong. There, you have a control path which will return an unspecified value: a clear no-no.
Note: This answer was written while the question still had a C++ tag, and uses C++ terminology. The end effect in C is the same, but the terminology might be different.
You are invoking undefined behaviour, that it works in one version is just an accident:
return (n*factNnumbers(--n));
Do you use n first and then decrement it or the other way around? I don't know and neither does the compiler, it's free to do either of them or format your hard drive. Just use n * f(n - 1).
Also, your "working" version does not return for the n==1 case, which is illegal.
There are two causes of undefined behavior in your code:
Whether n or --n in n * factNnumbers(--n) will be evaluated first is unspecified.See this. You want just n * factNnumbers(n - 1), why decrement? You're not using decremented n afterwards (at least you didn't want to).
You're not returning a value on all control paths, what's going to be returned on n == 1? An indeterminate value that will mess up the whole result.
the rule of decrement:
X = Y-- first passes the value of I to X and decrements after
X = --I first pass and decrements the value decremented X
for your case, you decrement the value of parameter passed as argument to the function factNnumbers. Therefore remedy this error, I invite you to put (n-1) instead of (--n).
I think it’s better to use the tgamma function from math.h for double precision calculations involving factorials (such as Poisson distribution etc.): tgamma(n+1) will give you factorial(n).
Factorial function is increasing very fast, and this will work also for values too big to fit an integer type.
When n<=1 (or == 1 in your code), the factorial function has to return 1. Futhermore the your --n in you code is false and sould be n-1 as:
function factorial(n)
{
if (n<=1)
return 1;
else
return n * factorial(n-1);
}

This code is giving an absurd answer [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is really happening in this code?
I have a code which includes a recursive function. I have wasted a lot of time on recursion, but i still couldn't get it, really:
#include<stdio.h>
count(int);
main(){
int x=10,z;
z=count(x);
}
count(int m){
if(m>0)
return count(m-1);
}
When count is called for the first time with argument 10, it fulfils the condition and the recursion starts. What happens really when a function calls itself? I dont get it. What does the statement return count(m-1) mean? Where does it tranfer the control?
The return value of the function count is undefined, because there is no default return if (m <= 0) is true.
C11, § 6.9.1 Function definitions
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
Besides, to understand how a recursive function works, you have to take a paper and try to execute the code by yourself (see also here).
You need count to return something when m <= 0. You should declare the return type of count and compile with -Wall so the compiler will help you find mistakes in your code.
recursion means that the function will call itself, mostly at the end of itself, if it's tail recursion.
So your count function checks that the input argument is > 0 and then if it is, it will call count(m-1). Now it starts at the top of count with m=9. It does the same thing, and then calls count with m=8, etc.
Until the end condition is reached, which should normally be explicitly catered for in your function, such as if (m == 0) return m; or some such thing. At that point the recursion ends and the function terminates.
Also, count should have a return type, such as int count (int m)
what does the statement return count(m-1) mean ? where does it tranfer the control?
That seems to be your only question.
it means that it is calling "count" with the value m-1. So if m was 10, then it is calling "count" with 9.
It is transferring the control recursively to the count method.
You also don't have a return for the every possible path in the "count" method.
What happens if m is <= 0?

Resources