Count the number of times graph crosses X | C ++ implementation to count the number of times the graph crosses the x - axis . ; Function to to count the number of times the graph crosses the x - axis . ; Iterate over the steps array ; Update the previous level and current level by value given in the steps array ; Condition to check that the graph crosses the origin . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int times ( int steps [ ] , int n ) { int current_level = 0 ; int previous_level = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { previous_level = current_level ; current_level = current_level + steps [ i ] ; if ( ( previous_level < 0 && current_level >= 0 ) || ( previous_level > 0 && current_level <= 0 ) ) { count ++ ; } } return count ; } int main ( ) { int steps [ 12 ] = { 1 , -1 , 0 , 0 , 1 , 1 , -3 , 2 } ; int n = sizeof ( steps ) / sizeof ( int ) ; cout << times ( steps , n ) ; return 0 ; }