Problem 3-5

CSharp · Console

/Program.cs

// Write a program that reads the sequential heights of a flying plane
// (sequence of positive integers ending with 0) and 
// prints the longest continuous horizontal segment of the flight
using System;
using System.Diagnostics;
					
public class Program
{
	public static int InputInt(string prompt)
	{
		Console.Write("Enter " + prompt + ": ");
		return Convert.ToInt32(Console.ReadLine());
	}
	
    public static void Main(string[] args)
    {
        // Inductive extension:
		int h = 0;			// last height
		int max = 0;		// longest horisontal segment (including last one)
		int last_len = 0;	// length of last horisontal segment
		
		int nextHeight = InputInt("h");
		while (nextHeight != 0)
		{
			if(nextHeight == h)
				last_len++;
			else
			{
				last_len = 1;
				h = nextHeight;
			}
			
			if(last_len > max)
			{
				max = last_len;
			}
			nextHeight = InputInt("h");	
		}
		Console.WriteLine("Longest horisontal segment length = " + max);
		
		// Time = O(sequence length)
    }
}
;