C# Examples on Fundamental Mathematical Operations
1) C# Program to Check whether the Entered Number is Even or Odd
This is a C# Program to check whether the entered number is even or odd.
This C# Program checks if a given integer is Odd or Even.
Here if a given number is divisible by 2 with the remainder 0 then the number is an Even number. If the number is not divisible by 2 then that number will be an Odd number.
Here is source code of the C# program which checks a given integer is odd or even. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
/* * C# Program to Check whether the Entered Number is Even or Odd */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace check1 { class Program { static void Main(string[] args) { int i; Console.Write("Enter a Number : "); i = int.Parse(Console.ReadLine()); if (i % 2 == 0) { Console.Write("Entered Number is an Even Number"); Console.Read(); } else { Console.Write("Entered Number is an Odd Number"); Console.Read(); } } } } |
In this C# program, we are reading the number using ‘i’ integer variable. If condition statement is used to check the number is even and odd. For even number the modulus of the value of ‘i’ variable by 2 is equal to zero, if the condition is true then print the statement as even number.
Otherwise, if the condition is false then execute the else statement, for odd number the modulus of the value of ‘i’ variable by 2 is not equal to zero, if the condition is true then execute the statement and print the statement as odd number.
1 2 3 4 |
Enter a Number : 25 Entered Number is an Odd Number |
2) C# Program to Swap 2 Numbers
This is a C# Program to swap 2 numbers.
This C# Program Swaps 2 Numbers.
It obtains two numbers from the user and swaps the numbers using a temporary variable.
Here is source code of the C# program that swaps two numbers. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
/* * C# Program to Swap two Numbers */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { class Program { static void Main(string[] args) { int num1, num2, temp; Console.Write("\nEnter the First Number : "); num1 = int.Parse(Console.ReadLine()); Console.Write("\nEnter the Second Number : "); num2 = int.Parse(Console.ReadLine()); temp = num1; num1 = num2; num2 = temp; Console.Write("\nAfter Swapping : "); Console.Write("\nFirst Number : "+num1); Console.Write("\nSecond Number : "+num2); Console.Read(); } } } |
In this C# program, we are reading the numbers using ‘num1’ and ‘num2’ variables respectively. Interchange the values of the ‘num1’ and ‘num2’ variables using temporary variable ‘t’. Print the swapped value of 2 numbers.
1 2 3 4 5 6 7 |
Enter the First Number : 23 Enter the Second Number : 25 After Swapping : First Number : 25 Second Number : 23 |
3) C# Program to Get a Number and Display the Sum of the Digits
This is a C# Program to get a number and display the sum of the digits.
This C# Program Gets a Number and Display the Sum of the Digits.
The digit sum of a given integer is the sum of all its digits.
Here is source code of the C# Program to Get a Number and Display the Sum of the Digits. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/* * C# Program to Get a Number and Display the Sum of the Digits */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { class Program { static void Main(string[] args) { int num, sum = 0, r; Console.WriteLine("Enter a Number : "); num = int.Parse(Console.ReadLine()); while (num != 0) { r = num % 10; num = num / 10; sum = sum + r; } Console.WriteLine("Sum of Digits of the Number : "+sum); Console.ReadLine(); } } } |
In this C# program, we are reading a number using ‘num’ variable. Using while loop computes the sum of the digits. The digit sum of a given integer is the sum of all its digits.
Compute the modulus of the value of ‘num’ variable by 10. Divide the value of ‘num’ variable by 10. Compute the summation of the value of ‘sum’ variable with the value of ‘r’ variable. Print the sum of the digits.
1 2 3 4 |
Enter a Number : 123 Sum of Digits of the Number : 6 |
4) C# Program to Get a Number and Display the Number with its Reverse
This is a C# Program to get a number and display the number with its reverse.
This C# Program Gets a Number and Display the Number with its Reverse.
Here we obtain a number from the user and display the digits in the reverse order.
Here is source code of the C# Program to Get a Number and Display the Number with its Reverse. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/* * C# Program to Get a Number and Display the Number with its Reverse */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { class Program { static void Main(string[] args) { int num, reverse = 0; Console.WriteLine("Enter a Number : "); num = int.Parse(Console.ReadLine()); while (num != 0) { reverse = reverse * 10; reverse = reverse + num % 10; num = num / 10; } Console.WriteLine("Reverse of Entered Number is : "+reverse); Console.ReadLine(); } } } |
In this C# program, we are reading the number using ‘num’ variable. Multiply the value of ‘reverse’ variable by 10 and add this value of reverse variable with the modulus of the value of ‘reverse’ variable by 10. Compute the division of the value of ‘num’ variable by 10. Print the number with its reverse order.
1 2 3 4 |
Enter a Number : 123 Reverse of Entered Number : 321 |
5) C# Program to Print a Binary Triangle
This is a C# Program to Print a binary triangle.
This C# Program Prints a Binary Triangle.
Binary Triangle is a Triangle formed with 1’s and 0’s.Number of rows in the binary triangle is obtained from the user.
Here is source code of the C# Program to Print a Binary Triangle. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/* * C# Program to Print a BinaryTriangle */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { class Program { public static void Main(String[] args) { int p, lastInt = 0, input; Console.WriteLine("Enter the Number of Rows : "); input = int.Parse(Console.ReadLine()); for (int i = 1; i <= input; i++) { for (p = 1; p <= i; p++) { if (lastInt == 1) { Console.Write("0"); lastInt = 0; } else if (lastInt == 0) { Console.Write("1"); lastInt = 1; } } Console.Write("\n"); } Console.ReadLine(); } } } |
In this C# program, we are reading the number of rows using ‘input’ variable. Binary Triangle is a triangle formed with 1’s and 0’s. Number of rows in the binary triangle is obtained from the user. Nested-if else condition statement is used to check that the value of ‘lastInt’ variable is equal to 1. If the condition is true, then execute the statement print the value as 0.
Otherwise, if the condition is false, then execute the else if condition statement and check the value of ‘lastInt’ variable is equal to 0. If the condition is true, then execute the statement and print the statement value as 1 and again initialize the value of ‘lastInt’ variable as 1. Print the Binary Triangle from the given number.
1 2 3 4 5 6 7 8 |
Enter the Number of Rows : 5 1 01 010 1010 10101 |
6) C# Program to Count the Number of 1’s in the Entered Number
This is a C# Program to count the number of 1’s in the entered number.
This C# Program Counts the Number of 1’s in the Entered Number.
Here the array of numbers are obtained with its limit and number of 1’s in it is counted and displayed.
Here is source code of the C# Program to Count the Number of 1’s in the Entered Number. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/* * C# Program to Count the Number of 1's in the Entered Number */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication16 { class Program { static void Main(string[] args) { int m, count = 0; Console.WriteLine("Enter the Limit : "); m = int.Parse(Console.ReadLine()); int[] a = new int[m]; Console.WriteLine("Enter the Numbers :"); for (int i = 0; i < m; i++) { a[i] = Convert.ToInt32(Console.ReadLine()); } foreach (int o in a) { if (o == 1) { count++; } } Console.WriteLine("Number of 1's in the Entered Number : "); Console.WriteLine(count); Console.ReadLine(); } } } |
In this C# program, we are reading the limit of the ‘array’ size. Using for loop enter the coefficient element values of an array. If condition statement, is used to check that the value of ‘i’ variable is equal to 1. If the condition is true then execute the statement and increment the value of the ‘count’ variable. Print the counted number of 1’s in the entered number.
1 2 3 4 5 6 7 8 9 10 |
Enter the Limit : 5 Enter the Numbers : 1 2 1 4 1 Number of 1's in the Entered Number : 3 |
C# Examples on Date Formats and Years
7) String Format for DateTime
Custom DateTime Formatting
There are following custom format specifiers y
(year), M
(month), d
(day), h
(hour 12), H
(hour 24), m
(minute), s
(second), f
(second fraction), F
(second fraction, trailing zeroes are trimmed), t
(P.M or A.M) and z
(time zone).
Following examples demonstrate how are the format specifiers rewritten to the output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// create date time 2008-03-09 16:05:07.123 DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123); String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24 String.Format("{0:m mm}", dt); // "5 05" minute String.Format("{0:s ss}", dt); // "7 07" second String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M. String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone |
You can use also date separator /
(slash) and time sepatator :
(colon). These characters will be rewritten to characters defined in the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator.
1 2 3 4 5 |
// date separator in german culture is "." (so "/" changes to ".") String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9/3/2008 16:05:07" - english (en-US) String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07" - german (de-DE) |
Here are some examples of custom date and time formatting:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// month/day numbers without/with leading zeroes String.Format("{0:M/d/yyyy}", dt); // "3/9/2008" String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008" // day/month names String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008" String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008" // two/four digit year String.Format("{0:MM/dd/yy}", dt); // "03/09/08" String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008" |
8) Standard DateTime Formatting
In DateTimeFormatInfo there are defined standard patterns for the current culture. For example property ShortTimePattern is string that contains value h:mm tt
for en-US culture and value HH:mm
for de-DE culture.
Following table shows patterns defined in DateTimeFormatInfo and their values for en-US culture. First column contains format specifiers for the String.Format method.
Specifier | DateTimeFormatInfo property | Pattern value (for en-US culture) |
---|---|---|
t |
ShortTimePattern | h:mm tt |
d |
ShortDatePattern | M/d/yyyy |
T |
LongTimePattern | h:mm:ss tt |
D |
LongDatePattern | dddd, MMMM dd, yyyy |
f |
(combination of D and t ) |
dddd, MMMM dd, yyyy h:mm tt |
F |
FullDateTimePattern | dddd, MMMM dd, yyyy h:mm:ss tt |
g |
(combination of d and t ) |
M/d/yyyy h:mm tt |
G |
(combination of d and T ) |
M/d/yyyy h:mm:ss tt |
m , M |
MonthDayPattern | MMMM dd |
y , Y |
YearMonthPattern | MMMM, yyyy |
r , R |
RFC1123Pattern | ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*) |
s |
SortableDateTimePattern | yyyy'-'MM'-'dd'T'HH':'mm':'ss (*) |
u |
UniversalSortableDateTimePattern | yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*) |
(*) = culture independent |
Following examples show usage of standard format specifiers in String.Format method and the resulting output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
String.Format("{0:t}", dt); // "4:05 PM" ShortTime String.Format("{0:d}", dt); // "3/9/2008" ShortDate String.Format("{0:T}", dt); // "4:05:07 PM" LongTime String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime String.Format("{0:m}", dt); // "March 09" MonthDay String.Format("{0:y}", dt); // "March, 2008" YearMonth String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123 String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime |
9) C# Program to Check Whether the Entered Year is a Leap Year or Not
This is a C# Program to check whether the entered year is a leap year or not.
This C# Program Checks Whether the Entered Year is a Leap Year or Not.
When A year is divided by 4. If the remainder becomes 0 then the year is called a leap year.
Here is source code of the C# Program to Check Whether the Entered Year is a Leap Year or Not. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
/* * C# Program to Check Whether the Entered Year is a Leap Year or Not */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { class leapyear { static void Main(string[] args) { leapyear obj = new leapyear(); obj.readdata(); obj.leap(); } int y; public void readdata() { Console.WriteLine("Enter the Year in Four Digits : "); y = Convert.ToInt32(Console.ReadLine()); } public void leap() { if ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) { Console.WriteLine("{0} is a Leap Year", y); } else { Console.WriteLine("{0} is not a Leap Year", y); } Console.ReadLine(); } } } |
In this C# program, we are reading the value of year using ‘year’ variable. When A year is divided by 4. If the remainder becomes 0, then the year is called a leap year.
The Nested-If else condition statement is used to check the given year is leap year or not. In if condition statement the modulus of the value of ‘year’ variable by 4 is equal to 0, and the modulus of the value of ‘year’ variable by 100 is not equal to 0 using logical AND operators.
Otherwise, if the condition is false, then execute the else if condition statement. Compute the modulus of the value of ‘year’ variable by 400 is equal to 0 using logical OR operators. If the condition is true then print the statement as leap year. Otherwise, if the condition is false then execute the else statement. Print the statement as not leap year.
1 2 3 4 |
Enter the Year in Four Digits : 1004 1004 is a Leap Year |
10) C# Program to Display the Date in Various Formats
This is a C# Program to display the date in various formats.
This C# Program Displays the Date in Various Formats.
Here the Date is Displayed in various Formats.
Here is source code of the C# Program to Display the Date in Various Formats . The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/* * C# Program to Display the Date in Various Formats */ using System; namespace DateAndTime { class Program { static int Main() { DateTime date = new DateTime(2013,6, 23); Console.WriteLine("Some Date Formats : "); Console.WriteLine("Date and Time: {0}", date); Console.WriteLine(date.ToString("yyyy-MM-dd")); Console.WriteLine(date.ToString("dd-MMM-yy")); Console.WriteLine(date.ToString("M/d/yyyy")); Console.WriteLine(date.ToString("M/d/yy")); Console.WriteLine(date.ToString("MM/dd/yyyy")); Console.WriteLine(date.ToString("MM/dd/yy")); Console.WriteLine(date.ToString("yy/MM/dd")); Console.Read(); return 0; } } } |
In this C# Program, we are creating the date object to the DateTime() constructor to get any date. The Date Format Specifier is used to represent a date in various ways. Representation of a date can be done by one of two Date Format Specifiers that is a Short Date Format Specifier or a Long Date Format Specifier.
1 2 3 4 5 6 7 8 9 10 11 |
Some Date Formats : Date and Time : 6/23/2013 12:00:00 AM 2013-06-23 23-Jun-13 6/23/2013 6/23/13 06/23/2013 06/23/13 13/06/23 |
11) C# Program to Compare Two Dates
This is a C# Program to compare two dates.
This C# Program Compares Two Dates.
Here two dates are compared and the date which occurs first is displayed.
Here is source code of the C# Program to Compare Two Dates. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* * C# Program to Campare Two Dates */ using System; namespace DateAndTime { class Program { static int Main() { DateTime sd = new DateTime(2010, 10, 12); Console.WriteLine("Starting Date : {0}", sd); DateTime ed = sd.AddDays(10); Console.WriteLine("Ending Date : {0}", ed); if (sd < ed) Console.WriteLine("{0} Occurs Before {1}", sd, ed); Console.Read(); return 0; } } } |
In this C# program, the DateTime() constructor is used to create the format of the date. If condition statement is used to compare the two dates and the date which occurs first is displayed.
1 2 3 4 5 |
Starting Date : 10/11/2010 12:00:00 AM Ending Date : 10/21/2010 12:00:00 AM 10/11/2010 12:00:00 Am Occurs Before 10/21/2010 12:00:00 AM |
12) C# Program to Display the ATM Transaction
This is a C# Program to display the atm transaction.
This C# Program Displays the ATM Transaction.
Here The types of ATM transaction are
1) Balance checking
2) Cash withdrawal
3) Cash deposition.
You can opt any of the above transaction according to your need of transaction.
Here is source code of the C# Program to Display the ATM Transaction. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/* * C# Program to Display the ATM Transaction */ using System; class program { public static void Main() { int amount = 1000, deposit, withdraw; int choice, pin = 0, x = 0; Console.WriteLine("Enter Your Pin Number "); pin = int.Parse(Console.ReadLine()); while (true) { Console.WriteLine("********Welcome to ATM Service**************\n"); Console.WriteLine("1. Check Balance\n"); Console.WriteLine("2. Withdraw Cash\n"); Console.WriteLine("3. Deposit Cash\n"); Console.WriteLine("4. Quit\n"); Console.WriteLine("*********************************************\n\n"); Console.WriteLine("Enter your choice: "); choice = int.Parse(Console.ReadLine()); switch (choice) { case 1: Console.WriteLine("\n YOUR BALANCE IN Rs : {0} ", amount); break; case 2: Console.WriteLine("\n ENTER THE AMOUNT TO WITHDRAW: "); withdraw = int.Parse(Console.ReadLine()); if (withdraw % 100 != 0) { Console.WriteLine("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100"); } else if (withdraw > (amount - 500)) { Console.WriteLine("\n INSUFFICENT BALANCE"); } else { amount = amount - withdraw; Console.WriteLine("\n\n PLEASE COLLECT CASH"); Console.WriteLine("\n YOUR CURRENT BALANCE IS {0}", amount); } break; case 3: Console.WriteLine("\n ENTER THE AMOUNT TO DEPOSIT"); deposit = int.Parse(Console.ReadLine()); amount = amount + deposit; Console.WriteLine("YOUR BALANCE IS {0}", amount); break; case 4: Console.WriteLine("\n THANK U USING ATM"); break; } } Console.WriteLine("\n\n THANKS FOR USING OUT ATM SERVICE"); } } |
In this C# program, we are performing the ATM Transaction. The types of ATM transaction are 1) Balance Checking, 2) Cash Withdrawal,3) Cash Deposition.
We are reading the pin number using ‘pin’ variable. If condition statement is used to check the value of ‘pin’ variable is not equal to 1520. If the condition is true, then execute the statement. Print the statement as please enter valid password. Do-While statement is used to print the types of ATM transaction.
The ‘choice’ variable is used to select anyone types of transaction. Use the value of ‘choice’ variable in the switch case statement. Case1 is used to print the available balance from the value of ‘amount’ variable. To withdraw the amount case2 statement is used.
Read the amount to withdraw using ‘withdraw’ variable. Nested If-Else condition statement is used to check the modulus of the value of ‘withdraw’ variable by 100 is not equal to 0. If the condition is true then print the statement as “please enter the amount in multiples of 100”.
Otherwise, if the condition is false, then execute the else if condition statement. Check the difference between the values of ‘amount’ variable by 500 is less than the value of ‘withdraw’ variable. Once the condition is true then execute the statement and print the statement as insufficient balance.
Otherwise, if the condition is false, execute the else condition statement. Assign the difference between the values of ‘amount’ variable by the value of ‘withdraw’ variable. Print the statement as please collect cash and your current balance using the value of ‘amount’ variable value.
To deposit the amount case3 statement is used to get the amount to deposit using deposit variable and assigns the resulted value to amount variable. Compute the summation of the value of ‘amount’ variable with the value of ‘deposit’ variable. Print the statement as the balance using amount variable value.
Runtime Test Cases
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Enter Your Pin Number 123 ********Welcome to ATM Service************** 1. Check Balance 2. Withdraw Cash 3. Deposit Cash 4. Quit ********************************************* Enter your choice: 1 YOUR BALANCE IN Rs : 1000 |
13) C# Program to Generate Random Numbers
This is a C# Program to generate random numbers.
This C# Program Generates Random Numbers.
Here random numbers are generated using the Random class and the next() in it.
Here is source code of the C# Program to Generate Random Numbers. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* * C# Program to Generate Random Numbers */ using System; class Program { static void Main() { Console.WriteLine("Some Random Numbers that are generated are : "); for (int i = 1; i < 10; i++) { Randfunc(); } } static Random r = new Random(); static void Randfunc() { int n = r.Next(); Console.WriteLine(n); Console.ReadLine(); } } |
In this C# program using for loop we are calling the Randfun() function. Create the random variable object ‘r’, then using ‘n’ variable we are calling the next() function. Print the random numbers.
C# Examples on Bitwise and Swapping Operations
14) C# Program to Accept the Height of a Person & Categorize as Tall, Dwarf or Average
This is a C# Program to accept the height of a person & categorize as tall, dwarf or average.
This C# Program accepts the height of a person & categorizes it as Tall, Dwarf or Average.
Here the program accepts height of a person in centimeters. Then, it categorizes it based on the height. If height is less than 150 centimeter, then the person is dwarf and if the height is between 151 to 165 then it is categorized as average and if the height is between 165 to 175 then it is categorized as tall.
Here is source code of the C# Program to Accept the Height of a Person & Categorize as Tall, Dwarf or Average. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* * C# Program to Accept the Height of a Person & Categorize as * Tall, Dwarf or Average */ using System; class program { public static void Main() { float height; Console.WriteLine("Enter the Height (in centimeters) \n"); height = int.Parse(Console.ReadLine()); if (height < 150.0) Console.WriteLine("Dwarf \n"); else if ((height >= 150.0) && (height <= 165.0)) Console.WriteLine(" Average Height \n"); else if ((height >= 165.0) && (height <= 195.0)) Console.WriteLine("Taller \n"); else Console.WriteLine("Abnormal height \n"); } } |
In this C# program, we are reading the height of a person using ‘height’ variable. Nested-if else condition statement is used to print the height of a person.
If condition statement is used to check the height of the person is less than 150.00 centimeters. If the condition is true then execute the statement and print the height of the person. Otherwise if the condition is false, then execute else if condition statement. Check the condition that the height of the person is between 150.00 to 165.00 centimeters using logical AND operator.
If it’s true then it will execute the statement, otherwise, another else if condition statement that height of the person should between 165.00 to 195.00 centimeters. If the condition is true, then execute the statement and print the height of the person.
1 2 3 4 5 |
Enter the Height (in centimeters) 165 Average Height |
15) C# Program to Find the Frequency of the Word ʺtheʺ in a given Sentence
This is a C# Program to find the frequency of the word ʺtheʺ in a given sentence.
This C# Program Finds the Frequency of the Word ʺtheʺ in a given Sentence.
Here the frequency of ‘the’ in the given string is found.
Here is source code of the C# Program to Find the Frequency of the Word ʺtheʺ in a given Sentence. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/* * C# Program to Find the Frequency of the Word ʺtheʺ in a given Sentence */ using System; class program { public static void Main() { string s1; Console.WriteLine("Enter the String : "); s1 = Console.ReadLine(); Console.WriteLine(counting.CountStringOccurrences(s1, "the")); Console.ReadLine(); } } public static class counting { public static int CountStringOccurrences(string text, string pattern) { int count = 0; int i = 0; while ((i = text.IndexOf(pattern, i)) != -1) { i += pattern.Length; count++; } return count; } } |
In this C# program, we are reading the string using ‘s1’ variable. The CountStringOccurrences() function is used to find the frequency of the word “the” in a given sentence from the counting variable. While loop is used to check the IndexOf() function value is not equal to -1.
If the condition is true then execute the statement. Compute the summation of the value of ‘i’ variable with the value of ‘pattern.length’ variable and increment the value of count variable value by 1. Print the frequency of the word “the” in a given sentence.
1 2 3 4 5 |
Enter the String : we only loop once over the source, which reduces the cost of the method. 3 |
16) C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation
This is a C# Program to swap the contents of two numbers using bitwise xor operation.
This C# Program Swaps the Contents of two Numbers using Bitwise XOR Operation.
Take two inputs from the user and perform Bitwise XOR Operation as shown in the program below.
Here is source code of the C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* * C# Program to Swap the Contents of two Numbers using Bitwise XOR Operation */ using System; class program { public static void Main() { int i, k; Console.WriteLine("Enter two integers \n"); i = int.Parse(Console.ReadLine()); k = int.Parse(Console.ReadLine()); Console.WriteLine("\n Before swapping i= {0} and k = {1}", i, k); i = i ^ k; k = i ^ k; i = i ^ k; Console.WriteLine("\n After swapping i= {0} and k = {1}", i, k); Console.ReadLine(); } } |
In this C# Program, we are reading two integers using ‘i’ and ’k’ integer variables. The bitwise XOR operation is used between ‘i’ and ‘k’ integer variable values. Assign the value to ‘i’ variable and perform the bitwise XOR operation. And assign the value to ‘k’ variable and again to ‘i’ variable. Print the contents of two numbers using bitwise XOR operation.
1 2 3 4 5 6 7 |
Enter two integers 23 34 Before swapping i= 23 and k = 34 After swapping i= 34 and k = 23 |
C# Examples on Access Specifiers
17) C# Program to Illustrate the Use of Access Specifiers
This is a C# Program to illustrate the use of access specifiers.
This C# Program Illustrates the Use of Access Specifiers.
Here the four types of access specifiers are explained by assigning values.
Here is source code of the C# Program to Illustrate the Use of Access Specifiers. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/* * C# Program to Illustrate the Use of Access Specifiers */ using System; namespace accessspecifier { class Program { static void Main(string[] args) { two B = new two(); B.show(); } } class one { private int x; protected int y; internal int z; public int a; protected internal int b; } class two : one { public void show() { Console.WriteLine("Values are : "); //x=10; y = 20; z = 30; a = 40; b = 50; // Console.WriteLine(+x); // Error x is not accessible Console.WriteLine(y); Console.WriteLine(z); Console.WriteLine(a); Console.WriteLine(b); Console.ReadLine(); } } } |
This C# program is used to illustrate the use of access specifiers. Create the object variable to the class two. In class one, explain the four types of access specifiers by assigning values. Then we are displaying the output of the program.
1 2 3 4 5 6 7 |
Values are : 20 30 40 50 |
18) C# Program to Print a Diamond Using Nested Loop
This is a C# Program to print a diamond using nested loop.
This C# Program Prints a Diamond Using Nested Loop.
Take input from the user and go on to draw the diamond pattern as shown in the program below.
Here is source code of the C# Program to Print a Diamond Using Nested Loop. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/* * C# Program to Print the Sum of all the Multiples of 3 and 5 */ using System; class program { public static void Main() { int number, i, k, count = 1; Console.Write("Enter number of rows\n"); number = int.Parse(Console.ReadLine()); count = number - 1; for (k = 1; k <= number; k++) { for (i = 1; i <= count; i++) Console.Write(" "); count--; for (i = 1; i <= 2 * k - 1; i++) Console.Write("*"); Console.WriteLine(); } count = 1; for (k = 1; k <= number - 1; k++) { for (i = 1; i <= count; i++) Console.Write(" "); count++; for (i = 1; i <= 2 * (number - k) - 1; i++) Console.Write("*"); Console.WriteLine(); } Console.ReadLine(); } } |
In this C# program, we are reading the number of rows using ‘number’ variable. Compute the value of ‘count’ variable as the difference between the values of ‘number’ variable by 1.
Using for loop initialize the value of ‘k’ variable as 1 and check the condition that the value of ’k’ variable is less than or equal to the value of ‘number’ variable. If the condition is true then execute the iteration of the loop.
Another for loop is used to check that the value of ‘i’ variable is less than or equal to the value of ‘count’ variable. If the condition is true, then execute the iteration of the loop and decrement the value of ‘count’ variable by 1.
Using another for loop initialize the value of ‘i’ variable as 1 and check the multiplication of the value 2 with the difference of the value of ‘k’ variable and the difference of resulted value by1, are equal using logical AND operator. If the condition is true, then execute the iteration of the loop. Print the * Symbol.
Another for loop is used by initialize the value of ‘k’ variable as 1. Check the value of ‘k’ variable is less or equal to the value of ‘number’ variable. If the condition is true then it will execute the iteration of the loop.
Another for loop is used to check the value of ‘i’ variable is less than or equal to the value of ‘count’ variable. If the condition is true then execute the iteration of the loop and decrement the value of ‘count’ variable by 1.
Using another for loop initialize the value of ‘i’ variable as 1. Check the multiplication of 2 values with the difference of the value of ‘number’ variable by the value of ‘k’ variable and also by1. If the condition is true then execute the iteration of the loop and print the * symbol.
1 2 3 4 5 6 7 8 9 |
Enter number of rows 3 * *** ***** *** * |
19) C# Program to Illustrate LeftShift Operations
This is a C# Program to illustrate leftshift operations.
This C# Program Illustrates LeftShift Operations.
The shift operators allow programmers to adjust an integer by shifting all of its bits to the left or the right.
Here is source code of the C# Program to Illustrate LeftShift Operations. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* * C# Program to Illustrate LeftShift Operations */ using System; class sample { public static void Main() { int x = 1024 * 1024 * 1024; uint p = 1024 * 1024 * 1024; int y = -42; Console.WriteLine("LEFT SHIFT OPERATIONS :"); Console.WriteLine("{0},{1},{2}", x, x * 2, x << 1); Console.WriteLine("{0},{1},{2}", p, p * 2, p << 1); Console.WriteLine("{0},{1},{2}", x, x * 4, x << 2); Console.WriteLine("{0},{1},{2}", p, p * 4, p << 2); Console.WriteLine("{0},{1},{2}", y, y * 1024 * 1024 * 64, x << 26); Console.ReadLine(); } } |
In this C# program, illustrate leftshift operations. Using ‘x’ integer and ‘p’ unsigned integer variable multiply 1024 value as thrice. Assign -42 values to ‘y’ integer variable.
The shift operators allow programmers to adjust an integer by shifting all of its bits to the left or the right. Print the value using leftshift operations.
1 2 3 4 5 6 7 8 |
LEFT SHIFT OPERATIONS : 1073741824,-2147483648,-2147483648 1073741824,2147483648,2147483648 1073741824,0,0 1073741824,0,0 -42,1476395008,0 |
20) C# Program to Check whether the given Integer has an Alternate Pattern
This is a C# Program to check whether the given integer has an alternate pattern.
This C# Program Checks whether the given Integer has an Alternate Pattern.
Take input from the user and check for alternate pattern as shown in the program below.
Here is source code of the C# Program to Check whether the given Integer has an Alternate Pattern. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
/* * C# Program to Check whether the given Integer has an * Alternate Pattern */ using System; using System.Collections.Generic; using System.Linq; using System.Text; class program { public static void Main() { int num, x, y, count = 0; Console.WriteLine("Enter the Number:"); num = int.Parse(Console.ReadLine()); x = num << 1; y = x ^ num; y = y + 1; while ((y / 2) != 0) { if (y % 2 != 0) { count++; break; } else { y = y / 2; } } if (count == 1) { Console.WriteLine("false"); } else { Console.WriteLine("true"); } Console.Read(); } } |
In this C# Program, we are reading the number using ‘num’ variable. Compute the Binary Left Shift Operation, the left operand’s value is moved left by the number of bits specified by the right operand.
The ‘y’ variable is used to compute the Binary XOR operation, copies the bit if it is set in one operand but not both and increment the value of ‘y’ variable by 1. While loop is used to check the number is in powers of 2.
If else condition statement is used to check that modulus of the value of ‘y’ variable by 2 is not equal to 0. If the condition is true, then it will execute the statement and increment the value of ‘count’ variable. Otherwise, if the condition is false, then execute the else statement. Using if else condition statement print the alternate pattern of the given integer.
1 2 3 4 |
Enter the Number: 100 false |
21) C# Program to Read a Grade & Display the Equivalent Description
This is a C# Program to read a grade & display the equivalent description.
This C# Program Reads a Grade & Display the Equivalent Description.
Here If grade is S, it prints super, if grade is A, it prints very good, if grade is B, it prints fair, if grade is Y, it prints absent, if grade is F, it prints fail.
Here is source code of the C# Program to Read a Grade & Display the Equivalent Description. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
/* * C# Program to Read a Grade & Display the Equivalent Description */ using System; using System.IO; class program { public static void Main() { char grade; Console.WriteLine("Enter the Grade in UpperCase \n"); grade = Convert.ToChar(Console.ReadLine()); switch (grade) { case 'S': Console.WriteLine(" SUPER"); break; case 'A': Console.WriteLine(" VERY GOOD"); break; case 'B': Console.WriteLine(" FAIR"); break; case 'Y': Console.WriteLine(" ABSENT"); break; case 'F': Console.WriteLine(" FAIL"); break; default: Console.WriteLine("ERROR IN GRADE \n"); break; Console.ReadLine(); } } } |
In this C# program, we are reading the grade using ‘grade’ variable. The toupper() function is used to convert the lower case letter of ‘grade’ variable value to upper case. Switch case statement is used to display equivalent grade description, if the grade variable value doesn’t match any value in case statement then execute the default statement. Print the equivalent description of the grade.
1 2 3 4 5 |
Enter the Grade in UpperCase A VERY GOOD |
22) C# Program to Find Greatest among 2 numbers
This is a C# Program to find greatest among 2 numbers.
This C# Program Finds Greatest among 2 numbers.
Here the user enters two numbers and the greatest among the two numbers is found by comparing the two numbers and the result is displayed.
Here is source code of the C# Program to Find Greatest among 2 numbers. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/* * C# Program to Find Greatest among 2 numbers */ using System; class prog { public static void Main() { int a, b; Console.WriteLine("Enter the Two Numbers : "); a = Convert.ToInt32(Console.ReadLine()); b = Convert.ToInt32(Console.ReadLine()); if (a > b) { Console.WriteLine("{0} is the Greatest Number", a); } else { Console.WriteLine("{0} is the Greatest Number ", b); } Console.ReadLine(); } } |
In this C# program, we are finding the greatest value among 2 numbers. If else condition statement is used to compare the two numbers and print the greatest value among 2 numbers.
1 2 3 4 5 6 |
Enter the Two Numbers : 24 34 34 is the Greatest Number |
C# Examples on Unboxing Operation and Sealed classes.
23) C# Program to Display Squarefeet of a House
This is a C# Program to display squarefeet of a house.
This C# Program Displays Squarefeet of a House.
Here the length and width of the room are given and the squarefeet is calculated and displayed.
Here is source code of the C# Program to Display Squarefeet of a House. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/* * C# Program to Display Squarefeet of a House */ using System; class pgm { public static void Main() { int length, width, area; Console.Write ("Enter length of room in feet: "); length = Convert.ToInt32 (Console.ReadLine()); Console.Write ( "Enter width of room in feet:"); width = Convert.ToInt32(Console.ReadLine()); area = length * width; Console.WriteLine ("Floor is " + area + " square feet."); Console.ReadLine(); } } |
In this C# program, we are reading the length and width of the room using ‘length’ and ‘width’ variables respectively. Using the formula length * width the squarefeet is calculated and print the squarefeet of a house.
1 2 3 4 5 |
Enter Length of Room in Feet : 20 Enter width of Room in Feet : 20 Floor is 400 square feet. |
24) C# Program to Create Sealed Class
This is a C# Program to create sealed class.
This C# Program Creates Sealed Class.
Here sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.
Here is source code of the C# Program to Create Sealed Class. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* * C# Program to Create Sealed Class */ using System; sealed class SealedClass { public int x; public int y; } class SealedTest { static void Main() { SealedClass sc = new SealedClass(); sc.x = 100; sc.y = 180; Console.WriteLine("x = {0}, y = {1}", sc.x, sc.y); Console.ReadLine(); } } |
In this C# program, we have already defined the values of ‘x’ and ‘y’ variable as 100 and 180 respectively. The sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, this class cannot be inherited.
1 2 3 |
x = 100 ,y = 180 |
25) C# Program to Perform Unboxing Operation
This is a C# Program to perform unboxing operation.
This C# Program Performs Unboxing Operation.
Here Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface.
Here is source code of the C# Program to Perform Unboxing Operation. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/* * C# Program to Perform Unboxing Operation */ using System; class sample { int data; void insert(object x) { data = (int)x * 5; } object delete() { data=0; return (object)data; } public static void Main() { sample s = new sample(); s.insert(10); Console.WriteLine("Data : {0}", s.data); Console.WriteLine("Data : {0}", s.delete()); Console.ReadLine(); } } |
In this C# Program, we are performing the unboxing operation. In sample class we have created insert() and delete() function. The insert() function use data variable to multiply the value of argument with the value of 5.
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. Using object variable‘s’ we are passing the value 10 to the insert() function as an argument.
1 2 3 4 |
Data : 50 Data : 0 |
26) C# Program to Display All the Prime Numbers Between 1 to 100
This is a C# Program to display all the prime numbers between 1 to 100.
This C# Program Displays All the Prime Numbers Between 1 to 100.
Here prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Here is source code of the C# Program to Display All the Prime Numbers Between 1 to 100. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/* * C# Program to Display All the Prime Numbers Between 1 to 100 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PrimeNumber { class Program { static void Main(string[] args) { bool isPrime = true; Console.WriteLine("Prime Numbers : "); for (int i = 2; i <= 100; i++) { for (int j = 2; j <= 100; j++) { if (i != j && i % j == 0) { isPrime = false; break; } } if (isPrime) { Console.Write("\t" +i); } isPrime = true; } Console.ReadKey(); } } } |
In this C# program, using for loop we are finding the prime numbers from 1 to 100. Inside the loop, if condition statement is used to check that range value is less than 2, if the condition is true.
Then execute if condition statement and print number of prime numbers. Using if condition statement checks the value of ‘i’ variable is not equal to the value of ‘j’ variable and the modulus of the value of ‘i’ variable by the value of ‘j’ variable is equal to 0 using logical AND operators.
If the condition is true, then execute if condition statement. Assign the value of isprime variable as false. For loop is used to check the number of prime numbers occurring up to the range. Using if condition statement, print all prime numbers between1 to 100.
1 2 3 4 5 6 |
Prime Numbers : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 |
27) C# Program to Accept a Number from the user and Display it if it is Positive
This is a C# Program to accept a number from the user and display it if it is Positive.
This C# Program Accepts a Number from the user and Display it if it is Positive.
Here if a given number is less than zero then it is displayed as positive else negative.
Here is source code of the C# Program to Accept a Number from the user and Display it if it is Positive. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
/* * C# Program to Accept a Number from the user and Display it * if it is Positive */ using System; class program { public static void Main(string[] args) { Console.WriteLine("Enter a number: "); int number = Convert.ToInt32(Console.ReadLine()); if (number > 0) { Console.WriteLine("Number is positive"); } else if (number == 0) { Console.WriteLine("Number is 0"); } else { Console.WriteLine("Number is negative"); } Console.ReadLine(); } } |
In this C# program, we are reading a number using the ‘number’ variable. Nested if else condition statement is used to check that given number is less than zero. If the condition is true then execute the statement and print the statement as positive. Otherwise, if the condition is false, then execute the else statement and print the statement as the number is 0.
1 2 3 4 |
Enter a Number : -4 Number is Negative |
C# Examples on Numerical Operations
28) C# Program to Find Magnitude of Integer
This is a C# Program to find magnitude of integer.
This C# Program Finds Magnitude of Integer.
Here Magnitude of an integer is nothing but the length of the integer which is obtained using the mod function.
Here is source code of the C# Program to Find Magnitude of Integer. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/* * C# Program to Find Magnitude of Integer */ using System; public class Program { public static void Main() { int num, mag=0; Console.WriteLine("Enter the Number : "); num = int.Parse(Console.ReadLine()); Console.WriteLine("Number: " + num); while (num > 0) { mag++; num = num / 10; }; Console.WriteLine("Magnitude: " + mag); Console.Read(); } } |
In this C# program, we are reading a number using ‘num’ variable. Using While loop check the value of ‘num’ variable is greater than 0. If the condition is true then execute the statement and compute the magnitude of integer. Magnitude of an integer is nothing but the length of the integer which is obtained using the mod function. Print the magnitude of integer.
1 2 3 4 5 |
Enter the Number : 3145678 Number : 3145678 Magnitude : 7 |
29) C# Program to Compute Average for the Set of Values
This is a C# Program to compute average for the set of values.
This C# Program Computes Average for the Set of Values.
Here the elements are obtained from the user and its average is found and displayed.
Here is source code of the C# Program to Compute Average for the Set of Values. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
/* * C# Program to Compute Average for the Set of Values */ using System; class program { public static void Main() { int m, i, sum = 0, avg = 0; Console.WriteLine("Enter the Number of Terms in the Array "); m = int.Parse(Console.ReadLine()); int[] a = new int[m]; Console.WriteLine("Enter the Array Elements "); for (i = 0; i < m; i++) { a[i] = int.Parse(Console.ReadLine()); } for (i = 0; i < m; i++) { sum += a[i]; } avg = sum / m; Console.WriteLine("Average is {0}", avg); Console.ReadLine(); } } |
In this C# program, we are reading the number of terms in the array using ‘m’ variable. Then for loop is used to enter the coefficient element values of the array. Compute the values and divide the size of an array. Print the average for the set of values.
1 2 3 4 5 6 7 8 9 |
Enter the Number of Terms in the Array : 4 Enter the Elements 1 2 3 4 Average is 2 |
30) C# Program to Display Numbers in the form of Triangle
This is a C# Program to display numbers in the form of triangle.
This C# Program Displays Numbers in the form of Triangle.
Here the numbers are displayed in the form of a triangle.
Here is source code of the C# Program to Display Numbers in the form of Triangle. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
/* * C# Program to Display Numbers in the form of Triangle */ using System; class Pascal { public static void Main() { int[,] arr = new int[8, 8]; for (int i = 0; i < 8; i++) { for (int k = 7; k > i; k--) { //For loop to print spaces Console.Write(" "); } for (int j = 0; j < i; j++) { if (j == 0 || i == j) { arr[i, j] = 1; } else { arr[i, j] = arr[i - 1, j] + arr[i - 1, j - 1]; } Console.Write(arr[i, j] + " "); } Console.WriteLine(); } Console.ReadLine(); } } |
In this C# program, we are printing the numbers in the form of triangle. Pascal’s triangle is a triangular array of the binomial coefficients. The program consists of six integer type of variables named i, j, rows, array[][], k and num respectively. Out of this variable i, j and k have been defined to control the for loop, the integer ‘rows’ stores the limit of Pascal’s triangle entered by the user.
As the C program for Pascal’s triangle is executed, it first asks for the value of limit of the triangle. The program assigns ‘rows’ variable value with the value of ‘i’ variable; i.e., number of space with the limit of Pascal’s triangle, for loop in which ‘i’ is the loop control variable. Again, in order to control the space, a nested for loop with ‘k’ as a control variable is used.
Finally, for printing the elements in this program for Pascal’s triangle in C, another nested for loop of control variable ‘j’ has been used. The formula used to generate the numbers of Pascal’s triangle is:
Pascal triangle: array[i][j] = array[i – 1][j – 1] + array[i – 1][j].
1 2 3 4 5 6 7 8 9 |
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 |
C# Examples on Files and Folders
31) Use FileStream with using“ statement
It’s the best practice to use FileStream with using statement. The using statement ensures that Dispose method is called (even if an exception occurs). The Dispose method releases both managed and unmanaged resources and allows others to access the file. If you don’t dispose the stream it can take a minute to file to be accessible again (it waits to garbage collector to free the FileStream instance and close the file).
Open existing file for read and write
The following examples require to add namespace using System.IO;
1 2 3 4 5 6 |
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open)) { // read from file or write to file } |
Open existing file for reading
1 2 3 4 5 6 |
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read)) { // read from file } |
Open existing file for writing
1 2 3 4 5 6 |
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write)) { // write to file } |
Open file for writing (with seek to end), if the file doesn’t exist create it
1 2 3 4 5 6 |
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Append)) { // append to file } |
Create new file and open it for read and write, if the file exists overwrite it
1 2 3 4 5 6 |
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Create)) { // write to just created file } |
Create new file and open it for read and write, if the file exists throw exception
1 2 3 4 5 6 |
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.CreateNew)) { // write to just created file } |
32) Read file using FileStream
First create FileStream to open a file for reading. Then call FileStream.Read in a loop until the whole file is read. Finally close the stream.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
using System.IO; public static byte[] ReadFile(string filePath) { byte[] buffer; FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); try { int length = (int)fileStream.Length; // get file length buffer = new byte[length]; // create buffer int count; // actual number of bytes read int sum = 0; // total number of bytes read // read until Read method returns 0 (end of the stream has been reached) while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) sum += count; // sum is a buffer offset for next reading } finally { fileStream.Close(); } return buffer; } |
33) Read Text File into String
It’s super easy to read whole text file into string using static class File and its method File.ReadAllText.
1 2 3 |
string text = File.ReadAllText(@"c:\file.txt", Encoding.UTF8); |
Read Text File into String (with StreamReader)
Let’s look under the hood of the previous example. Method File.ReadAllText is implemented similarly to the following code. The using statement ensures that method StreamReader.Dispose is called. The StreamReader’s Dispose also calls FileStream.Dispose method which closes the file.
1 2 3 4 5 6 7 8 |
string text; var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read); using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { text = streamReader.ReadToEnd(); } |
Read Text File into String Array
Again, the easy way is to use static class File and it’s method File.ReadAllLines.
1 2 3 |
string[] lines = File.ReadAllLines(@"c:\file.txt", Encoding.UTF8); |
Read Text File into String Array (with StreamReader)
If you look under the hood of the File.ReadAllLines method, you can find implementation similar to this. As it was previously written, the using statement disposes StreamReader and FileStream (which closes the file).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
string[] lines; var list = new List<string>(); var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read); using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { string line; while ((line = streamReader.ReadLine()) != null) { list.Add(line); } } lines = list.ToArray(); |
Read Text File Line by Line
To reduce memory usage for large text files, you can process lines immediately instead of adding it to the list as in the previous example. To do that use File.ReadLines. This method internally creates Enumerator. Every time foreach asks for a next value, it calls StreamReader.ReadLine under the hood.
1 2 3 4 5 6 |
foreach (string line in File.ReadLines(@"c:\file.txt", Encoding.UTF8)) { // process the line } |
Read Text File Line by Line (with StreamReader)
The code above can be implement also directly using StreamReader.ReadLine as shows the code bellow.
1 2 3 4 5 6 7 8 9 10 11 |
var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read); using (var streamReader = new StreamReader(fileStream, Encoding.UTF8)) { string line; while ((line = streamReader.ReadLine()) != null) { // process the line } } |
34) Load Text from File to String
StreamReader
To load text from file to string you can use StreamReader.ReadToEnd method. First create new instance of StreamReader. Pass file path or Stream as a constructor parameter and specify the text file encoding (default is UTF-8).
Don’t forget to include namespace using System.IO;
1 2 3 4 5 6 7 |
string text; using (var streamReader = new StreamReader(@"c:\file.txt", Encoding.UTF8)) { text = streamReader.ReadToEnd(); } |
35) Get Files from Directory
Get files from directory
Method Directory.GetFiles returns string array with files names (full paths).
1 2 3 4 5 6 7 8 |
using System.IO; string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); // returns: // "c:\MyDir\my-car.BMP" // "c:\MyDir\my-house.jpg" |
Get files from directory (with specified extension)
You can specify search pattern. You can use wildcard specifiers in the search pattern, e.g. „*.bmp“ to select files with the extension or „a*“ to select files beginning with letter “a“.
1 2 3 4 5 |
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp"); // returns: // "c:\MyDir\my-car.BMP" |
Get files from directory (including all subdirectories)
If you want to search also in subfolders use parameter SearchOption.AllDirectories.
1 2 3 4 5 6 7 |
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp", SearchOption.AllDirectories); // returns: // "c:\MyDir\my-car.BMP" // "c:\MyDir\Friends\james.BMP" |
36) Delete All Files (*.*)
Delete all files
1 2 3 4 5 6 7 |
using System.IO; string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); foreach (string filePath in filePaths) File.Delete(filePath); |
Delete all files (one-row example)
To delete all files using one code line, you can use Array.ForEach with combination of anonymous method.
1 2 3 4 |
Array.ForEach(Directory.GetFiles(@"c:\MyDir\"), delegate(string path) { File.Delete(path); }); |
37) Get Application Directory
Following examples show how to get application or assembly folder.
Directory of windows forms application (.exe)
Class Application in System.Windows.Forms namespace has static property ExecutablePath. It contains path of the .exe file (that started the application) including the executable file name. To get only the folder part of the path, use static method GetDirectoryName of Path class.
1 2 3 4 5 6 |
using System.IO; using System.Windows.Forms; string appPath = Path.GetDirectoryName(Application.ExecutablePath); |
Directory of any loaded assembly (.exe or .dll)
First get reference to the assembly. You can use static methods of Assembly class. To get assembly of currently executing code use method Assembly.GetExecutingAssembly. To get assembly in which the specified class is defined use method Assembly.GetAssembly (with the specified class type as a paramater). The assembly must be loaded. Next get assembly file path using Assembly.CodeBase property.
1 2 3 4 5 6 7 |
using System.IO; using System.Reflection; string path = Path.GetDirectoryName( Assembly.GetAssembly(typeof(MyClass)).CodeBase); |
38) File Attributes
Get file attributes
To get file attributes use static method File.GetAttributes. The method returns FileAttributes which is a bitwise combination of file attribute flags.
1 2 3 4 5 6 |
string filePath = @"c:\test.txt"; // get file attributes FileAttributes fileAttributes = File.GetAttributes(filePath); |
Set file attributes
To set file attributes use static method File.SetAttributes. Parameter of the method is a bitwise combination of FileAttributes enumeration.
1 2 3 4 5 6 7 8 |
// clear all file attributes File.SetAttributes(filePath, FileAttributes.Normal); // set just only archive and read only attributes (no other attribute will set) File.SetAttributes(filePath, FileAttributes.Archive | FileAttributes.ReadOnly); |
Check whether a file has any attribute
To check whether a file has any attribute (readonly, hidden) get current file attributes first and use bitwise AND (&) operator with a mask of specific attributes.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// check whether a file is read only bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly); // check whether a file is hidden bool isHidden = ((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden); // check whether a file has archive attribute bool isArchive = ((File.GetAttributes(filePath) & FileAttributes.Archive) == FileAttributes.Archive); // check whether a file is system file bool isSystem = ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System); |
Add file attributes to current ones
To add file attributes to the existing ones get the current file attributes first and use bitwise OR (|) with the desired attributes.
1 2 3 4 5 6 7 8 |
// set (add) hidden attribute (hide a file) File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden); // set (add) both archive and read only attributes File.SetAttributes(filePath, File.GetAttributes(filePath) | (FileAttributes.Archive | FileAttributes.ReadOnly)); |
Delete/clear file attributes from current ones
To delete file attributes from the existing ones get the current file attributes first and use AND (&) operator with a mask (bitwise complement of desired attributes combination).
1 2 3 4 5 6 7 8 |
// delete/clear hidden attribute File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.Hidden); // delete/clear archive and read only attributes File.SetAttributes(filePath, File.GetAttributes(filePath) & ~(FileAttributes.Archive | FileAttributes.ReadOnly)); |
39) Get File Time
Get file times using File class
Use File class when you want to get just one specific time, for example if you are only interested in a file last modification time. To do this use static method File.GetLastWriteTime with file path as a parameter. File class also provides static methods to get file creation time or file last access time. You can also get this times in UTC, e.g. to get file last write time in UTC use File.GetLastWriteTimeUtc.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// local times DateTime creationTime = File.GetCreationTime(@"c:\file.txt"); DateTime lastWriteTime = File.GetLastWriteTime(@"c:\file.txt"); DateTime lastAccessTime = File.GetLastAccessTime(@"c:\file.txt"); // UTC times DateTime creationTimeUtc = File.GetCreationTimeUtc(@"c:\file.txt"); DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(@"c:\file.txt"); DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(@"c:\file.txt"); // write file last modification time (local / UTC) Console.WriteLine(lastWriteTime); // 9/30/2007 2:16:04 PM Console.WriteLine(lastWriteTimeUtc); // 9/30/2007 6:16:04 PM |
Get file times using FileInfo class
Use instance of FileInfo class when you want to get more than one file time or any other informations about the file (like file attributes). Advantage is that you will get all needed informations just in one disk access. See following example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
FileInfo fileInfo = new FileInfo(@"c:\file.txt"); // local times DateTime creationTime = fileInfo.CreationTime; DateTime lastWriteTime = fileInfo.LastWriteTime; DateTime lastAccessTime = fileInfo.LastAccessTime; // UTC times DateTime creationTimeUtc = fileInfo.CreationTimeUtc; DateTime lastWriteTimeUtc = fileInfo.LastWriteTimeUtc; DateTime lastAccessTimeUtc = fileInfo.LastAccessTimeUtc; // write file last modification time (local / UTC) Console.WriteLine(lastWriteTime); // 9/30/2007 2:16:04 PM Console.WriteLine(lastWriteTimeUtc); // 9/30/2007 6:16:04 PM |
40) Open File With Associated Application
Applications are launched using Process.Start method. The file path or url is passed as a parameter.
1 2 3 4 |
// open text file in notepad (or another default text editor) System.Diagnostics.Process.Start(@"c:\textfile.txt"); |
1 2 3 4 |
// open image in default viewer System.Diagnostics.Process.Start(@"c:\image.jpg"); |
1 2 3 4 |
// open url in default web browser System.Diagnostics.Process.Start("http://www.cscode.net"); |
1 2 3 4 |
// open PDF file System.Diagnostics.Process.Start(@"c:\document.pdf"); |
Similarly you can open Word document or any other file from your .NET application.
C# Examples on Interface and Looping Operations
41) C# Program to Implement PhoneBook
This is a C# Program to implement phonebook.
This C# Program Implements PhoneBook.
Reads a file with names and phone numbers and builds a phone book from it and Returns the phone number for a given name.
Here is source code to Implement PhoneBook.The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
/* * C# Program to Implement PhoneBook */ using System; using System.Collections; using System.IO; class PhoneBook { static void Main(string[] arg) { Hashtable tab = new Hashtable(); string fileName; if { (arg.Length > 0) fileName = arg[0]; } else { fileName = "phoneBook.txt"; } StreamReader r = File.OpenText(fileName); string line = r.ReadLine(); while (line != null) { int pos = line.IndexOf('='); string name = line.Substring(0, pos).Trim(); long phone = Convert.ToInt64(line.Substring(pos + 1)); tab[name] = phone; line = r.ReadLine(); } r.Close(); for (; ; ) { Console.Write("Name : "); string name = Console.ReadLine().Trim(); if (name == "") break; object phone = tab[name]; if (phone == null) Console.WriteLine("-- Not Found in Phone Book"); else Console.WriteLine(phone); } } } |
In C# Program, we are reading a file with names and phone numbers and build a phone book from it and return the phone number for a given name. If else condition statement is used to assign the value of ‘arg[0]’ variable to the file name.
Otherwise, if the condition is false then execute the else statement. Assign the phonebook text file to the file name variable. While loop is used to check that line variable value is not equal to null. If the condition is true then execute the iteration of the loop. In substring() function assign the name, from the file present in read mode.
Using ToInt64() function convert the text in number format to the phone variable. Then close the file. If else condition statement, is used to display the name and phone number from the phone book.
1 2 3 4 5 6 |
Name : Tom 21540024500 Name : Joe -- Not Found in Phone Book |
42) C# Program to Implement for-each in Interface
This is a C# Program to implement for each in interface.
This C# Program Implements for-each in Inteface.
It demonstrates the best practice for iterating a custom collection by implementing the IEnumerable and IEnumerator interfaces. In this code, members of these interfaces are not explicitly called, but they are implemented to support the use of foreach to iterate through the collection.
Here is source code of the C# Program to Implement for-each in Inteface. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
/* * C# Program to Implement for-each in Inteface */ using System; using System.Collections; class GrowableArray : IEnumerable { object[] a; public GrowableArray(int size) { a = new object[size]; } public GrowableArray() : this(8) {} void Grow() { object[] b = new object[2 * a.Length]; Array.Copy(a, b, a.Length); a = b; } public object this[int i] { set { if (i >= a.Length) Grow(); a[i] = value; } get { if (i >= a.Length) Grow(); return a[i]; } } public IEnumerator GetEnumerator() { return new GAEnumerator(a); } class GAEnumerator : IEnumerator { object[] a; int i = -1; public GAEnumerator(object[] a) { this.a = a; } public object Current { get { return a[i]; } } public void Reset() { i = -1; } public bool MoveNext() { do i++; while (i < a.Length && a[i] == null); if (i == a.Length) return false; else return true; } } } class Test { public static void Main() { GrowableArray a = new GrowableArray(2); a[0] = 0; a[1] = 1; a[3] = 3; foreach (object x in a) Console.Write(" " + x); } } |
This C# program is used to implement for-each in Interface. It demonstrates the best practice for iterating a custom collection by implementing the IEnumerable and IEnumerator interfaces.
In this code, members of these interfaces are not explicitly called, but they are implemented to support the use of foreach to iterate through the collection.
43) C# Program to Calculate Acceleration
This is a C# Program to calculate acceleration.
This C# Program Calculates Acceleration.
Here the velocity and time are obtained and acceleration is calculated.
Here is source code of the C# Program to Calculate Acceleration. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/* * C# Program to Calculate Acceleration */ using System; class program { static void Main(string[] args) { int v, t, acc; Console.WriteLine("Enter the Velocity : "); v = int.Parse(Console.ReadLine()); Console.WriteLine("Enter the Time : "); t = int.Parse(Console.ReadLine()); acc = v / t; Console.WriteLine("Acceleration : {0}", acc); } } |
In this C# Program, we are reading the velocity and time to compute the acceleration by using the formula
Acceleration = velocity / time
44) C# Program to Find a Number using Pythagoras Theorem
This is a C# Program to find a number using pythagoras theorem.
This C# Program Finds a Number using Pythagoras Theorem.
Here the pythagoras theorem is used to find the other number.
Here is source code of theC# Program to Find a Number using Pythagoras Theorem. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/* * C# Program to Find a Number using Pythagoras Theorem */ using System; using System.Collections.Generic; using System.Linq; using System.Text; class Program { static void Main(string[] args) { double a, b, c; Console.WriteLine("Enter the First Value "); a = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the Second Value "); b = double.Parse(Console.ReadLine()); c = Math.Sqrt(a * a + b * b); Console.WriteLine("The Other Number is : {0}", c); Console.ReadLine(); } } |
In this C# Program, we are reading the first Value and second value using ‘a’ and ‘b’ variables respectively. The pythagoras theorem is used to find the other number.
Multiply the value of ‘a’ variable with the value of ‘a’ variable and the value of ‘b’ variable with value of ‘b’ variable. Add both the multiplied value and take the square root of that value.
45) C# Program to Perform Division of Exponents of Same Base
This is a C# Program to perform division of exponents of same base.
This C# Program Performs Division of Exponents of Same Base.
Here the power value for all same base is found.
Here is source code of the C# Program to Perform Multiplication of Exponents of Same Base. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* * C# Program to Perform Division of Exponents of Same Base */ using System; class Program { static void Main() { Console.WriteLine("Enter the Base : "); double num = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the First Exponent :"); double exp1 = double.Parse(Console.ReadLine()); Console.WriteLine("Enter the Second Exponent :"); double exp2 = double.Parse(Console.ReadLine()); double div; div = exp1 - exp2; Console.WriteLine("Result is : {0}^{1} : {2}", num, div, Math.Pow(num, div)); Console.ReadLine(); } } |
In this C# program, we are reading the base, the first and second exponent value using the variables ‘num’, ‘exp1’ and ‘exp2’ respectively. The ‘div’ variable is used to compute the difference between the first and second exponent values and the power value for all same bases is found. Print the division of exponents of same base.
Seriously this site was sooo important me to increase my collage result in programming subject and I recommended to this every student who is searching for best examples with answers and this surface also sooo attractive feel to study well. ❤❤❤❤❤❤❤❤❤❤❤