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
using System ; class GFG { static 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 ; } public static void Main ( ) { int [ ] steps = { 1 , - 1 , 0 , 0 , 1 , 1 , - 3 , 2 } ; int n = steps . Length ; Console . WriteLine ( times ( steps , n ) ) ; } }