Write a program that reads a string from the user and generates a histogram for the characters encountered in this string. A histogram is a representation of how many times each character appears in the input string. Use function Histogram that takes the string as input and displays its histogram.

For example,

String: My name is Nermeen
Histogram //output
M       *
y         *
space  ***
n         **
a         *
m        **
e         ****
i         *
s         *
N        *
r         *

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            string Sentence = Console.ReadLine();
            char[] letters = Sentence.ToCharArray();
            for (int i = 0; i < letters.Length; i++)
                int count = 0;
                for (int j = 0; j < letters.Length; j++)
                    if (letters[i] == letters[j])

                for (int k = 0; k <count ; k++)

                    Console.Write("{0} : *",letters[i]);
                Console.WriteLine( );



The problem in my code is that some characters get repeated for example m:if there is another m in another place the program writes it again m:.would you please correct the code for me so that i could the program as the output required by problem.

thanks :)

Edited by Dani: Formatting fixed

6 Years
Discussion Span
Last Post by reemhatim

I could fix it for you, but this looks like an assignment and what would you learn?

Your problem is that you need to store each character, and a count of how many times it occurs. You need at least one more variable.


No,it is not an assignment it is a question in a book I have for learning c#. would you please declare it more for me what variable do I need.thanks


what advise would you give me to be a good programmer in c# . I'm still a beginner and I need help to know how to get to the right way . thanks :)


Well, you need something that holds the character and the current amount. Take a look at Dictionary<>. You could use the letter as the key and the count as the value.

You'll have to make sure there is an entry for the letter before you add it.


I tried alot but I'm still having the same problem .Would you please help me more? thanks

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.