Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to find the floor and ceiling of the value N in an unsorted list with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

class FloorCeilFinder
{
    // Finds the floor and ceil of N in the given list
    public static (int floor, int ceil) FindFloorAndCeil(List<int> lst, int N) {
        int floorval = int.MinValue; // Initialize to smallest possible value
        int ceilval = int.MaxValue;  // Initialize to largest possible value

        foreach (int num in lst) {
            if (num <= N && num > floorval) {
                floorval = num; // Update floorval if num is closer to N
            }
            if (num >= N && num < ceilval) {
                ceilval = num; // Update ceilval if num is closer to N
            }
        }

        // If no valid floorval or ceilval is found, set them to a special value
        if (floorval == int.MinValue) floorval = -1;
        if (ceilval == int.MaxValue) ceilval = -1;

        return (floorval, ceilval);
    }

    static void Main()
    {
        List<int> lst = new List<int> { 4, 10, 8, 2, 6, 9, 1 };
        int N = 5;

        var (floorval, ceilval) = FindFloorAndCeil(lst, N);

        Console.WriteLine("floor: " + (floorval == -1 ? "None" : floorval.ToString()));
        Console.WriteLine("ceil: " + (ceilval == -1 ? "None" : ceilval.ToString()));
    }
}



/*
run:

floor: 4
ceil: 6

*/

 



answered Nov 8, 2025 by avibootz
edited Nov 8, 2025 by avibootz
...