Distance Traveled by Two Trains together in the same Direction | C ++ Program to find the distance traveled together by the two trains ; Function to find the distance traveled together ; Stores distance travelled by A ; Stpres distance travelled by B ; Stores the total distance travelled together ; Sum of distance travelled ; Condition for traveling together ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int calc_distance ( int A [ ] , int B [ ] , int n ) { int distance_traveled_A = 0 ; int distance_traveled_B = 0 ; int answer = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { distance_traveled_A += A [ i ] ; distance_traveled_B += B [ i ] ; if ( ( distance_traveled_A == distance_traveled_B ) && ( A [ i ] == B [ i ] ) ) { answer += A [ i ] ; } } return answer ; } int main ( ) { int A [ 5 ] = { 1 , 2 , 3 , 2 , 4 } ; int B [ 5 ] = { 2 , 1 , 3 , 1 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << calc_distance ( A , B , N ) ; return 0 ; }