- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Position after taking N steps to the right and left in an alternate manner in C++
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,
#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
Advertisements