How does the control flow in a recursive program work? - c

I am not sure why this piece of code prints out "5678998765". I see how it gets the 56789 part but when the numbers start going down is where i get confused. So if someone could explain i would be grateful.
int out(int k) {
if (k == 10) {
return 1;
}
printf("%d", k);
out(k +1);
printf("%d", k);
}
int main()
{
out(5);
return 0;

It is printed from last printf; every function needs to be executed till the end.
int out(int k) {
if (k == 10) {
return 1;
}
printf(" + %d", k);
out(k +1);
printf(" - %d", k);
}
You should try this, when it will be clearer.

Within the function for each value of k that is not equal to 10 there are two calls of printf
printf("%d", k);
out(k +1);
printf("%d", k);
So if the function is called the first time when k is equal to 5 then you will have
5 ( a call of out( 6 ) ) 5
then in the recursive call you will heav
56 ( a call of out( 7 ) ) 65
and so on.
When k is equal to 10 then nothing is outputted.

When main evaluates out(5), out runs and does this:
k is not 10, so continue.
Print k, which is 5.
Evaluate out(6).
Print k, which is 5.
That evaluates out(6), so replace the step “Evaluate out(6)” with what out does for that:
k is not 10, so continue.
Print k, which is 5.
k is not 10, so continue.
Print k, which is 6.
Evaluate out(7).
Print k, which is 6.
Print k, which is 5.
Now you can see the program is going to print 5, then 6, then evaluate out(7), then print 6, then print 5. This continues until we have:
k is not 10, so continue.
Print k, which is 5.
k is not 10, so continue.
Print k, which is 6.
k is not 10, so continue.
Print k, which is 7.
k is not 10, so continue.
Print k, which is 8.
k is not 10, so continue.
Print k, which is 9.
k is 10, so return 1.
Print k, which is 9.
Print k, which is 8.
Print k, which is 7.
Print k, which is 6.
Print k, which is 5.

Related

How to make a series that adds up by 5 every 5 counts using for loop?

I'm kind of new in C programming and I'm trying to make a program that prints the nth term of a series and every 5 counts, it adds up by 5.
Example: 1, 2, 3, 4, 9, 10, 11, 12, 17, 18, 19, 20, 25......
Here is my code
int num,digit,count = 1;
printf("Enter n: ");
scanf("%d", &num);
for(int i=1; i<=num; i++){
count++;
if(count > 5){
count = 0;
i+=4;
}
printf("%d ",i);
}
My code doesn't get to the specific nth term that I'm asking for. For example, I've inputted 10 and it only shows up until the 6th term
The thing to do is get clear in your head what you want to do and how you are going to do it. Rather than tinkering with code, break things down into simple parts and make them clear.
#include <stdio.h>
int main(void)
{
int num = 10;
// Method 1: Spell everything out.
// i counts number of terms printed.
// j counts number of terms since last multiple of four terms.
// k is current term.
for (
int i = 0, j = 0, k = 1; // Initialize all counters.
i < num; // Continue until num terms are printed.
++i) // Update count.
{
printf("%d ", k); // Print current term.
++j; // Increment four-beat count.
if (4 <= j)
{
// Every fourth term, reset j and increment the term by 5.
j = 0;
k += 5;
}
else
// Otherwise, increment the term by 1.
k += 1;
}
printf("\n");
// Method 2: Use one counter and calculate term.
// Iterate i to print num terms.
for (int i = 0; i < num; ++i)
/* Break the loop count into two parts: the number of groups of 4
(i/4) and a subcount within each group (i%4). Looking at the
starts of each group (1, 9, 17, 25...), we see each is eight
greater than the previous one. So we multiply the group number by
8 to get the right offsets for them. Within each group, the term
increments by 1, so we use i%4 directly (effectively multiplied by
1). Then (i/4)*8 + i%4 would start us at 0 for i=0, but we want to
start at 1, so we add 1.
*/
printf("%d ", (i/4)*8 + i%4 + 1);
printf("\n");
}
You shall not change the variable i within the body of the for loop.
You need to introduce one more variable that will store the current outputted number.
Here is a demonstration program.
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter n: " );
scanf( "%u", &n );
for ( unsigned int i = 0, value = 0, count = 1; i < n; i++ )
{
if ( count == 5 )
{
value += 5;
count = 1;
}
else
{
++value;
}
printf( "%u ", value );
++count;
}
}
The program output is
Enter n: 13
1 2 3 4 9 10 11 12 17 18 19 20 25
Here's another take that I think is a bit less complicated, with explanations in the comments:
#include <stdio.h>
int main(void)
{
int num, count = 1;
num = 20;
// if you look closely, you actually have an initial condition before the
// main pattern starts. Once the pattern starts, its actually every _fourth_
// term that gets added by 5. You'll make things easier on yourself if you
// print out this initial condition, then handle the pattern in the loop.
// If you really want to be correct, you can wrap this in a if (num > 0) check
printf("%d ", count++);
// start at 1, because we already printed the first item
for(int i=1; i<num; i++, count++)
{
// now we can focus on every fourth term
if (i % 4 == 0)
{
// if it's the fourth one, add 5 to the previous value
// Of course this simplifies to count += 4
count = (count-1) + 5;
}
printf("%d ",count);
}
}
Demonstration

