Position after taking N steps to the right and left in an alternate manner in C++

C++Server Side ProgrammingProgramming

In this problem, we are given three integers N, A and B. there is a person who is standing at coordinate 0 moves

A step towards the right and then B step towards left. Then again right. Our task is to print the final position of the element after N moves.

Let’s take an example to understand the problem,

Input − N = 4, A = 3, B = 1

Output

Explanation

1st move -> right 3, +3
2nd move -> left 1, -1
3rd move -> right 3, +3
4th move -> left 1, -1.
Position after 4 moves, +3-1+3-1 = 4.

To solve this problem, we have to find the total steps taken by the person, taking the right moves positively and left moves negative. All odd moves are taken right and even moves are taken left.

Total steps taken will be calculated by the formula,

Steps = [((n+1)/2)*a - (n/2)*b]

Example

Program to show an illustration of our solution,

 Live Demo

#include <iostream>
using namespace std;
void finalPosition(int n, int a, int b) {
   int steps = {((n + 1)/2)*a - (n/2)*b};
   cout<<steps;
}
int main() {
   int N=4, A=3, B=1;
   cout<<"The final position of the person after "<<N<<" steps is ";
   finalPosition(N,A,B);
   return 0;
}

Output

The final position of the person after 4 steps is 4
raja
Updated on 17-Apr-2020 08:14:51

Advertisements