C# program to print triangle with different symbols and letters (smiley, copyright, star, numbers, alphabets) on console


Here in this post we are going to learn, how to print triangle on console using C#.net.

Outputs we are going to learn:

printing triangle with white smiley symbol on consoleprinting triangle with black smiley symbol on consoleprinting triangle with copyright symbol on consoleprinting triangle with star symbol on consoleprinting triangle with numbers on consoleprinting triangle with numbers on consoleimageimage

So we will print the above outputs on the console using C#.Net

How are we going to implement:

1. we will ask the user to enter Number of rows to print.

2. then we will print the pattern

3. to print the special symbols like smiley and copyright I have used Unicode characters and for that we need to mark output encoding as below

Marking output encoding
Console.OutputEncoding = System.Text.Encoding.UTF8;

4. I have given only 3 examples with symbols and if you want to try with more you can get the Unicode characters from the below link

https://www.compart.com/en/unicode/category/So?page=4

Triangle with Star symbol
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write("*");
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Triangle with numbers
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write(i);
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Triangel with numbers
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write(starCount);
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Triangle with Copyright symbol
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write('\u00A9');
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Triangle with black smiley
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write('\u263A');
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Triangle with white smiley
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write('\u263B');
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Triangle with alphabets
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            int ascii = 65;
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write(Convert.ToChar(ascii + starCount));
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Triangle with alphabets
using System;

namespace AlgorithamsAndLogics
{
    class TrianglePattern
    {
        static void Main(String[] args)
        {
            int ascii = 65;
            Console.OutputEncoding = System.Text.Encoding.UTF8;
            Console.WriteLine("Howmany number of rows do you want to print?");
            int numberOfRows = Convert.ToInt32(Console.ReadLine());
            for (int i = 1; i <= numberOfRows; i++)
            {
                int starCount = 0;
                for (int j = 1; j <= numberOfRows – i; j++)
                {
                    Console.Write(" ");
                }
                while (2 * i – 1 != starCount)
                {
                    Console.Write(Convert.ToChar(ascii + i – 1));
                    starCount++;
                }
                Console.WriteLine("");
            }
            Console.ReadKey();
        }
    }
}

Output:

image

Happy coding..!

Advertisements

Deserializing JSON object to runtime type or dynamic types using JsonConvert.DeserializeObject and reflection


JsonConvert.DeserializeObject method has 8 overloaded methods one of them will full fill our requirement.

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

these are the 8 overloaded methods of JsonConvert.DeserializeObject

 

Screenshot_10

Screenshot_13

Screenshot_14

Screenshot_15

Screenshot_16

Screenshot_17

Screenshot_18

Screenshot_19

If we want to deserialize Json object to a runtime type or dynamic type we can use 3rd overload method of JsonConvert.DeserializeObject

string jsonData = "{\"key\":\"value\"}";
string typeName = "SampleNamespace.SampleClassName";
Type requestType = Type.GetType(typeName);
var result = JsonConvert.DeserializeObject(jsonData, requestType);

In the above code typeName is class name which is matching json properties.

then create the type using Type.GetType() method.

then pass this type to our JsonConvert.DeserializeObject method.

Happy Coding SmileComputer

How can we force clients to refresh JavaScript files?


Q: How can we force web clients to refresh or load latest version javascript files from the web server.

This is the problem most of the web developers facing after deploying their newer versions of javascript files.

We normally ask the customer to hit Ctrl + F5 to ensure that all the latest javascript files loaded from server not from the cache.

But we can solve this in different ways as follows

Solution 1: If you are maintaining javascript versioning

If you are using javascript versions, it’s easy to solve the issue. i.e we just need to add the version to javascript file path as follows

<script src="~/scripts/demojs.js?100"></script>
<script src="~/scripts/demojs.js?version=100"></script>

so If the version of the file changed then the url also change. so if the url is different than the file which is already in cache, the browser (client) will request to get latest file from the server.

So these file will render to clients as follows

Loading from cache

image

Loading from server

image

Solution 2: If you are not using versioning use Asp.Net MVC datetime object ticks

In this case we just use ticks from C# datetime object as follows

<script src="~/scripts/demojs.js?@DateTime.Now.Ticks"></script>
<script src="~/scripts/demojs.js?currentTime=@DateTime.Now.Ticks"></script>

image

Solution 3: Restart application and Recycle Application pool in IIS

Please do following steps after completion of your deployment in IIS

  1. Restart your website

image

2. Then find the applicationpool of your website and recycle it.

image

In case of Microsoft Azure websites

Screenshot_10

Thanks

Happy coding ComputerSmile

invalid uri: the uri string is too long. XDocument load


The reason for the error

invalid uri: the uri string is too long. XDocument load

is the issue with parameter we are passing. It is expecting file path or textreader or xmlreader depends on the method signature we are using.

The parameter we are following should not be the XML data in string.

XDocument.Load method is having 8 overloaded functions as shown below.