How to output this numbers sequence?

Examples:
enter a number:5
output : 5,10,15,20,25,20,15,10,5
**Example 2:**
enter a number :3 output : 3,6,9,6,3
Code:
#include<stdio.h>
void main(){
int a,i ;
a=5;
i=1;
do{
printf("%d\t",a*i);
i++;
}
while(i<=5);
int b,l;
b=3;
l=1;
do{
printf("\n%d\t",b*l);
l++;
}
while (l<=3);
}
Please help me with my codes so that I can improve myself and the showing the correct result that is supposed to first increase an then to decrease the given number.
To print those kinds of sequences you can also use recursion. Your function would look something like this:
void printSequence(int x, int incr)
{
if (x == incr * incr)
{
printf("%d ", x);
return;
}
printf("%d ", x);
printSequence(x + incr, incr);
printf("%d ", x);
}
So you send starting number and increment to the function. In your case they would be the same number, because you want to start, for example, with 5 and increment it by 5 until you hit 5*5. Your base case is when your number x becomes eaqual to x*x which is in code represented as x == incr * incr. If your base case is true, you just print out current value of x and return from the function. And if your base case is not true you want to print out the value of x and call the same function again with incremented x. Then print out the value of x again when you recursively start going back from the last function call to the original one.
If your main looks like this:
int main(void)
{
printSequence(5, 5);
return 0;
}
Output will be:
5 10 15 20 25 20 15 10 5

How to fix program printing a 0 after the print statement executes in C?

This program tests Goldbach's Conjecture, printing a given even integer as the sum of two primes. After printing the first one, the given integer is to iterate by 2 , then find the sum of two primes for that integer. And so on until the program is interrupted by the user.
This problem is that the program prints a '0' after every executed print statement.
The code:
#include <stdio.h>
#include <math.h>
int GC(int goldsum); //function prototype
int main()
{
int goldsum;
printf("Enter an even integer greater than 5: ");
scanf("%d", &goldsum);
printf("%d\n", GC(goldsum));
goldsum = goldsum + 2;
printf("%d\n", GC(goldsum));
}
int GC(int goldsum) //function definition
{
int i, j; //prime addends
int div1, div2; //divisors
char prime1, prime2;
for (i=2 ;i<goldsum ;i++) //when number is less than goldsum, run this loop iterating by 1
{
prime1 = 1;
for (div1=2 ;div1<i ;div1++) //this loop determines if "i" is prime.
if (i % div1 == 0) //if yes, the prime number is stored in "i"
prime1 = 0;
if (prime1)
{
for (j=3; j<goldsum; j+=2) //when number is less than goldsum, run this loop iterating by 2
{
prime1 = 1;
for (div2=2; div2<j; div2++) //this loop determines if "j" is prime.
if(j % div2 == 0) //if yes, the prime number is stored in "j"
prime1 = 0;
if (prime1)
if (i + j == goldsum) //If i + j = goldsum, it prints the result.
{
printf("%d + %d = %d\n",i ,j , goldsum);
return 0;
}
}
}
}
return 0;
}
The output:
Enter an even integer greater than 5: 10
3 + 7 = 10
0
5 + 7 = 12
0
What I want it to look like:
Enter an even integer greater than 5: 10
3 + 7 = 10
5 + 7 = 12
use just GC(goldsum);
instead of printf("%d\n", GC(goldsum));
Maybe you misunderstood the return 0; we put in main(). Every function has to return the value we desire. In the case of main we want 0 because that means everything was OK. In the case of your function the return value should be what YOU want from it.
Edit: re-read the question and adding this: Since you don't want a return value from you function you should declare it as void and not have it in a printf() because all the printing you want is in your function.
Void functions do not return a value, so that is what you want.

