

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
- Related Questions & Answers
- Print a matrix in alternate manner (left to right then right to left) in C++
- How to handle right-to-left and left-to-right swipe gestures on Android?
- C++ Program to get blocks position after right side rotation
- Set the left, right, top and bottom padding of an element
- How to handle right-to-left and left-to-right swipe gestures on iOS App?
- How to handle right-to-left and left-to-right swipe gestures on Android using Kotlin?
- How to position text to top left position on an image with CSS
- Left and Right Alignment using the float Property in CSS
- Program to find out the position of a ball after n reversals in Python
- Shift strings Circular left and right in JavaScript
- How to position text to top right position on an image with CSS
- CSS3 Left to right Gradient
- Program to print right and left arrow patterns in C
- Program to find number of items left after selling n items in python
- Alternate Primes till N in C++?
Advertisements