//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.IO.TextReader.
public static XDocument Load(TextReader textReader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from an System.Xml.XmlReader.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that contains the content for the System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified System.Xml.XmlReader.
public static XDocument Load(XmlReader reader);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream.
//
// Parameters:
//   stream:
//     The stream that contains the XML data.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a System.IO.TextReader, optionally
//     preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   textReader:
//     A System.IO.TextReader that contains the content for the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.IO.TextReader.
public static XDocument Load(TextReader textReader, LoadOptions options);
//
// Summary:
//     Loads an System.Xml.Linq.XDocument from an System.Xml.XmlReader, optionally setting
//     the base URI, and retaining line information.
//
// Parameters:
//   reader:
//     A System.Xml.XmlReader that will be read for the content of the System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the XML that was read from the specified
//     System.Xml.XmlReader.
public static XDocument Load(XmlReader reader, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument from a file, optionally preserving white
//     space, setting the base URI, and retaining line information.
//
// Parameters:
//   uri:
//     A URI string that references the file to load into a new System.Xml.Linq.XDocument.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies white space behavior, and whether
//     to load base URI and line information.
//
// Returns:
//     An System.Xml.Linq.XDocument that contains the contents of the specified file.
public static XDocument Load(string uri, LoadOptions options);
//
// Summary:
//     Creates a new System.Xml.Linq.XDocument instance by using the specified stream,
//     optionally preserving white space, setting the base URI, and retaining line information.
//
// Parameters:
//   stream:
//     The stream containing the XML data.
//
//   options:
//     A System.Xml.Linq.LoadOptions that specifies whether to load base URI and line
//     information.
//
// Returns:
//     An System.Xml.Linq.XDocument object that reads the data that is contained in
//     the stream.
public static XDocument Load(Stream stream, LoadOptions options);

The parameter we are following should not be the XML data in string.

If you want to load xml from string to XDocument use XDocument.Parse as shown in below picture

Screenshot_3

Happy Coding ComputerSmile

Reverse words in a string without using string functions in C#


  1. static void Main(string[] args)
  2.         {
  3.             string inp = Console.ReadLine();
  4.             StringBuilder strb = new StringBuilder();
  5.             List<char> word = new List<char>();
  6.             for (int c = 0; c < inp.Length; c++)
  7.             {
  8.  
  9.                 if (char.IsWhiteSpace(inp[c]) == true || c == inp.Length)
  10.                 {
  11.                     string tsb = string.Empty;
  12.                     foreach (var item in word)
  13.                     {
  14.                         tsb += item;
  15.                     }
  16.                     strb.Insert(0, tsb);
  17.                     strb.Insert(0, ' ');
  18.                     word = new List<char>();
  19.                 }
  20.                 else
  21.                     word.Add(inp[c]);
  22.             }
  23.             string tsb1 = string.Empty;
  24.             foreach (var item in word)
  25.             {
  26.                 tsb1 += item;
  27.             }
  28.             strb.Insert(0, tsb1);
  29.             string output = strb.ToString();
  30.             Console.WriteLine(output);
  31.             Console.Read();
  32.         }

OUT PUT:

input string: This is nice blog

output string: blog nice is This

How to find number of words in a string without using split method


Using string split function:

  1. static void Main(string[] args)
  2.         {
  3.             string str = Console.ReadLine();
  4.             string[] words = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  5.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words.Length);
  6.             Console.Read();
  7.         }

Find number of words without using string.split function:

Using Regex:
  1. static void Main(string[] args)
  2.         {
  3.             string str = Console.ReadLine();
  4.             var words = Regex.Matches(str, @"[\S]+");
  5.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words.Count);
  6.             Console.Read();
  7.         }

Using whitespace:
  1. string str = Console.ReadLine();
  2.             int words = 1;
  3.             for (int i = 0; i < str.Length – 1; i++)
  4.             {
  5.                 if (char.IsWhiteSpace(str[i]) == true)
  6.                 {
  7.                     words++;
  8.                 }
  9.             }
  10.             Console.WriteLine("No of words in \"{0}\" are {1}", str, words);
  11.             Console.Read();

How to convert string to xml in c#


Example1:

  1. String rawXml =
  2.           @"<root>
  3.                 <person firstname=""Riley"" lastname=""Scott"" />
  4.                 <person firstname=""Thomas"" lastname=""Scott"" />
  5.             </root>";
  6.             XmlDocument xmlDoc = new XmlDocument();
  7.             xmlDoc.LoadXml(rawXml);

Example2:

  1. String rawXml =
  2.           @"<root>
  3.                 <person firstname=""Riley"" lastname=""Scott"" />
  4.                 <person firstname=""Thomas"" lastname=""Scott"" />
  5.             </root>";
  6.             XElement xmlDoc = XElement.Parse(rawXml);

Example3:

  1. String rawXml =
  2.           @"<root>
  3.                 <person firstname=""Riley"" lastname=""Scott"" />
  4.                 <person firstname=""Thomas"" lastname=""Scott"" />
  5.             </root>";
  6.             XDocument xd = XDocument.Parse(rawXml);