Very simple console barchart

ddanbe 0 Tallied Votes 1K Views Share

Well, I don't think I can make this any simpler. I hope newbies in the C# language can learn from it.

using System;
using System.Collections.Generic;

namespace SimpleBarChart
{
    class Program
    {
        static void Main(string[] args)
        {
            // Make some data in a list for simplicity here.
            // Normaly get them from a user, file or a histogram calculation.
            List<float> BinList = new List<float>();
            BinList.Add(3.3f);
            BinList.Add(5f);
            BinList.Add(4.2f);
            BinList.Add(7.2f);
            BinList.Add(8.5f);
            BinList.Add(6.1f);
            BinList.Add(2f);
            BinList.Add(1.6f);
            DrawBarChart(BinList);
            Console.ReadKey();
        }

        static void DrawBarChart(List<float> LF)
        {
            // calculate maximum of the data
            float max = 0;  
            for (int i = 0; i < LF.Count; i++)
            {
                if (LF[i] > max) max = LF[i];
            }
            // draw chart
            Console.WriteLine('|');
            for (int i = 0; i < LF.Count; i++)
            {
                Console.Write('|');
                for (int j = 0; j < (int)(LF[i]/max * 25f); j++)
                {
                    Console.Write('#');
                }
                Console.WriteLine();
            }
            Console.WriteLine('|');
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.