Lesson 4.4

Conditional Statements Programming Exercises


Objective

If Else Programming Question
Nested If Programming Question
Switch Case Programming Question



Qu 1: Write a program to calculate leap year using IF Else statement between Years 2000 to Year 2050.

Qu 2: Write a program to calculate prime number using nested if else statements.

Hints

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

namespace nested_if
{
    class Program
    {
        static void Main(string[] args)
        {
            label:
            int count = 0;
            Console.WriteLine("Enter a number to find all prime number under them: ");
            int num = Convert.ToInt32(Console.ReadLine());
            
            if (num >= 2)
            {
                count = 0;
                for (int i = 2; i <= num; i++)
                {
                    if (num % i == 0)
                    {
                        count++;
                    }
                }
                if (count == 1)
                {
                    Console.WriteLine(num + " is a prime number");
                }
                else
                {
                    Console.WriteLine(num + " is not a prime number");
                }
            }
            else
            {
                Console.WriteLine("Please enter number 2 or above 2");
                goto label;
            }
            Console.ReadKey();
        }
    }
}

Output

Enter a number to find all prime number under them: 37

37 is a prime number

__

Qu 3: Write a program to show some funny messages based on user input using switch case statements. The message should be like this:

  • You are naughty.
  • You are going to die after 70 years.
  • You will have 5 kids, etc.

Summary

In this chapter you have covered some programming exercises of if else, nested if else and switch case statements. In the next chapter we will learn Loop Statements in C#.

BackNext