Please explain the code?

int main()
{
int N, K, i, j, k, x, final, cur, A[22];
for(i=!!scanf("%d %d",&N,&K), printf("%d\n",(final=N*N)-N);i<=N;A[i++]=i);
for(i=(cur=N)-1; i>=1; i--)
for(j=1; j<=i; printf("%d %d min\n%d %d max\n",A[j],A[j+1],A[j],A[j+1]),A[j]=++cur, A[j+1]=++cur, j++);
for(printf("%d",final-1+(cur=final)*0+(x=2)*0); cur>N; printf(" %d",cur), cur-=x, x+=2);
return 0;
}
Please explain the use of 2 exclamation marks in the first "for" statement.
I will just explain first for loops, last 3 for loops is easy to understand.
Step by step explanation.
Step 1:
for(i=!!scanf("%d %d",&N,&K), printf("%d\n",(final=N*N)-N);i<=N;A[i++]=i);
Here, scanf("%d %d",&N,&K) returns 2 (number of integer read successfully.)
Step 2: single negation, !2 = 0, now negate this 0, !0 = 1. So, i = !!2 = 1
Step 3: Suppose your input was 3 5 [N=3, K=5]. so output of printf("%d\n",(final=N*N)-N) will be final = (3*3)-3 = 6
Step 4: Checking condition: i<=N means, is 1<=N? If yes then this loop continues until the condition becomes false. in the process as A[i++] = i, first the index i of A is set then i increases by 1, then the value of A[i] is set to i. So finally you get the following array:
A[1] = 2;
A[2] = 3;
A[3] = 4;
Step 3: Suppose your input was 3 5 [N=3, K=5]. so output of printf("%d\n",(final=N*N)-N) will be (final = (3*3)-3) = 6(output) ,final =6.

Debugging Factorial Recursion

I am new to the C programming language and I am trying to learn recursion for computing the factorial of a given number. My question is the debugging printf statement is printing 2,6,24,120 if I input '5'. How does it print 4 times if the function calls are replaced with the corresponding values and computes the factorial at a time?
#include<stdio.h>
#include<stdlib.h>
int factorial(int n);
int main()
{
int num;
int fact_val;
printf("Enter the number for which you are going to compute the factorial:");
scanf("%d",&num);
fact_val=factorial(num);
printf("The factorial of the given number is %d\n",fact_val);
return 0;
}
int factorial(int n)
{
int factorial_val;
if(n==1)
return 1;
else
{
factorial_val=factorial(n-1)*n;
printf("Debugger-%d\n",factorial_val);
}
return factorial_val;
}
When you reach your base-case, you return immediately rather than printing.
So you see a printf for cases: 5, 4, 3, 2, and when the function is passed 1, the value isn't printed: you return instead.
Furthermore you recurse before you print, so the cases are printed in order, least-first: the first print happens only after you've recursed all the way down to 2. Hence you see: 2, 6, 24, 120. Only when you've returned from the current recursion is the intermediate value printed.
Write down the recursion to make it clearer:
5 -> recurse with 4:
4 -> recurse with 3:
3 -> recurse with 2:
2 -> recurse with 1:
1 -> base case, just return...
printf (1 * 2) = 2;
printf (2 * 3) = 6;
printf (6 * 4) = 24;
printf (24 * 5) = 120;

Resources