Explain this C programming, how it works, and more details.

Question:

Explain this C programming, how it works, and more details.

int iterationofsequence1(int n)
{
int sq[n];
int len=2;
sq[0]=0;
sq[1]=1;
for(int i=0,1=2;i<n;i++,1++)
{if(isOdd(sq[1-1]))
{
sq[1]=sq[1-1]+sq[1-2];
}
else
{
sq[1]=sq[1-1]+(sq[1-2]+sq[1-3]);
}
len=1;
}
return sq[n-1];
}

int recursionofsequence2(int n, int sq[], int 1 int i)
{
if(isOdd(sq[1]))
{
i++;
sq[1+1]=sq[1]+i;
}
else{
sq[1+1]=sq[1]/2;
}
1++;
if(1<n){
return recursionofsequence2(n, sq, 1, i);
}
else
{
return sq[n-1];
}
}

Summary:

Basically, a sequence is considered and the two methods find the nth number in the sequence. The first method follows an iterative approach to find the nth number in the sequence, while the second method follows a recursive approach to find the nth number in the sequence.

Explanation:

Explanation for the function iterationOfSequence1:

Tracing:

Consider the example where n = 4 is passed to the function.

  • Consider array sq[n]

Initializing len=2, sq[0]=0, sq[1]=1

  • Loop iteration-1
i=0, l=2

i<n is true

sq[l-1] = sq[2-1] = sq[1]

isOdd(sq[1]) = true

sq[2] = sq[1] + sq[0] = 1 + 0 = 1

len = 2

Loop iteration-2

i=1, l=3

i<n is true

sq[l-1] = sq[3-1] = sq[2]

isOdd(sq[2]) = true

sq[3] = sq[2] + sq[1] = 1 + 1 = 2

len = 3

Loop iteration-3

i=2, l=4

i<n is true

sq[l-1] = sq[4-1] = sq[3]

isOdd(sq[3]) = false

sq[4] = sq[3] + sq[2] + sq[1]= 2 + 1 + 1 = 4

len = 4

Loop iteration-4

i=3, l=5

i<n is true

sq[l-1] = sq[5-1] = sq[4]

isOdd(sq[3]) = false

sq[5] = sq[4] + sq[3] + sq[2] = 4+ 2 + 1 = 7

len = 5

Loop iteration-5

i=4, l=6

i<n is false

stop

return sq[n-1] = sq[4-1] = sq[3] = 2

 

The given method finds a number of the sequence in the nth position. If the previous number in the sequence is odd, then the current number will be obtained by adding the last two numbers. If it is even, then the current number will be obtained by the last 3 numbers. Finally, n-1 the number in the sequence is returned.

The explanation for the function recursionOfSequence2 with C programming:

Tracing:

  • Passed arguments are n, sq[], l, and I

Let them be:

n=4, sq[]={0, 1}, l=1, i=1
  •  Recursion-1
sq[l] = sq[1] = 1

isOdd(1) = true

i=i+1 = 1+1 = 2

sq[l+1] = sq[2] = sq[1] + i = 1 + 2 = 3

l = 2

l<n is true

 

  •  Recursion-2
sq[l] = sq[2] = 3

isOdd(3) = true

i=i+1 = 1+1 = 3

sq[l+1] = sq[3] = sq[2] + i = 3 + 3 = 6

l = 3

l<n is true

 

  • Recursion-3
sq[l] = sq[3] = 6

isOdd(6) = false

sq[l+1] = sq[4] = sq[3] /2= 6/2 = 3

l = 4

l<n is false

return sq[n -1] = sq[4-1] = sq[3] = 6

 

In this method the same process happens as in method-1, The only difference is that it follows a recursive approach, while the first method follows an iterative approach.

 

Also, read the Vehicle management system in c++.

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *