0% found this document useful (0 votes)
2K views68 pages

C# Programming Example and Solutions

The document contains C# code examples for basic programs including printing "Hello World", adding integers, swapping variable values, multiplying floating point numbers, and performing all arithmetic operations. It also includes programs to convert between units like feet to meters, Celsius to Fahrenheit, and days to years/weeks/days. Additionally, it shows conditional programs to check if a number is even or odd, find the largest of three numbers, and find the largest number using conditional operators. All programs demonstrate basic programming concepts in C# through examples that take user input and display output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2K views68 pages

C# Programming Example and Solutions

The document contains C# code examples for basic programs including printing "Hello World", adding integers, swapping variable values, multiplying floating point numbers, and performing all arithmetic operations. It also includes programs to convert between units like feet to meters, Celsius to Fahrenheit, and days to years/weeks/days. Additionally, it shows conditional programs to check if a number is even or odd, find the largest of three numbers, and find the largest number using conditional operators. All programs demonstrate basic programming concepts in C# through examples that take user input and display output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 68

C# programming example and solutions

TOPIC 1

C# Language Basic programs with examples

C# Program to Print “Hello, World!”


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadKey();
}
}
}

C# Program to Add Two Integers


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
int total = num2 + num1;
Console.WriteLine($"Total is {total}");
Console.ReadKey();
}
}
}

C# Program to Swap Values of Two Variables


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Type value of number 1: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Type value of number 2: ");
int num2 = Convert.ToInt32(Console.ReadLine());

int temp = num1;


num1 = num2;
1
C# programming example and solutions
num2 = temp;
Console.WriteLine("\nAfter swapping values");
Console.WriteLine($"Value of number 1: {num1}");
Console.WriteLine($"Value of number 2: {num2}");
Console.ReadKey();
}
}
}

C# Program to Multiply two Floating Point Numbers


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());

double total = num2 * num1;

Console.WriteLine($"Total is: {total}");


Console.ReadKey();
}
}
}

C# Program to perform all arithmetic operations


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());

int sum = num1 + num2;


int sub = num1 - num2;
int mult = num1 * num2;
int mod = num1 % num2;
float div = (float)num1 / num2;

Console.WriteLine("\nSum of number1 and number2: {sum}");


Console.WriteLine($"Difference of number1 and number2 : {sub}");
Console.WriteLine($"Product of number1 and number2: {mult}");
Console.WriteLine($"Modulus of number1 and number2: {mod}");
Console.WriteLine($"Quotient of number1 and number2: {div}");
Console.ReadKey();
}
}
}
2
C# programming example and solutions
C# Program to convert feet to meter
using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter feet: ");
double feet = Convert.ToInt32(Console.ReadLine());
double meter = feet / 3.2808399;
Console.WriteLine($"\nFeet in meter: {meter}");
Console.ReadKey();
}
}
}

C# Program to convert celcius to farenheit


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Temperature in Celsius: ");
double celsius = Convert.ToDouble(Console.ReadLine());
double fahrenheit = (1.8 * celsius) + 32;
Console.WriteLine($"Temperature in Fahrenheit: {fahrenheit}");
Console.ReadKey();
}
}
}

C# Program to convert farenheit to celcius


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Temperature in Fahrenheit: ");
double fahrenheit = Convert.ToDouble(Console.ReadLine());
double celsius = (fahrenheit - 32) * 5 / 9;
Console.WriteLine($"Temperature in Celsius: {celsius}");
Console.ReadKey();
}
}
}

3
C# programming example and solutions
C# Program to find the Size of data types
using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Size of char: {sizeof(char)}");
Console.WriteLine($"Size of Short: {sizeof(short)}");

Console.WriteLine($"Size of int: {sizeof(int)}");


Console.WriteLine($"Size of long: {sizeof(long)}");

Console.WriteLine($"Size of float: {sizeof(float)}");


Console.ReadKey();
}
}
}

C# Program to Print ASCII Value


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
char c;
Console.Write("Enter a character: ");
c = Convert.ToChar(Console.ReadLine());
Console.WriteLine($"\nASCII value of {c} is {Convert.ToInt32(c)}");
Console.ReadKey();
}
}
}

C# Program to Calculate Area of Circle


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Radius: ");
double radius = Convert.ToDouble(Console.ReadLine());
double area = Math.PI * radius * radius;
Console.WriteLine($"\nArea of circle: {area}");
Console.ReadKey();
}
}
}

4
C# programming example and solutions
C# Program to Calculate Area of Square
using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the Length of Side: ");
double side = Convert.ToDouble(Console.ReadLine());
double area = side * side;
Console.WriteLine($"\nArea of Square: {area}");
Console.ReadKey();
}
}
}

C# Program to Calculate Area of Rectangle


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter length of rectangle: ");
double length = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter breadth of rectangle: ");
double breadth = Convert.ToDouble(Console.ReadLine());

double area = length * breadth;


Console.WriteLine("\nArea of rectangle: {area}");
Console.ReadKey();
}
}
}

C# Program to convert days to years, weeks and days


using System;

namespace StudyCSharp
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter days: ");
int days = Convert.ToInt32(Console.ReadLine());

int years = (days / 365);


int weeks = (days % 365) / 7;
days = days - ((years * 365) + (weeks * 7));

Console.WriteLine($"Years: {years}");
Console.WriteLine($"weeks: {weeks}");
Console.WriteLine($"Days: {days}");
5
C# programming example and solutions

Console.ReadKey();
}
}
}

TOPIC 2
List of all conditional programs in c# language

C# Program to check whether an integer entered by the user is odd or even


using System;

namespace csharpprograms
{
class Program
{
static void Main(string[] args)
{
int number;
Console.Write("Enter a number: ");
number = Convert.ToInt32(Console.ReadLine());

// Even number if remainder is 0


if (number % 2 == 0)
Console.WriteLine("Entered number is an even number");
else
Console.WriteLine("Entered number is odd number");

Console.ReadLine();
}
}
}

C# Program to find the largest number among three number.


using System;

namespace csharpprograms
{
class Program
{
static void Main(string[] args)
{
Console.Write("Input the 1st number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the 2nd number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the 3rd number: ");
int num3 = Convert.ToInt32(Console.ReadLine());

6
C# programming example and solutions
if (num1 > num2)
{
if (num1 > num3)
{
Console.Write("The 1st number is the greatest among three. \n\n");
}
else
{
Console.Write("The 3rd number is the greatest among three. \n\n");
}
}
else if (num2 > num3)
Console.Write("The 2nd number is the greatest among three \n\n");
else
Console.Write("The 3rd number is the greatest among three \n\n");

Console.ReadLine();
}
}
}

C# Program to Find the Largest Number using Conditional Operator.


using System;

namespace csharpprograms
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter three numbers:");
int num1 = Convert.ToInt32(Console.ReadLine());
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = Convert.ToInt32(Console.ReadLine());

int largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ?
num2 : num3);

Console.WriteLine($"{largest} is the largest number.");

Console.ReadLine();
}
}
}

C# Program to find the Largest among Three Variables using Nested if.
using System;

namespace csharpprograms
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter three numbers: \n");
int num1 = Convert.ToInt32(Console.ReadLine());
int num2 = Convert.ToInt32(Console.ReadLine());
int num3 = Convert.ToInt32(Console.ReadLine());

7
C# programming example and solutions
if (num1 >= num2)
{
if (num1 >= num3)
Console.WriteLine($"{num1} is the largest number");
else
Console.WriteLine($"{num3} is the largest number");
}

else if (num2 >= num3)


Console.WriteLine($"{num2} is the largest number");

else
Console.WriteLine($"{num3} is the largest number");

Console.ReadLine();
}
}
}

C# program to check leap year using conditional Operator.


using System;

namespace csharpprograms
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Year: ");
int year = Convert.ToInt32(Console.ReadLine());
Console.WriteLine((year % 400 == 0) || ((year % 4 == 0) && (year % 100 !=
0)) ? "Entered year is a leap" : "Not leap year");

Console.ReadLine();
}
}
}

C# Program to Check whether an alphabet is a vowel or not.


using System;

public class exercise17


{
static void Main(string[] args)
{
char ch;

Console.Write("Input an Alphabet (A-Z or a-z): ");


ch = Convert.ToChar(Console.ReadLine().ToLower());

int i = ch;
if (i >= 48 && i <= 57)
Console.Write("You entered a number, please enter an alpahbet.");
else
{
switch (ch)
{
case 'a':
Console.WriteLine("The Alphabet is vowel");
break;
8
C# programming example and solutions
case 'i':
Console.WriteLine("The Alphabet is vowel");
break;
case 'o':
Console.WriteLine("The Alphabet is vowel");
break;
case 'u':
Console.WriteLine("The Alphabet is vowel");
break;
case 'e':
Console.WriteLine("The Alphabet is vowel");
break;
default:
Console.WriteLine("The Alphabet is not a vowel");
break;
}
}
Console.ReadLine();
}
}

C# program to check number is positive, negative or zero.


using System;

public class charpexercise


{
static void Main(string[] args)
{
int num;

Console.WriteLine("Enter any number: ");


num = Convert.ToInt32(Console.ReadLine());

if (num > 0)
{
Console.WriteLine("Enter number is positive ");
}
else if (num < 0)
{
Console.WriteLine("Enter number is nagative ");
}
else
{
Console.WriteLine("Enter number is zero ");
}

Console.ReadLine();
}
}

9
C# programming example and solutions
C# program to check uppercase or lowercase alphabets.
using System;

public class charpexercise


{
static void Main(string[] args)
{
char ch;

Console.WriteLine("Enter any character: ");


ch = Convert.ToChar(Console.ReadLine());

if (ch >= 'a' && ch <= 'z')


{
Console.WriteLine(ch + " is lowercase alphabet ");
}
else if (ch >= 'A' && ch <= 'Z')
{
Console.WriteLine(ch + " is uppercase alphabet ");
}
else
{
Console.WriteLine(ch + " is not an alphabet ");
}

Console.ReadLine();
}
}

C# program to check entered character vowel or consonant.


using System;

public class charpexercise


{
static void Main(string[] args)
{
char ch;

Console.WriteLine("Enter any character: ");


ch = Convert.ToChar(Console.ReadLine());

// Condition for vowel checking


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A'
|| ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
Console.WriteLine(ch + " is Vowel.");

else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
Console.WriteLine(ch + " is Consonant.");

Console.ReadLine();
}
}

10
C# programming example and solutions
C# program to check whether a character is alphabet, digit or special
character.
using System;

public class charpexercise


{
static void Main(string[] args)
{
char ch;

Console.WriteLine("Enter any character: ");


ch = Convert.ToChar(Console.ReadLine());

// Alphabet checking condition


if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
Console.WriteLine(ch + "is an Alphabet. ");
else if (ch >= '0' && ch <= '9')
Console.WriteLine(ch + "is a Digit. ");
else
Console.WriteLine(ch + "is a Special character.. ");

Console.ReadLine();
}
}

C# program to print day name of week.


using System;

public class charpexercise


{
static void Main(string[] args)
{

int week;

Console.WriteLine("Enter week number (1-7): ");


week = Convert.ToInt32(Console.ReadLine());

if (week == 1)
Console.WriteLine("Monday");
else if (week == 2)
Console.WriteLine("Tuesday");
else if (week == 3)
Console.WriteLine("Wednesday");
else if (week == 4)
Console.WriteLine("Thursday");
else if (week == 5)
Console.WriteLine("Friday");
else if (week == 6)
Console.WriteLine("Saturday");
else if (week == 7)
Console.WriteLine("Sunday");
else
Console.WriteLine("Invalid Input! Please enter week in between 1-7.");

Console.ReadLine();
}
}

11
C# programming example and solutions
C# program to accept two integers and check whether they are equal or
not.
using System;

public class charpexercise


{
static void Main(string[] args)
{

int num1, num2;

Console.WriteLine("Input the values for Number1 and Number2 : ");


num1 = Convert.ToInt32(Console.ReadLine());
num2 = Convert.ToInt32(Console.ReadLine());

if (num1 == num2)
Console.WriteLine("Number1 and Number2 are equal\n");
else
Console.WriteLine("Number1 and Number2 are not equal\n");

Console.ReadLine();
}
}

C# program to detrermine a candidate’s age is eligible for casting the vote or


not.
using System;

public class charpexercise


{
static void Main(string[] args)
{

int Candiateage;

Console.WriteLine("Input the age of the candidate : ");


Candiateage = Convert.ToInt32(Console.ReadLine());

if (Candiateage < 18)


{
Console.WriteLine("Sorry, You are not eligible to caste your vote.\n");
Console.WriteLine($"You would be able to caste your vote after {18 -
Candiateage} year.\n");
}
else
Console.WriteLine("Congratulation! You are eligible for casting your
vote.\n");

Console.ReadLine();
}
}

12
C# programming example and solutions
C# program to find the eligibility of admission for an engineering course
based on the criteria.
using System;

public class charpexercise


{
public static void Main()
{
int p, c, m;

Console.Write("\n\n");
Console.Write("Find eligibility for admission :\n");
Console.Write("----------------------------------");
Console.Write("\n\n");

Console.Write("Eligibility Criteria :\n");


Console.Write("Marks in Maths >=65\n");
Console.Write("and Marks in Phy >=55\n");
Console.Write("and Marks in Chem>=50\n");
Console.Write("and Total in all three subject >=180\n");
Console.Write("or Total in Maths and Physics >=140\n");
Console.Write("-------------------------------------\n");

Console.Write("Input the marks obtained in Physics :");


p = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the marks obtained in Chemistry :");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the marks obtained in Mathematics :");
m = Convert.ToInt32(Console.ReadLine());
Console.Write("Total marks of Maths, Physics and Chemistry : {0}\n", m + p +
c);
Console.Write("Total marks of Maths and Physics : {0}\n", m + p);

if (m >= 65)
if (p >= 55)
if (c >= 50)
if ((m + p + c) >= 180 || (m + p) >= 140)
Console.Write("The candidate is eligible for admission.\n");
else
Console.Write("The candidate is not eligible.\n\n");
else
Console.Write("The candidate is not eligible.\n\n");
else
Console.Write("The candidate is not eligible.\n\n");
else
Console.Write("The candidate is not eligible.\n\n");

Console.ReadLine();
}
}

13
C# programming example and solutions
C# program to calculate the total marks, percentage and division of
student.
using System;

public class csharpExercise


{
static void Main(string[] args)
{
double rl, phy, che, ca, total;
double per;
string nm, div;

Console.Write("\n\n");
Console.Write("Calculate the total, percentage and division to take marks of
three subjects:\n");
Console.Write("---------------------------------------------------------------
----------------");
Console.Write("\n\n");

Console.Write("Input the Roll Number of the student :");


rl = Convert.ToInt32(Console.ReadLine());

Console.Write("Input the Name of the Student :");


nm = Console.ReadLine();

Console.Write("Input the marks of Physics : ");


phy = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the marks of Chemistry : ");
che = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the marks of Computer Application : ");
ca = Convert.ToInt32(Console.ReadLine());

total = phy + che + ca;


per = total / 3.0;
if (per >= 60)
div = "First";
else
if (per < 60 && per >= 48)
div = "Second";
else
if (per < 48 && per >= 36)
div = "Pass";
else
div = "Fail";

Console.Write("\nRoll No : {0}\nName of Student : {1}\n", rl, nm);


Console.Write("Marks in Physics : {0}\nMarks in Chemistry : {1}\nMarks in
Computer Application : {2}\n", phy, che, ca);
Console.Write("Total Marks = {0}\nPercentage = {1}\nDivision = {2}\n", total,
per, div);

Console.ReadLine();
}
}

14
C# programming example and solutions
C# program to enter month number and print number of days in month.
using System;

public class csharpExercise


{
static void Main(string[] args)
{
int month;

Console.WriteLine("Enter month number (1-12): ");


month = Convert.ToInt32(Console.ReadLine());

if (month == 1)
Console.WriteLine("Enter month : January \nNo. of days : 31 days");
else if (month == 2)
Console.WriteLine("Enter month : February \nNo. of days : 28 or 29 days");
else if (month == 3)
Console.WriteLine("Enter month : March \nNo. of days : 31 days");
else if (month == 4)
Console.WriteLine("Enter month : April \nNo. of days : 30 days");
else if (month == 5)
Console.WriteLine("Enter month : May \nNo. of days : 31 days");
else if (month == 6)
Console.WriteLine("Enter month : June \nNo. of days : 30 days");
else if (month == 7)
Console.WriteLine("Enter month : July \nNo. of days : 31 days");
else if (month == 8)
Console.WriteLine("Enter month : August \nNo. of days : 31 days");
else if (month == 9)
Console.WriteLine("Enter month : September \nNo. of days : 30 days");
else if (month == 10)
Console.WriteLine("Enter month : October \nNo. of days : 31 days");
else if (month == 11)
Console.WriteLine("Enter month : November \nNo. of days : 30 days");
else if (month == 12)
Console.WriteLine("Enter month : December \nNo. of days : 31 days"); ;
else
Console.WriteLine("Invalid input! Please enter month number between (1-
12).");

Console.ReadLine();
}
}

C# program to count total number of notes in entered amount.


using System;

public class csharpExercise


{
static void Main(string[] args)
{

int amount;

int note1, note2, note5, note10, note20, note50, note100, note500;

note1 = note2 = note5 = note10 = note20 = note50 = note100 = note500 = 0;

Console.WriteLine("Enter amount: ");


amount = Convert.ToInt32(Console.ReadLine());
15
C# programming example and solutions

if (amount >= 500)


{
note500 = amount / 500;
amount -= note500 * 500;
}
if (amount >= 100)
{
note100 = amount / 100;
amount -= note100 * 100;
}
if (amount >= 50)
{
note50 = amount / 50;
amount -= note50 * 50;
}
if (amount >= 20)
{
note20 = amount / 20;
amount -= note20 * 20;
}
if (amount >= 10)
{
note10 = amount / 10;
amount -= note10 * 10;
}
if (amount >= 5)
{
note5 = amount / 5;
amount -= note5 * 5;
}
if (amount >= 2)
{
note2 = amount / 2;
amount -= note2 * 2;
}
if (amount >= 1)
{
note1 = amount;
}

Console.WriteLine("Total number of notes = \n");


Console.WriteLine("500 = " + note500);
Console.WriteLine("100 = " + note100);
Console.WriteLine("50 = " + note50);
Console.WriteLine("20 = " + note20);
Console.WriteLine("10 = " + note10);
Console.WriteLine("5 = " + note5);
Console.WriteLine("2 = " + note2);
Console.WriteLine("1 = " + note1);

Console.ReadLine();
}
}

16
C# programming example and solutions
C# program to check whether a triangle can be formed by the given value
for the angles.
using System;

public class csharpExercise


{
static void Main(string[] args)
{

int anglea, angleb, anglec, sum;

Console.WriteLine("Input three angles of triangle : ");


anglea = Convert.ToInt32(Console.ReadLine());
angleb = Convert.ToInt32(Console.ReadLine());
anglec = Convert.ToInt32(Console.ReadLine());

// Calculate the sum of all angles of triangle


sum = anglea + angleb + anglec;

// Check whether sum=180 then its a valid triangle otherwise invalid triangle
if (sum == 180)
Console.WriteLine("It is a valid triangle.\n");
else
Console.WriteLine("It is a invalid triangle.\n");

Console.ReadLine();
}
}

TOPIC 3
List of C# Language Loop Programs with Examples

Write C# program to print alphabets from a to z


using System;

public class csharpExercise


{
static void Main(string[] args)
{

char ch;

Console.WriteLine("Alphabets from a - z are: ");


for (ch = 'a'; ch <= 'z'; ch++)
//Printing all alphabets with tab
Console.Write(ch + "\t");

Console.ReadLine();
}
}

17
C# programming example and solutions
Write C# program to print ASCII values of all characters
using System;

public class csharpExercise


{
static void Main(string[] args)
{
int i;

// Printing ASCII values from 0 to 255


for (i = 0; i <= 255; i++)
Console.WriteLine("ASCII value of " + i + " = " + i);

Console.ReadLine();
}
}

Write C# program to print multiplication table of a given number


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int i, num;

//Reading number
Console.WriteLine("Enter number to print table: ");
num = Convert.ToInt32(Console.ReadLine());

for (i = 1; i <= 10; i++)


//Printing table of number entered by user
Console.Write("{0} X {1} = {2} \n", num, i, num * i);

Console.ReadLine();
}
}

Write C# program to print all natural numbers in reverse order


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int i, num;

//Read a number from user


Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

/*Running loop from the number entered by user, and Decrementing by 1*/
for (i = num; i >= 1; i--)
Console.WriteLine("\n" + i);

Console.ReadLine();
}
}
18
C# programming example and solutions
Write C# program to print sum of digits enter by user
using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, total;

//Reading number
Console.WriteLine("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

//Adding sum of digit in total variable


for (total = 0; num > 0; num = num / 10)
total = total + (num % 10);

//Printing sum of digit


Console.WriteLine("Sum of digits: " + total);

Console.ReadLine();
}
}

Write C# program to find sum of even numbers between 1 to n


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int i, num, sum = 0;

// Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

for (i = 2; i <= num; i += 2)


//Adding current even number to sum variable
sum += i;
Console.WriteLine("Sum of all even number between 1 to " + num + " = " + sum);

Console.ReadLine();
}
}

Write C# program to find sum of odd numbers between 1 to n


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int i, num, sum = 0;

// Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());
19
C# programming example and solutions

for (i = 1; i <= num; i += 2)


//Adding current odd number to sum variable
sum += i;
Console.WriteLine("Sum of all odd numbers between 1 to " + num + " = " + sum);

Console.ReadLine();
}
}

Write C# program to swap first and last digit of a number


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, last, first, temp, count = 0;
double swap;

// Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

temp = num;
last = temp % 10;
count = (int)Math.Log10(temp);

while (temp >= 10)


{
temp /= 10;
}
first = temp;
swap = (last * Math.Pow(10, count) + first) + (num - (first * Math.Pow(10,
count) + last));

Console.WriteLine("Last Digit:" + last);

Console.WriteLine("First Digit:" + first);

Console.WriteLine(num + " is swapped to " + swap);

Console.ReadLine();
}
}

Write C# program to find the sum of first and last digit of any number
using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, sum = 0, firstDigit, lastDigit;

// Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

lastDigit = num % 10;


20
C# programming example and solutions

firstDigit = num;

while (num >= 10)


num = num / 10;
firstDigit = num;

//Finding sum of first and last digit


sum = firstDigit + lastDigit;

Console.WriteLine("Sum of first and last digit: " + sum);

Console.ReadLine();
}
}

Write C# program to find first and last digit of any number


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, last;

// Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

last = num % 10;


Console.WriteLine("The last digit of entered number: " + last);

while (num >= 10)


num = num / 10;

Console.WriteLine("The first digit of entered number: " + num);

Console.ReadLine();
}
}

Write C# program to calculate product of digits of a number


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, product = 1;

// Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

// Repeat the steps till n becomes 0


while (num != 0)
{
product = product * (num % 10);

// Remove the last digit from n


21
C# programming example and solutions
num = num / 10;
}

Console.WriteLine("Product of digits = " + product);

Console.ReadLine();
}
}

Write C# program to reverse a number


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, rev = 0;

// Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

//finding reverse number using while loop


while (num > 0)
{
rev = rev * 10;
rev = rev + num % 10;
num = num / 10;
}

Console.Write("Reversed number is = " + rev);

Console.ReadLine();
}
}

Write C# program to calculate power using while & for loop


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int basenumber, exponent, power, i;

// Reading number
Console.Write("Enter any number: ");
basenumber = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter any number: ");


exponent = Convert.ToInt32(Console.ReadLine());

power = 1;
i = 1;
//caculatinh power of given number
while (i <= exponent)
{
power = power * basenumber;
i++;
}
22
C# programming example and solutions
Console.Write("Power : " + power);

Console.ReadLine();
}
}

Write C# program to find factorial of any number


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, i;
long fact = 1;

// Reading number
Console.Write("Enter any number to calculate factorial: ");
num = Convert.ToInt32(Console.ReadLine());
fact = 1;
i = 1;

//Run loop from 1 to number entered by user


while (i <= num)
{
fact = fact * i;
i++;
}

Console.Write("Factorial of : " + num + " is " + fact);


Console.ReadLine();
}
}

Write C# program to check whether a number is Armstrong number or not


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, sum = 0, i, r;
// Reading number
Console.Write("Please enter a number: ");
num = Convert.ToInt32(Console.ReadLine());

//Finding armstrong number or not


for (i = num; i > 0; i = i / 10)
{
r = i % 10;
sum = sum + r * r * r;
}

if (num == sum)
Console.WriteLine(num + " is an armstrong number.");
else
Console.WriteLine(num + " is not an armstrong number.");
Console.ReadLine();
}
}
23
C# programming example and solutions
Write C# program to find Armstrong numbers between 1 to n
using System;

public class csharpExercise


{
static void Main(string[] args)
{
int lower, higher, i, temp1, temp2, remainder, n = 0;
double result = 0;

// Reading number
Console.Write("Please Enter two numbers: ");
lower = Convert.ToInt32(Console.ReadLine());
higher = Convert.ToInt32(Console.ReadLine());

Console.Write("Armstrong numbers between " + lower + " and " + higher + " are:
");

for (i = lower + 1; i < higher; ++i)


{
temp2 = i;
temp1 = i;

// number of digits calculation


while (temp1 != 0)
{
temp1 /= 10;
++n;
}

// result contains sum of nth power of its digits


while (temp2 != 0)
{
remainder = temp2 % 10;
result += Math.Pow(remainder, n);
temp2 /= 10;
}

// checking if number i is equal to the sum of nth power of its digits


if (result == i)
{
Console.WriteLine(i);
}

// resetting the values to check Armstrong number for next iteration


n = 0;
result = 0;

Console.ReadLine();
}
}

24
C# programming example and solutions
Write C# program to calculate compound Interest
using System;

public class csharpExercise


{
static void Main(string[] args)
{
float amount, rate, intrest, time, ci, a;

/*Reading amount, rate of intrest


and period in years from user
*/

Console.Write("Type the amount : ");


amount = Convert.ToInt32(Console.ReadLine());

Console.Write("Type the interest rate : ");


rate = Convert.ToInt32(Console.ReadLine());

Console.Write("Type the period in years: ");


time = Convert.ToInt32(Console.ReadLine());

intrest = 1 + (rate / 100);

// ci=pow(intrest,time);
ci = 1;
for (a = 1; a <= time; a++)
ci = ci * intrest;

ci = amount * ci - amount;

Console.WriteLine("Your compound interest is : " + ci);

Console.ReadLine();
}
}

Write C# program to check a enter number is Prime number or not using


while & for loop
using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, i, f;

//Reading number
Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

f = 0;
i = 2;
while (i <= num / 2)
{
if (num % i == 0)
{
f = 1;
break;

25
C# programming example and solutions
}
i++;
}
if (f == 0)
Console.WriteLine(num + " is a Prime Number");
else
Console.WriteLine(num + " is not a Prime Number");

Console.ReadLine();
}
}

Write C# program to check whether a number is palindrome or not


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num, i, rev;

// Reading a number from user


Console.Write("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());

rev = num;
for (i = 0; num > 0; num = num / 10)
{
i = i * 10;
i = i + (num % 10);
}

//Checking if reverse number is equal to original num or not.


if (rev == i)
Console.WriteLine(rev + " is a Palindrome Number.");
else
Console.WriteLine(rev + " is not a Palindrome Number.");

Console.ReadLine();
}
}

Write C# program to print number in words


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int n, num = 0;

// Reading a number from user


Console.WriteLine("Enter any number to print in words: ");
n = Convert.ToInt32(Console.ReadLine());

while (n != 0)
{
num = (num * 10) + (n % 10);
n /= 10;
}
26
C# programming example and solutions

//print corresponding digit in words till num becomes 0


while (num != 0)
{
switch (num % 10)
{
case 0:
Console.Write("zero ");
break;
case 1:
Console.Write("one ");
break;
case 2:
Console.Write("two ");
break;
case 3:
Console.Write("three ");
break;
case 4:
Console.Write("four ");
break;
case 5:
Console.Write("five ");
break;
case 6:
Console.Write("six ");
break;
case 7:
Console.Write("seven ");
break;
case 8:
Console.Write("eight ");
break;
case 9:
Console.Write("nine ");
break;
}
num = num / 10;
}

Console.ReadLine();
}
}

Write C# program to find HCF of two numbers


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int i, num1, num2, min, HCF = 1;

// Reading 2 numbers from user


Console.WriteLine("Enter any number to print in words: ");
num1 = Convert.ToInt32(Console.ReadLine());
num2 = Convert.ToInt32(Console.ReadLine());

// Find min number between two numbers


min = (num1 < num2) ? num1 : num2;

27
C# programming example and solutions
for (i = 1; i <= min; i++)
{
if (num1 % i == 0 && num2 % i == 0)
{
HCF = i;
}
}

Console.WriteLine("HCF of " + num1 + " and " + num2 + " is: " + HCF);

Console.ReadLine();
}
}

Write C# program to find LCM of two numbers


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int num1, num2, x, y, lcm = 0;
Console.Write("Enter the First Number : ");
num1 = int.Parse(Console.ReadLine());
Console.Write("Enter the Second Number : ");
num2 = int.Parse(Console.ReadLine());
x = num1;
y = num2;
while (num1 != num2)
{
if (num1 > num2)
{
num1 = num1 - num2;
}
else
{
num2 = num2 - num1;
}
}
lcm = (x * y) / num1;
Console.Write("Least Common Multiple is : " + lcm);

Console.ReadLine();
}
}

28
C# programming example and solutions
TOPIC 4
List of Switch case C# programs with an examples

Write C# program to print number of days in a month using switch case


using System;

public class csharpExercise


{
static void Main(string[] args)
{
int monthnumber;
//Reading a month number from user
Console.WriteLine("Enter month number(1-12): ");
monthnumber = Convert.ToInt32(Console.ReadLine());
switch (monthnumber)
{
case 1:
Console.WriteLine("31 days");
break;
case 2:
Console.WriteLine("28 or 29 days");
break;
case 3:
Console.WriteLine("31 days");
break;
case 4:
Console.WriteLine("30 days");
break;
case 5:
Console.WriteLine("31 days");
break;
case 6:
Console.WriteLine("30 days");
break;
case 7:
Console.WriteLine("31 days");
break;
case 8:
Console.WriteLine("31 days");
break;
case 9:
Console.WriteLine("30 days");
break;
case 10:
Console.WriteLine("31 days");
break;
case 11:
Console.WriteLine("30 days");
break;
case 12:
Console.WriteLine("31 days");
break;
default:
Console.WriteLine("Invalid input!!! enter month number between 1-12");
break;
}
Console.ReadLine();
}
}
29
C# programming example and solutions
Write C# program to print day of week name using switch case
using System;

public class csharpExercise


{
static void Main(string[] args)
{
int weeknumber;

//Reading week no from user


Console.WriteLine("Enter week number(1-7): ");
weeknumber = Convert.ToInt32(Console.ReadLine());

switch (weeknumber)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
default:
Console.WriteLine("Invalid input! Please enter week no. between 1-
7.");
break;
}

Console.ReadLine();
}
}

30
C# programming example and solutions
Write C# program to create calculator using switch Statement
using System;

class Program
{
static void Main(string[] args)
{
int num1;
int num2;
string operand;
float answer;

Console.Write("Please enter the first integer: ");


num1 = Convert.ToInt32(Console.ReadLine());

Console.Write("Please enter an operand (+, -, /, *): ");


operand = Console.ReadLine();

Console.Write("Please enter the second integer: ");


num2 = Convert.ToInt32(Console.ReadLine());

switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
Console.WriteLine($"{num1} {operand} {num2} = {answer}");

Console.ReadLine();
}
}

Write C# program to check even or odd number using switch case


using System;

class Program
{

static void Main(string[] args)


{
int num;

//Reading a number from user


Console.Write("Enter any number to check even or odd: ");
num = Convert.ToInt32(Console.ReadLine());

31
C# programming example and solutions
switch (num % 2)
{
//If n%2 == 0
case 0:
Console.WriteLine(num + " is even number");
break;
//Else if n%2 == 1
case 1:
Console.WriteLine(num + " is odd number");
break;
}
Console.ReadLine();
}
}

Write C# program to check vowel or consonant using switch case


using System;

class Program
{
static void Main(string[] args)
{
char ch;

//Reading an alphabet from user


Console.WriteLine("Enter any alphabet: ");
ch = Convert.ToChar(Console.ReadLine());

// checking vowel and consonant


switch (ch)
{
case 'a':
Console.WriteLine("vowel");
break;
case 'e':
Console.WriteLine("vowel");
break;
case 'i':
Console.WriteLine("vowel");
break;
case 'o':
Console.WriteLine("vowel");
break;
case 'u':
Console.WriteLine("vowel");
break;
case 'A':
Console.WriteLine("vowel");
break;
case 'E':
Console.WriteLine("vowel");
break;
case 'I':
Console.WriteLine("vowel");
break;
case 'O':
Console.WriteLine("vowel");
break;
case 'U':
Console.WriteLine("vowel");
break;

32
C# programming example and solutions
default:
Console.WriteLine("consonant");
break;
}
Console.ReadLine();
}
}

Write C# program to print gender (Male/Female) program according to


given M/F.
using System;

class Program
{
static void Main(string[] args)
{
char gender;

//Reading gender from user


Console.WriteLine("Enter gender (M/m or F/f): ");
gender = Convert.ToChar(Console.ReadLine());

// checking vowel and consonant


switch (gender)
{
case 'M':
case 'm':
Console.WriteLine("MALE");
break;
case 'F':
case 'f':
Console.WriteLine("FEMALE");
break;
default:
Console.WriteLine("Unspecified Gender");
break;
}

Console.ReadLine();
}
}

Write C# Program to find maximum number using switch case.


using System;

class Program
{
static void Main(string[] args)
{
int num1 = 0, num2 = 0;

//Reading two numbers from user


Console.WriteLine("Enter two numbers to find maximum number: ");
num1 = Convert.ToInt32(Console.ReadLine());
num2 = Convert.ToInt32(Console.ReadLine());

33
C# programming example and solutions
// Condition to check maximum number
switch (num1 > num2)
{
case true:
Console.WriteLine(num1 + " is Maximum number");
break;
case false:
Console.WriteLine(num2 + " is Maximum number");
break;
}
Console.ReadLine();
}
}

TOPIC 5
List of C# language array programs with an examples

Write C# Program to get the Length of the Array


using System;

class Program
{
static void Main()
{
int[] arrayA = new int[10];
int lengthA = arrayA.Length;
Console.WriteLine("Length of ArrayA : {0}", +lengthA);
long longLength = arrayA.LongLength;
Console.WriteLine("Length of the Long Length Array : {0}", longLength);
int[,] twoD = new int[20, 50];
Console.WriteLine("The Size of 2D Array is : {0}", twoD.Length);
Console.ReadLine();
}
}

Write C# Program to Convert a 2D Array into 1D Array


using System;

namespace Program
{
class twodmatrix
{
int p, r;
int[,] a;
int[] b;
twodmatrix(int x, int y)
{
p = x;
r = y;
a = new int[p, r];
b = new int[p * r];
}

34
C# programming example and solutions
public void readmatrix()
{
for (int i = 0; i < p; i++)
{
for (int j = 0; j < r; j++)
{
Console.Write("a[{0},{1}]=", i, j);
a[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
}
public void printtwodimentionalarray()
{
for (int i = 0; i < p; i++)
{
for (int j = 0; j < r; j++)
{
Console.Write("{0}\t", a[i, j]);

}
Console.Write("\n");
}
}
public void convert()
{
int k = 0;
for (int i = 0; i < p; i++)
{
for (int j = 0; j < r; j++)
{
b[k++] = a[i, j];
}
}
}
public void printonedimentionalarray()
{
for (int i = 0; i < p * r; i++)
{
Console.WriteLine("{0}\t", b[i]);
}
}

public static void Main(string[] args)


{
twodmatrix obj = new twodmatrix(2, 3);
Console.WriteLine("Enter the Elements : ");
obj.readmatrix();
Console.WriteLine("\nGiven 2-D Array() is : ");
obj.printtwodimentionalarray();
obj.convert();
Console.WriteLine("\nConverted 1-D Array is : ");
obj.printonedimentionalarray();
Console.ReadLine();
}
}
}

35
C# programming example and solutions
Write C# Program to Demonstrate Jagged Arrays
using System;

class Program
{
static void Main()
{
int[][] jagArray = new int[3][];
jagArray[0] = new int[2];
jagArray[0][0] = 12;
jagArray[0][1] = 13;
jagArray[1] = new int[1] { 12 };
jagArray[2] = new int[3] { 15, 16, 17 };

for (int i = 0; i < jagArray.Length; i++)


{
int[] innerArray = jagArray[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.WriteLine(innerArray[a] + " ");
}
}

Console.ReadLine();
}
}

Write C# Program to Find Minimum and Maximum of Numbers


using System;
using System.Linq;

class Program
{
static void Main()
{
int[] Arr = { 20, -10, -30, 0, 15, 10, 30 };

Console.WriteLine("Maximum Element : " + Arr.Max());


Console.WriteLine("Minimum Element : " + Arr.Min());

Console.ReadLine();
}
}

Write a C# program to count total negative elements in an array


using System;

class Program
{
static void Main()
{
int[] arr = new int[100];
int i, num;

//Enter size of array


Console.WriteLine("Enter size of the array: ");
num = Convert.ToInt32(Console.ReadLine());

36
C# programming example and solutions
//Reading elements of array
Console.WriteLine("Enter elements in array: ");
for (i = 0; i < num; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}

Console.WriteLine("All negative elements in array are: ");


for (i = 0; i < num; i++)
{
//Printing negative elements
if (arr[i] < 0)
{
Console.WriteLine(arr[i]);
}
}
Console.ReadLine();
}
}

Write C# program to find sum of all elements of an array


using System;

class Program
{
static void Main()
{
int[] arr = new int[100];
int i, num, sum = 0;

////Reads size and elements in array


Console.WriteLine("Enter size of the array: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter " + num + " elements in the array: ");

for (i = 0; i < num; i++)


{
arr[i] = Convert.ToInt32(Console.ReadLine());
}

//Adding all elements


for (i = 0; i < num; i++)
{
sum = sum + arr[i]; // Calculating sum
}

Console.WriteLine("Sum of all elements of array: " + sum);

Console.ReadLine();
}
}

37
C# programming example and solutions
Write C# program to count even and odd elements in an array
using System;

class Program
{
static void Main()
{
int[] arr = new int[100];
int i, num, evennum, oddnum;

////Reads size and elements in array


Console.WriteLine("Enter size of the array: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter " + num + " elements in the array: ");

for (i = 0; i < num; i++)


{
arr[i] = Convert.ToInt32(Console.ReadLine());
}

evennum = 0; // Assuming 0 even numbers


oddnum = 0; // Assuming 0 odd numbers

for (i = 0; i < num; i++)


{
/* If the current element of array is evennumber then increment evennumber
count */
if (arr[i] % 2 == 0)
evennum++;
else
oddnum++; // increment oddnumber count
}

Console.WriteLine("Total even numbers: " + evennum);


Console.WriteLine("Total odd numbers: " + oddnum);

Console.ReadLine();
}
}

Write C# program to insert an element in array


using System;

class Program
{
static void Main()
{
int[] arr = new int[100];
int i, num, size, position;

// Reading array size & elements in the array


Console.WriteLine("Enter size of the array: ");
size = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}

38
C# programming example and solutions
//Reading element to insert & position of the element

Console.WriteLine("Enter element to insert: ");


num = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter the element position: ");


position = Convert.ToInt32(Console.ReadLine());

//checking elements valis position

if (position > size + 1 || position <= 0)


{
Console.WriteLine("Invalid position! Please enter position between 1 to "
+ num);
}
else
{
//Inserting element in an array & increasing the size of the array

for (i = size; i >= position; i--)


{
arr[i] = arr[i - 1];
}
arr[position - 1] = num;
size++;

// Printing new array with new element

Console.WriteLine("Array elements after insertion :");

for (i = 0; i < size; i++)


{
Console.WriteLine(arr[i] + "\t");
}
}
Console.ReadLine();
}
}

Write C# program to print all unique element in an array


using System;

class Program
{
static void Main()
{
int[] arr = new int[100]; ;
int i, j, k, size, isUnique;

//Reads size of the array


Console.WriteLine("Enter size of the array: ");
size = Convert.ToInt32(Console.ReadLine());

//Reads elements in array


Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}

39
C# programming example and solutions
//Removing all duplicate elements from the array
for (i = 0; i < size; i++)
{
// Assuming cuurent element is unique */
isUnique = 1;

for (j = i + 1; j < size; j++)


{

//If any duplicate element is found

if (arr[i] == arr[j])
{
// Removing duplicate element
for (k = j; k < size - 1; k++)
{
arr[k] = arr[k + 1];
}

size--;
j--;
isUnique = 0;
}
}

/*
If array element is not unique
then also remove the current element
*/
if (isUnique != 1)
{
for (j = i; j < size - 1; j++)
{
arr[j] = arr[j + 1];
}

size--;
i--;
}
}

//Printing all unique elements in array


Console.WriteLine("All unique elements in the array are: ");
for (i = 0; i < size; i++)
{
Console.WriteLine(arr[i] + "\t");
}
Console.ReadLine();
}
}

40
C# programming example and solutions
Write C# program to sort an array in ascending order
using System;

class Program
{
static void Main()
{
int[] arr = new int[100]; ;
int size, i, j, temp;

//Reads size of the array


Console.WriteLine("Enter size of the array: ");
size = Convert.ToInt32(Console.ReadLine());
//Reads elements in array
Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < size; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}

//Sorting an array in ascending order

for (i = 0; i < size; i++)


{
for (j = i + 1; j < size; j++)
{
//If there is a smaller element found on right of the array then swap
it.
if (arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
//Printing the sorted array in ascending order

Console.WriteLine("Elements of array in sorted ascending order:");


for (i = 0; i < size; i++)
{
Console.WriteLine(arr[i]);
}
Console.ReadLine();
}
}

Write C# program to copy all elements of one array to another


using System;

class Program
{
static void Main()
{
int[] arr = new int[100];

int[] first = new int[100];


int[] second = new int[100];

int i, num;
41
C# programming example and solutions

//Reads size of the array


Console.WriteLine("Enter size of the array: ");
num = Convert.ToInt32(Console.ReadLine());
//Reads elements in array
Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < num; i++)
{
first[i] = Convert.ToInt32(Console.ReadLine());
}

//Copy all elements from first array to second array


for (i = 0; i < num; i++)
{
second[i] = first[i];
}

//Printing all elements of first array entered by user


Console.WriteLine("Elements of first array are:");
for (i = 0; i < num; i++)
{
Console.Write(first[i] + "\t");
}

//Printing all elements of second array


Console.WriteLine("\nElements of second array are:");
for (i = 0; i < num; i++)
{
Console.Write(second[i] + "\t");
}

Console.ReadLine();
}
}

Write C# program to count number of each element in an array


using System;

class Program
{
static void Main()
{
int i, j, count, num;

int[] arr = new int[100];


int[] frequency = new int[100];

//Reads size of the array


Console.WriteLine("Enter size of the array: ");
num = Convert.ToInt32(Console.ReadLine());

//Reads elements in array


Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < num; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
//Initially initialize frequency variable to -1
frequency[i] = -1;
}

42
C# programming example and solutions
for (i = 0; i < num; i++)
{
count = 1;
for (j = i + 1; j < num; j++)
{
//If duplicate element is found
if (arr[i] == arr[j])
{
count++;

//Make sure not to count frequency of same element again


frequency[j] = 0;
}
}

//If frequency of current element is not counted


if (frequency[i] != 0)
frequency[i] = count;
}

//Print frequency of each element


Console.WriteLine("\nFrequency of all elements of array : \n");
for (i = 0; i < num; i++)
if (frequency[i] != 0)
Console.WriteLine(arr[i] + " occurs " + frequency[i] + " times");

Console.ReadLine();
}
}

Write C# program to delete all duplicate elements from an array


using System;

class Program
{
static void Main()
{
int[] arr = new int[100];
int num; // Total number of elements in array
int i, j, k;

//Reads size of the array


Console.WriteLine("Enter size of the array: ");
num = Convert.ToInt32(Console.ReadLine());

//Reads elements in array


Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < num; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}

// Finding all duplicate elements in array


for (i = 0; i < num; i++)
{
for (j = i + 1; j < num; j++)
{
//If any duplicate found */
if (arr[i] == arr[j])
{

43
C# programming example and solutions
// Delete the current duplicate element
for (k = j; k < num; k++)
{
arr[k] = arr[k + 1];
}

//Decrement size after removing duplicate element


num--;

// If shifting of elements occur then don't increment j


j--;
}
}
}

// Print array after deleting duplicate elements


Console.WriteLine("\nArray elements after deleting duplicates : ");
for (i = 0; i < num; i++)
{
Console.WriteLine(arr[i]);
}
Console.ReadLine();
}
}

Write C# program to count total duplicate elements in an array


using System;

class Program
{
static void Main()
{
int[] arr = new int[100];
int i, j, num, count = 0;

//Reads size of the array


Console.WriteLine("Enter size of the array: ");
num = Convert.ToInt32(Console.ReadLine());

//Reads elements in array


Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < num; i++)
arr[i] = Convert.ToInt32(Console.ReadLine());

//Find all duplicate elements in array


for (i = 0; i < num; i++)
for (j = i + 1; j < num; j++)
// If duplicate element found then increment count by 1
if (arr[i] == arr[j])
{
count++;
break;
}
Console.WriteLine("\nTotal number of duplicate elements found in array:" +
count);

Console.ReadLine();
}
}

44
C# programming example and solutions
Write C# program to merge two sorted array
using System;

class Program
{
static void Main()
{
int[] arr1 = new int[100];
int[] arr2 = new int[100];
int[] mergeArray = new int[100];

int size1, size2, mergeSize;


int index1, index2, mergeIndex;
int i;

//Reads size of the array


Console.WriteLine("Enter the size of 1st array :");
size1 = Convert.ToInt32(Console.ReadLine());

//Reads elements in array


Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < size1; i++)
{
arr1[i] = Convert.ToInt32(Console.ReadLine());
}

//Reads size of the array


Console.WriteLine("Enter the size of 2nd array :");
size2 = Convert.ToInt32(Console.ReadLine());

//Reads elements in array


Console.WriteLine("Enter elements in the array: ");
for (i = 0; i < size2; i++)
{
arr2[i] = Convert.ToInt32(Console.ReadLine());
}

mergeSize = size1 + size2;

//Merging two array in ascending order


index1 = 0;
index2 = 0;
for (mergeIndex = 0; mergeIndex < mergeSize; mergeIndex++)
{

//If all elements of one array is merged to final array


if (index1 >= size1 || index2 >= size2)
{
break;
}
if (arr1[index1] < arr2[index2])
{
mergeArray[mergeIndex] = arr1[index1];
index1++;
}
else
{
mergeArray[mergeIndex] = arr2[index2];
index2++;
}
}

45
C# programming example and solutions
//Merging the remaining elements of array
while (index1 < size1)
{
mergeArray[mergeIndex] = arr1[index1];
mergeIndex++;
index1++;
}
while (index2 < size2)
{
mergeArray[mergeIndex] = arr2[index2];
mergeIndex++;
index2++;
}

//Print merged array


Console.WriteLine("\nArray merged in ascending order : ");
for (i = 0; i < mergeSize; i++)
{
Console.Write("\t" + mergeArray[i]); ;
}

Console.ReadLine();
}
}

Write C# Program to Find the Average Values of all the Array Elements
using System;

class Program
{
public void sumAverageElements(int[] arr, int size)
{

int sum = 0;
int average = 0;
for (int i = 0; i < size; i++)
sum += arr[i];
average = sum / size;
Console.WriteLine("Sum Of Array is : " + sum);
Console.WriteLine("Average Of Array is : " + average);
Console.ReadLine();
}
public static void Main(string[] args)
{
int size;
Console.WriteLine("Enter the Size :");
size = Convert.ToInt32(Console.ReadLine());
int[] a = new int[size];
Console.WriteLine("Enter the Elements of the Array : ");
for (int i = 0; i < size; i++)
{
a[i] = Convert.ToInt32(Console.ReadLine());
}
int len = a.Length;
Program p = new Program();
p.sumAverageElements(a, len);
}
}

46
C# programming example and solutions
Write C# program to find reverse of an array
using System;

class Program
{
static void Main()
{
int[] array = new int[100];
int size, i;

//Reads size of the array


Console.WriteLine("Enter size of the array: ");
size = Convert.ToInt32(Console.ReadLine());

//Reads elements in array


Console.WriteLine("Enter elements in array: ");
for (i = 0; i < size; i++)
array[i] = Convert.ToInt32(Console.ReadLine());

//Print array in reversed order


Console.WriteLine("\nArray in reverse order: ");
for (i = size - 1; i >= 0; i--)
Console.Write("\t" + array[i]);

Console.ReadLine();
}
}

Write a program in C# Sharp to find the second largest element in an array


using System;

public class program


{
public static void Main()
{
int num, i, j = 0, lrg, lrg2nd;
int[] arr1 = new int[50];

Console.Write("Input the size of array : ");


num = Convert.ToInt32(Console.ReadLine());

//Stored values into the array


Console.Write("Input {0} elements in the array :\n", num);
for (i = 0; i < num; i++)
{
arr1[i] = Convert.ToInt32(Console.ReadLine());
}
// find location of the largest element in the array
lrg = 0;

for (i = 0; i < num; i++)


{
if (lrg < arr1[i])
{
lrg = arr1[i];
j = i;
}
}

47
C# programming example and solutions
// ignore the largest element and find the 2nd largest element in the array
lrg2nd = 0;
for (i = 0; i < num; i++)
{
if (i == j)
{
i++; //ignoring the largest element
i--;
}
else
{
if (lrg2nd < arr1[i])
{
lrg2nd = arr1[i];
}
}
}

Console.Write("The Second largest element in the array is : {0} \n\n",


lrg2nd);
Console.ReadLine();
}
}

TOPIC 6
All function programs in c# with an examples

Write a C# program to create a user define function with parameter


using System;

public class functionexcercise


{
public static void welcome(string name)
{
Console.WriteLine("Welcome " + name);
}
public static void HaveAnice()
{
Console.WriteLine("Have a nice day");
}
public static void Main(string[] args)
{
string str1;
Console.Write("Please Enter a name : ");
str1 = Console.ReadLine();
welcome(str1);
HaveAnice();

Console.ReadLine();
}
}

48
C# programming example and solutions
Write a C# program to add two numbers using function
using System;

public class functionexcercise


{
public static int Sum(int num1, int num2)
{
int total;
total = num1 + num2;
return total;
}

public static void Main()


{
Console.Write("Enter two numbers: ");
int number1 = Convert.ToInt32(Console.ReadLine());
int number2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"\nThe sum of two numbers is : {Sum(number1, number2)}");

Console.ReadLine();
}
}

Write a C# program to create a function to input a string and count


number of spaces are in the string
using System;

public class functionexcercise


{
public static int Countspaces(string str)
{
int spcctr = 0;
string strone;
for (int i = 0; i < str.Length; i++)
{
strone = str.Substring(i, 1);
if (strone == " ")
spcctr++;
}
return spcctr;
}
public static void Main()
{
string strtwo;
Console.Write("Please Enter a string : ");
strtwo = Console.ReadLine();
Console.WriteLine("\"" + strtwo + "\"" + " contains {0} spaces",
Countspaces(strtwo));

Console.ReadLine();
}
}

49
C# programming example and solutions
Write a C# program to find even or odd number using function
using System;

namespace Functionexcercise
{
class Program
{

static void Main(string[] args)


{
int number;

// Inputting number from user


Console.WriteLine("Enter any number: ");
number = Convert.ToInt32(Console.ReadLine());

CheckNumIsEvenOrOdd(number);

Console.ReadLine();
}

public static void CheckNumIsEvenOrOdd(int _number)


{
if (_number % 2 == 0)
Console.WriteLine("Number {0} is Even", _number);
else
Console.WriteLine("Number {0} is Odd", _number);
}

Write a C# program to create a function to calculate the sum of the


individual digits of a given number
using System;

public class functionexcercise


{
public static int SumCal(int number)
{
string n1 = Convert.ToString(number);
int sum = 0;
for (int i = 0; i < n1.Length; i++)
sum += Convert.ToInt32(n1.Substring(i, 1));
return sum;
}

public static void Main()


{
int num;
Console.Write("Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"The sum of the digits of the number {num} is :
{SumCal(num)}");
Console.ReadLine();
}
}

50
C# programming example and solutions
Write a C# program to create a function to check whether a number is
prime or not
using System;

public class functionexcercise


{
public static bool checkprime(int num)
{
for (int i = 2; i < num; i++)
if (num % i == 0)
return false;
return true;
}
public static void Main()
{
Console.Write("Enter a number : ");
int n = Convert.ToInt32(Console.ReadLine());

if (checkprime(n))
Console.WriteLine(n + " is a prime number");
else
Console.WriteLine(n + " is not a prime number");

Console.ReadLine();
}
}

Write a C# program to create a function to display the n number Fibonacci


sequence
using System;

class functionexcercise
{
public static int Fibonaccisequence(int number)
{
int num1 = 0;
int num2 = 1;

for (int i = 0; i < number; i++)


{
int temp = num1;
num1 = num2;
num2 = temp + num2;
}
return num1;
}
public static void Main()
{
Console.Write("Enter a number : ");
int num = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("The Fibonacci series of " + num + " numbers is :");


for (int i = 0; i < num; i++)
{
Console.Write(Fibonaccisequence(i) + " ");
}
Console.ReadLine();
}
}

51
C# programming example and solutions
Write a C# program to create a function to swap the values of two integer
numbers
using System;

public class functionexcercise


{
public static void interchangenumber(ref int num1, ref int num2)
{
int newnum;

newnum = num1;
num1 = num2;
num2 = newnum;
}
public static void Main()
{
int n1, n2;
Console.Write("Enter two number: ");
n1 = Convert.ToInt32(Console.ReadLine());
n2 = Convert.ToInt32(Console.ReadLine());
interchangenumber(ref n1, ref n2);
Console.WriteLine("After swapping the 1st number is : {0} , and the 2nd number
is : {1}", n1, n2);

Console.ReadLine();
}
}

Write a C# program to create a recursive function to find the factorial of a


given number
using System;

class functionexcercise
{
static void Main()
{
decimal fact;
Console.Write("Enter a number : ");
int num = Convert.ToInt32(Console.ReadLine());
fact = Factorial(num);
Console.WriteLine("The factorial of number {0} is {1}", num, fact);
Console.ReadLine();
}
static decimal Factorial(int n1)
{
// The bottom of the recursion
if (n1 == 0)
{
return 1;
}
// Recursive call: the method calls itself
else
{
return n1 * Factorial(n1 - 1);
}
}
}

52
C# programming example and solutions
Write a C# program to Print Binary Equivalent of an Integer using
Recursion
using System;

class Program
{
public static int binaryconversion(int num)
{
int bin;
if (num != 0)
{
bin = (num % 2) + 10 * binaryconversion(num / 2);
Console.Write(bin);
return 0;
}
else
{
return 0;
}
}
public static void Main(string[] args)
{
int num;
Console.WriteLine("Enter a decimal number: ");
num = int.Parse(Console.ReadLine());
Console.Write("The binary equivalent of num is :");
binaryconversion(num);
Console.ReadLine();
}
}

TOPIC 7

All LINQ programs in C# with examples

Write a program in C# to find the positive numbers from a list of numbers


using two where conditions in LINQ Query
using System;
using System.Linq;

class LinqExercise
{
static void Main()
{
int[] numbers = {1, 3, 6, 9, 10, -4, -2, -3, -88, 12, 19, 14
};

var nQuery =
from VrNum in numbers
where VrNum > 0
where VrNum < 10

53
C# programming example and solutions
select VrNum;
Console.Write("\nThe numbers within the range of 1 to 10 are : \n");
foreach (var VrNum in nQuery)
{
Console.Write("{0} ", VrNum);
}
Console.ReadLine();
}
}

Write a program in C# to display the name of the days of a week in LINQ


Query
using System;
using System.Linq;

class LinqExercise
{
static void Main(string[] args)
{
string[] dayWeek = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday" };

var days = from WeekDay in dayWeek


select WeekDay;
Console.WriteLine("Days of a week\n");
foreach (var WeekDay in days)
{
Console.WriteLine(WeekDay);
}
Console.ReadLine();
}
}

Write a program in C# to create a list of numbers and display the numbers


greater than 20 in LINQ Query
using System;
using System.Collections.Generic;

class LinqExercise
{
static void Main(string[] args)
{
List<int> list = new List<int>();
list.Add(10);
list.Add(20);
list.Add(30);
list.Add(40);
list.Add(90);
list.Add(50);
list.Add(70);

Console.WriteLine("\nThe members of the list are : ");


foreach (var lstnum in list)
Console.Write(lstnum + " ");
List<int> FilterList = list.FindAll(x => x > 20 ? true : false);
Console.WriteLine("\n\nThe numbers greater than 20 are : ");

foreach (var num in FilterList)


Console.WriteLine(num);
54
C# programming example and solutions
Console.ReadLine();
}
}

Write a program in C# to find the number of an array and the square of


each number in LINQ Query
using System;
using System.Linq;

class LinqExercise
{
static void Main(string[] args)
{

var arr = new[] { 6, 7, 8, 9 };

var sqaure = from int Number in arr


let SqrNo = Number * Number
select new { Number, SqrNo };

foreach (var a in sqaure)


Console.WriteLine(a);

Console.ReadLine();
}
}

Write a program in C# to display the top n-th records in LINQ Query


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

class LinqExercise11
{
static void Main(string[] args)
{
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(6);
list.Add(7);
list.Add(8);
list.Add(9);
list.Add(10);

Console.WriteLine("\nThe members of the list are : ");


foreach (var lstnum in list)
Console.WriteLine(lstnum + " ");

Console.Write("How many records you want to display? : ");


int num = Convert.ToInt32(Console.ReadLine());

list.Sort();
list.Reverse();

Console.Write("The top {0} records from the list are: \n", num);

55
C# programming example and solutions
foreach (int topn in list.Take(num))
Console.WriteLine(topn);

Console.ReadLine();
}
}

Write a program in C# to display the number and frequency of number


from given array in LINQ Query
using System;
using System.Linq;

class LinqExercise
{
static void Main(string[] args)
{
int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 2, 3, 10 };
Console.Write("The numbers in the array are : \n");
Console.Write("1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 2, 3, 10 \n");

var n = from x in arr


group x by x into y
select y;
Console.WriteLine("\nThe number and the frequency are : \n");
foreach (var arrno in n)
Console.WriteLine($"Number {arrno.Key} appears {arrno.Count()} times");

Console.ReadLine();
}
}

Write a program in C# to display the characters and frequency of character


from given string in LINQ Query
using System;
using System.Linq;

class LinqExercise
{
static void Main(string[] args)
{
string str;

Console.WriteLine("Input the string : ");


str = Console.ReadLine();

var Frequency = from x in str


group x by x into y
select y;
Console.Write("The frequency of the characters are :\n");
foreach (var Arr in Frequency)
{
Console.WriteLine("Character " + Arr.Key + ": " + Arr.Count() + " times");
}
Console.ReadLine();
}
}

56
C# programming example and solutions
Write a program in C# to find the uppercase words in a string in LINQ
Query
using System;
using System.Linq;
using System.Collections.Generic;

class LinqExercise
{
static void Main(string[] args)
{
string str;
Console.Write("Input the string : ");
str = Console.ReadLine();

var ucWord = WordFilt(str);


Console.Write("\nThe upper case words are :\n ");
foreach (string strRet in ucWord)
{
Console.WriteLine(strRet);
}
Console.ReadLine();
}

static IEnumerable<string> WordFilt(string mystr)


{
var upWord = mystr.Split(' ')
.Where(x => string.Equals(x, x.ToUpper(),
StringComparison.Ordinal));

return upWord;

}
}

Write a program in C# to Remove Items from List using remove function


by passing object in LINQ Query
using System;
using System.Collections.Generic;
using System.Linq;

class LinqExercise
{
static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");
list.Add("d");
list.Add("e");

var _result1 = from y in list


select y;
Console.Write("Here is the list of items : \n");
foreach (var tchar in _result1)
{
Console.WriteLine("Char: {0} ", tchar);
}

57
C# programming example and solutions
string newstr = list.FirstOrDefault(n => n == "c");
list.Remove(newstr);

var _result = from z in list


select z;
Console.Write("\nHere is the list after removing the item 'c' from the list :
\n");
foreach (var c in _result)
{
Console.WriteLine("Char: {0} ", c);
}

Console.ReadLine();
}
}

Write a program in C# to remove a range of items from a list by passing the


start index and number of elements to remove in LINQ Query
using System;
using System.Collections.Generic;
using System.Linq;

class LinqExercise21
{
static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");
list.Add("d");
list.Add("e");
list.Add("f");

var result = from y in list


select y;
Console.Write("Here is the list of items : \n");
foreach (var tchar in result)
{
Console.WriteLine("Char: {0} ", tchar);
}

list.RemoveRange(1, 4);

var _result = from n in list


select n;
Console.Write("\nHere is the list after removing the four items starting from
the list : \n");
foreach (var removeChar in _result)
{
Console.WriteLine("Char: {0} ", removeChar);
}

Console.ReadLine();
}
}

58
C# programming example and solutions
Write a program in C# to generate a Cartesian Product of two sets in LINQ
Query
using System;
using System.Linq;
using System.Collections.Generic;

class LinqExercise23
{
public static void Main(string[] args)
{
char[] charlist = { 'A', 'B', 'C' };
int[] numlist = { 1, 2, 3 };

var cartesianProduct = from letterlist in charlist


from numberlist in numlist
select new { letterlist, numberlist };

Console.Write("The Cartesian Product are : \n");


foreach (var productItem in cartesianProduct)
{
Console.WriteLine(productItem);
}
Console.ReadLine();
}
}

Write a program in C# to arrange the distinct elements in the list in


ascending order in LINQ Query
using System;
using System.Linq;
using System.Collections.Generic;

class LinqExercise
{
static void Main(string[] args)
{
var itemlist = (from c in Item_Mast.Getitem()
select c.ItemDes)
.Distinct()
.OrderBy(x => x);

foreach (var item in itemlist)


Console.WriteLine(item);
Console.ReadLine();
}
}
class Item_Mast
{
public int ItemId { get; set; }
public string ItemDes { get; set; }

public static List<Item_Mast> Getitem()


{
List<Item_Mast> list = new List<Item_Mast>();
list.Add(new Item_Mast() { ItemId = 1, ItemDes = "AUDI" });
list.Add(new Item_Mast() { ItemId = 2, ItemDes = "BMW" });
list.Add(new Item_Mast() { ItemId = 3, ItemDes = "BUGATTI" });
list.Add(new Item_Mast() { ItemId = 4, ItemDes = "HONDA" });
list.Add(new Item_Mast() { ItemId = 6, ItemDes = "FERRARI" });

59
C# programming example and solutions
list.Add(new Item_Mast() { ItemId = 6, ItemDes = "AUDI" });
list.Add(new Item_Mast() { ItemId = 5, ItemDes = "JAGUAR" });
list.Add(new Item_Mast() { ItemId = 6, ItemDes = "FERRARI" });
return list;
}
}

TOPIC 8
All string programs in C# with examples

Write a C# program to accept a string from keyboard and print it


using System;

public class StringExercise


{
public static void Main()
{
string str;

Console.Write("Enter the string : ");


str = Console.ReadLine();
Console.Write("The string you entered is : {0}\n", str);

Console.ReadLine();
}
}

Write a C# program to Separate the individual characters from a string


using System;

public class StringExercise


{
public static void Main()
{
string str;
int length = 0;

Console.Write("Input the string : ");


str = Console.ReadLine();
Console.Write("The characters of the string are : ");
while (length <= str.Length - 1)
{
Console.Write("{0} ", str[length]);
length++;
}
Console.ReadLine();
}
}

60
C# programming example and solutions
Write a C# program to find the length of a string without using library
function
using System;

public class StringExercise


{
public static void Main()
{
string str;
int length = 0;

Console.Write("Input the string : ");


str = Console.ReadLine();

foreach (char chr in str)


length += 1;

Console.Write("Length of the string is : {0}\n\n", length);

Console.ReadLine();
}
}

Write a C# program to count a total number of alphabets, digits and special


characters in a string
using System;

public class StringExercise


{
public static void Main()
{
string str;
int alphabet, digit, specialchar, i, l;
alphabet = digit = specialchar = i = 0;

Console.Write("Enter the string : ");


str = Console.ReadLine();
l = str.Length;

while (i < l)
{
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
alphabet++;
else if (str[i] >= '0' && str[i] <= '9')
digit++;
else
specialchar++;

i++;
}

Console.Write("Number of Alphabets in the string is : {0}\n", alphabet);


Console.Write("Number of Digits in the string is : {0}\n", digit);
Console.Write($"Number of Special characters in the string is :
{specialchar}");

Console.ReadLine();
}
}

61
C# programming example and solutions
Write a C# program to print individual characters of the string in reverse
order
using System;

public class StringExercise


{
public static void Main()
{
string str;
int length = 0;

Console.Write("Enter the string : ");


str = Console.ReadLine();

length = str.Length - 1;
Console.Write("The characters of the string in reverse are : \n");
while (length >= 0)
{
Console.Write("{0} ", str[length]);
length--;
}
Console.ReadLine();
}
}

Write a C# program to copy one string to another string


using System;

public class StringExercise


{
public static void Main()
{
string str1;
int i, length;

Console.Write("Enter the string : ");


str1 = Console.ReadLine();

length = str1.Length;
string[] str2 = new string[length];

/* Copies string1 to string2 character by character */


i = 0;
while (i < length)
{
string tmp = str1[i].ToString();
str2[i] = tmp;
i++;
}
Console.Write("\nThe First string is : {0}\n", str1);
Console.Write("The Second string is : {0}\n", string.Join("", str2));
Console.Write("Number of characters copied : {0}\n\n", i);

Console.ReadLine();
}
}

62
C# programming example and solutions
Write a C# program to count a total number of vowel or consonant in a
string
using System;

public class StringExercise


{
public static void Main()
{
string str;
int i, length, vowel, consonant;

Console.Write("Enter the string : ");


str = Console.ReadLine();

vowel = 0;
consonant = 0;
length = str.Length;

for (i = 0; i < length; i++)


{

if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' ||


str[i] == 'u' || str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' ||
str[i] == 'U')
{
vowel++;
}
else if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <=
'Z'))
{
consonant++;
}
}
Console.Write("\nThe total number of vowel in the string is : {0}\n", vowel);
Console.Write("The total number of consonant in the string is : {0}\n\n",
consonant);

Console.ReadLine();
}
}

63
C# programming example and solutions
Write a C# program to find maximum occurring character in a string
using System;

public class Exercise10


{
public static void Main()
{
string str;
int[] frequency = new int[255];
int i = 0, max, l;
int ascii;

Console.Write("Enter the string : ");


str = Console.ReadLine();
l = str.Length;

for (i = 0; i < 255; i++)


{
frequency[i] = 0;
}
// Reading frequency of each characters
i = 0;
while (i < l)
{
ascii = (int)str[i];
frequency[ascii] += 1;

i++;
}

max = 0;
for (i = 0; i < 255; i++)
{
if (i != 32)
{
if (frequency[i] > frequency[max])
max = i;
}
}
Console.Write("The Highest frequency of character '{0}' is appearing for
number of times : {1} \n\n", (char)max, frequency[max]);

Console.ReadLine();
}
}

Write a C# program to read a string through the keyboard and sort it using
bubble sort
using System;

public class Stringexercise


{
public static void Main()
{
string[] arr1;
string temp;
int num, i, j, lenghth;

Console.Write("Input number of strings :");

64
C# programming example and solutions
num = Convert.ToInt32(Console.ReadLine());
arr1 = new string[num];
Console.Write("Input {0} strings below :\n", num);
for (i = 0; i < num; i++)
{
arr1[i] = Console.ReadLine();
}
lenghth = arr1.Length;

for (i = 0; i < lenghth; i++)


for (j = 0; j < lenghth - 1; j++)
{
if (arr1[j].CompareTo(arr1[j + 1]) > 0)
{
temp = arr1[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = temp;
}
}
Console.Write("\n\nAfter sorting the array appears like : \n");
for (i = 0; i < lenghth; i++)
Console.WriteLine(arr1[i] + " ");

Console.ReadLine();
}
}

Write a C# program to sort a string array in ascending order


using System;

public class Exercise11


{
public static void Main()
{
string str;
char[] arr1;
char ch;
int i, j, length;
Console.Write("Enter the string : ");
str = Console.ReadLine();
length = str.Length;
arr1 = str.ToCharArray(0, length);

for (i = 1; i < length; i++)


for (j = 0; j < length - i; j++)
if (arr1[j] > arr1[j + 1])
{
ch = arr1[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = ch;
}
Console.Write("After sorting the string appears like : \n");
foreach (char c in arr1)
{
ch = c;
Console.Write("{0} ", ch);
}

Console.ReadLine();
}
}

65
C# programming example and solutions
Write a C# program to compare (less than, greater than, equal to ) two
substrings
using System;

class StringExample
{
public static void Main()
{
string str1 = "computer";
string str2 = "system";
string str;
int result;

Console.WriteLine();
Console.WriteLine("str1 = '{0}', str2 = '{1}'", str1, str2);
result = string.Compare(str1, 2, str2, 0, 2);
str = ((result < 0) ? "less than" : ((result > 0) ? "greater than" : "equal
to"));
Console.Write("Substring '{0}' in '{1}' is ", str1.Substring(2, 2), str1);
Console.Write("{0} ", str);
Console.WriteLine("substring '{0}' in '{1}'.", str2.Substring(0, 2), str2);

Console.ReadLine();
}
}

Write a C# program to find the number of times a substring appears in the


given string
using System;

public class stringexercise


{
public static void Main()
{
string str;
string findstring;
int start = 0;
int cnt = -1;
int index = -1;

Console.Write("Input the original string : ");


str = Console.ReadLine();
Console.Write("Input the string to be searched for : ");
findstring = Console.ReadLine();

while (start != -1)


{
start = str.IndexOf(findstring, index + 1);
cnt += 1;
index = start;
}
Console.Write("The string '{0}' occurs " + cnt + " times.\n", findstring);

Console.ReadLine();
}
}

66
C# programming example and solutions
Write a C# program to check the username and password
using System;

public class Stringexercise


{
public static void Main()
{
string username, password;
int ctr = 0;
do
{
Console.Write("Input a username: ");
username = Console.ReadLine();

Console.Write("Input a password: ");


password = Console.ReadLine();

if (username != "abcd" || password != "1234")


ctr++;
else
ctr = 1;

}
while ((username != "admin" || password != "123456") && (ctr != 3));

if (ctr == 3)
Console.WriteLine("\nLogin attemp three or more times. Try later!");
else
Console.WriteLine("\nThe password entered successfully!");

Console.ReadLine();
}
}

Write a C# program to read a sentence and replace lowercase characters by


uppercase and vice-versa
using System;

public class Stringexercise


{
public static void Main()
{
string str1;
char[] arr1;
int length, i;
length = 0;
char ch;
Console.Write("Enter the string : ");
str1 = Console.ReadLine();
length = str1.Length;
arr1 = str1.ToCharArray(0, length); // Converts string into char array.

Console.Write("\nAfter conversion, the string is: ");


for (i = 0; i < length; i++)
{
ch = arr1[i];
if (Char.IsLower(ch)) // check whether the character is lowercase
Console.Write(Char.ToUpper(ch)); // Converts lowercase character to
uppercase.

67
C# programming example and solutions
else
Console.Write(Char.ToLower(ch)); // Converts uppercase character to
lowercase.
}
Console.ReadLine();
}
}

Write a C# program to check whether a given substring is present in the


given string
using System;

public class Stringexercise


{
public static void Main()
{
string str1, str2;
bool m;

Console.Write("Enter the string : ");


str1 = Console.ReadLine();

Console.Write("Input the substring to search : ");


str2 = Console.ReadLine();
m = str1.Contains(str2);
if (m) // check boolean value is true or false.
Console.WriteLine("The substring exists in the string.");
else
Console.WriteLine("The substring is not exists in the string.");

Console.ReadLine();
}
}

68

You might also like