Please navigate to the bottom of the page for Table of Contents

Saturday, May 14, 2011

Simple coding questions–Part 1

During an interview (either in person or over phone), many interviewers like to ask very simple coding questions. This is usually to check how fast the interviewee can do a context switch in her mind, her ability to think about some very basic problem, etc.
So, let’s tackle a few of such coding problems in this post. I am using C# as the programming language in this example, but you can do the same in almost any modern language.

How to find the largest of 3 numbers

using System;

namespace SimpleCodingQuestions
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(FindLargestNumber(6, 3, 9));
        }

        /// <summary>
        /// Find the largest of three numbers
        /// </summary>
        /// <param name="a">first parameter</param>
        /// <param name="b">second parameter</param>
        /// <param name="c">third parameter</param>
        /// <returns></returns>
        public static long FindLargestNumber(long a, long b, long c)
        {
            // assume that the first value is the biggest
            long biggest = a;

            // check if b is the biggest
            if (b > biggest)
                biggest = b;

            // check if c is the biggest
            if (c > biggest)
                biggest = c;

            return biggest;
        }
    }
}



My next follow-up question is: Can you find the largest number in a variable length argument list? For those who come from the C/C++ background, this is the same as va_args list. In C#, this is referred by the the params keyword.

The params keyword lets you specify a method parameter that takes a variable number of arguments.

You can send a comma-separated list of arguments of the type specified in the parameter declaration, or an array of arguments of the specified type. You also can send no arguments.

No additional parameters are permitted after the params keyword in a method declaration, and only one params keyword is permitted in a method declaration.

For more details, refer to the MSDN article at http://msdn.microsoft.com/en-us/library/w5zay9db.aspx

Find the largest number in a variable length argument list

using System;

namespace SimpleCodingQuestions
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(FindLargestNumber(6, 3, 9));
            Console.WriteLine(FindLargestNumber(6));
            Console.WriteLine(FindLargestNumber(6, 3, 9, 2, 5, 8));
        }

        /// <summary>
        /// Find the largest number in a variable list 
        /// </summary>
        /// <param name="a">first parameter. Required.</param>
        /// <param name="numbers">variable list of longs</param>
        /// <returns></returns>
        public static long FindLargestNumber(long a, params long[] numbers)
        {
            // assume that the first value is the biggest
            long biggest = a;

            // loop through all the arguments passed
            foreach (long x in numbers)
            {
                // check if the current number is the biggest
                if (x > biggest)
                    biggest = x;
            }

            return biggest;
        }
    }
}

I hope this post helped you grasp an important concept. No question is simple. Even trivial questions can catch you off guard. Keep your focus razor sharp at all times. We will discuss a few more simple coding questions in the coming blog posts.

25 comments:

  1. Nice article , you have indeed cover the topic with great details. I have also blogged my experience as programming interview questions . let me know how do you find it.

    ReplyDelete
  2. Would it be silly to solve this in one line?

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

    namespace ConsoleApplication15
    {
    public class Program
    {
    public static void Main( string[] args )
    {
    Console.WriteLine( "The largest number is {0}", new List { 5, 3, 9 }.Max() );
    }
    }
    }

    ReplyDelete
  3. Oops, the comment engine stripped out the less than int greater than that's part of the generic List. Let me try it again with an HTML encode.

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

    namespace ConsoleApplication15
    {
    public class Program
    {
    public static void Main( string[] args )
    {
    Console.WriteLine( "The largest number is {0}", new List<int> { 5, 3, 9 }.Max() );
    }
    }
    }

    ReplyDelete
    Replies
    1. Great ! in one line code :)

      Delete
    2. KiaOra,


      Hip Hip Hooray! I was always told that slightly slow in the head, a slow learner. Not anymore! It’s like you have my back. I can’t tell you how much I’ve learnt here and how easily! Thank you for blessing me with this effortlessly ingestible digestible content.
      I don't often ask questions here, but this one (especially being a regex thing) has me a bit stumped.

      I'm trying to piece together a regex that allows characters, digits and a couple of other characters.
      Essentially:
      ^[a-zA-Z0-9:,';\/]+$

      Also it can't start or end with a slash...so the above becomes:
      ^[^\/][a-zA-Z0-9:,';\/]+[^\/]$

      So this gives a match:
      abcD,xy/z
      and this doesn't
      /abcD,xy/z







      Anyways great write up, your efforts are much appreciated.


      Gracias

      Delete
  4. wtf? dan's answer is right but hell, it's a coding question and the interviewer definitely isn't waiting for an answer that Microsoft answered but an answer that is actually logically thought by you.

    ReplyDelete
  5. Dan you give us answer in short thanks

    ReplyDelete
  6. We can also solve this question in One Line
    public int FindMax(int a, int b, int c)
    {
    var maxVlues = (a > b && a > c) ? a : (b > a && b > c) ? b : c;
    return maxVlues;
    }

    ReplyDelete
  7. Hola,


    What a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this.

    I have two methods and they do almost same thing, but at some most inner nested level one of method have additional command.

    Java Code:
    method2(){
    ... same code ...
    for {
    ... same code ...
    if{
    ... same code ...
    }
    }
    }






    Follow my new blog if you interested in just tag along me


    in any
    social media platforms!


    Shukran,

    ReplyDelete
  8. Hi There,

    I genuinely do look forward for the time where you post some new write ups. Your blog make me feel so educated! Continue soaring and writing please.

    i have created a simple program but not finding the solution to understand the Output of the code.

    Please any one Solve this code and output:----- Help!!!!!!
    {
    int a,b,c,d;
    printf("%d%d%d%d",3,3+2,c,a+b*c-d);
    getch();
    }

    But great job man, do keep posted with the new updates.

    Thank you,
    Preethi

    ReplyDelete
  9. You have touched good quality points here. In whatever way continue writing.
    UI UX company

    ReplyDelete
  10. Thank you for sharing practical insights and sharing your knowledge. Your blog is a must-read for anyone interested in this topic. keep it up. Transportation Management System

    ReplyDelete
  11. Excellent post! I appreciate how well you addressed this subject. Both the writing and the thoughts were excellent. We appreciate you sharing your knowledge. Anticipating more from you to read. Keep up the excellent work! E-commerce Web Development Services Company India

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Great post! I really enjoyed your insights. Your explanation made it much easier to understand.
    command logistics services

    ReplyDelete
  14. Thanks for the detailed explanation. Such a useful read! Thank you for your knowledge. SEO Agency USA

    ReplyDelete
  15. Thank you for such good writing! Your insights were spot on and exactly what I was looking for. I will definitely follow your blog for more content. SEO Services India

    ReplyDelete
  16. Great post! I really enjoyed your insights. Your explanation made it much easier to understand.Logistics Bpo

    ReplyDelete