 C# Basic Programming Examples – Programming, Pseudocode Example, C# Programming Example

# C# Basic Programming Examples

## 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.

Problem Description

This C# Program checks if a given integer is Odd or Even.

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 2) C# Program to Swap 2 Numbers

This is a C# Program to swap 2 numbers.

Problem Description

This C# Program Swaps 2 Numbers.

Problem Solution

It obtains two numbers from the user and swaps the numbers using a temporary variable.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Gets a Number and Display the Sum of the Digits.

Problem Solution

The digit sum of a given integer is the sum of all its digits.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Gets a Number and Display the Number with its Reverse.

Problem Solution

Here we obtain a number from the user and display the digits in the reverse order.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 5) C# Program to Print a Binary Triangle

This is a C# Program to Print a binary triangle.

Problem Description

This C# Program Prints a Binary Triangle.

Problem Solution

Binary Triangle is a Triangle formed with 1’s and 0’s.Number of rows in the binary triangle is obtained from the user.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Counts the Number of 1’s in the Entered Number.

Problem Solution

Here the array of numbers are obtained with its limit and number of 1’s in it is counted and displayed.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

## 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.

You can use also date separator `/` (slash) and time sepatator `:` (colon). These characters will be rewritten to characters defined in the current DateTimeForma­tInfo.DateSepa­rator and DateTimeForma­tInfo.TimeSepa­rator.

Here are some examples of custom date and time formatting:

### 8) Standard DateTime Formatting

In DateTimeForma­tInfo 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 DateTimeForma­tInfo 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` SortableDateTi­mePattern `yyyy'-'MM'-'dd'T'HH':'mm':'ss` (*)
`u` UniversalSorta­bleDateTimePat­tern `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.

### 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.

Problem Description

This C# Program Checks Whether the Entered Year is a Leap Year or Not.

Problem Solution

When A year is divided by 4. If the remainder becomes 0 then the year is called a leap year.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 10) C# Program to Display the Date in Various Formats

This is a C# Program to display the date in various formats.

Problem Description

This C# Program Displays the Date in Various Formats.

Problem Solution

Here the Date is Displayed in various Formats.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 11) C# Program to Compare Two Dates

This is a C# Program to compare two dates.

Problem Description

This C# Program Compares Two Dates.

Problem Solution

Here two dates are compared and the date which occurs first is displayed.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 12) C# Program to Display the ATM Transaction

This is a C# Program to display the atm transaction.

Problem Description

This C# Program Displays the ATM Transaction.

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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

### 13) C# Program to Generate Random Numbers

This is a C# Program to generate random numbers.

Problem Description

This C# Program Generates Random Numbers.

Problem Solution

Here random numbers are generated using the Random class and the next() in it.

Program/Source Code

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.

Program Explanation

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.

Problem Description

This C# Program accepts the height of a person & categorizes it as Tall, Dwarf or Average.

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Finds the Frequency of the Word ʺtheʺ in a given Sentence.

Problem Solution

Here the frequency of ‘the’ in the given string is found.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Swaps the Contents of two Numbers using Bitwise XOR Operation.

Problem Solution

Take two inputs from the user and perform Bitwise XOR Operation as shown in the program below.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

## 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.

Problem Description

This C# Program Illustrates the Use of Access Specifiers.

Problem Solution

Here the four types of access specifiers are explained by assigning values.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 18) C# Program to Print a Diamond Using Nested Loop

This is a C# Program to print a diamond using nested loop.

Problem Description

This C# Program Prints a Diamond Using Nested Loop.

Problem Solution

Take input from the user and go on to draw the diamond pattern as shown in the program below.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 19) C# Program to Illustrate LeftShift Operations

This is a C# Program to illustrate leftshift operations.

Problem Description

This C# Program Illustrates LeftShift Operations.

Problem Solution

The shift operators allow programmers to adjust an integer by shifting all of its bits to the left or the right.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Checks whether the given Integer has an Alternate Pattern.

Problem Solution

Take input from the user and check for alternate pattern as shown in the program below.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 21) C# Program to Read a Grade & Display the Equivalent Description

This is a C# Program to read a grade & display the equivalent description.

Problem Description

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 22) C# Program to Find Greatest among 2 numbers

This is a C# Program to find greatest among 2 numbers.

Problem Description

This C# Program Finds Greatest among 2 numbers.

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

## 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.

Problem Description

This C# Program Displays Squarefeet of a House.

Problem Solution

Here the length and width of the room are given and the squarefeet is calculated and displayed.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 24) C# Program to Create Sealed Class

This is a C# Program to create sealed class.

Problem Description

This C# Program Creates Sealed Class.

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 25) C# Program to Perform Unboxing Operation

This is a C# Program to perform unboxing operation.

Problem Description

This C# Program Performs Unboxing Operation.

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Displays All the Prime Numbers Between 1 to 100.

Problem Solution

Here prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 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.

Problem Description

This C# Program Accepts a Number from the user and Display it if it is Positive.

Problem Solution

Here if a given number is less than zero then it is displayed as positive else negative.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

## C# Examples on Numerical Operations

### 28) C# Program to Find Magnitude of Integer

This is a C# Program to find magnitude of integer.

Problem Description

This C# Program Finds Magnitude of Integer.

Problem Solution

Here Magnitude of an integer is nothing but the length of the integer which is obtained using the mod function.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 29) C# Program to Compute Average for the Set of Values

This is a C# Program to compute average for the set of values.

Problem Description

This C# Program Computes Average for the Set of Values.

Problem Solution

Here the elements are obtained from the user and its average is found and displayed.

Program/Source Code

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.

Program Explanation

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.

Runtime Test Cases

### 30) C# Program to Display Numbers in the form of Triangle

This is a C# Program to display numbers in the form of triangle.

Problem Description

This C# Program Displays Numbers in the form of Triangle.

Problem Solution

Here the numbers are displayed in the form of a triangle.

Program/Source Code

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.

Program Explanation

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].

Runtime Test Cases

## 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;`

Open existing file for writing

Open file for writing (with seek to end), if the file doesn’t exist create it

Create new file and open it for read and write, if the file exists overwrite it

Create new file and open it for read and write, if the file exists throw exception

### 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.

### 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.

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.Dis­pose is called. The StreamReader’s Dis­pose also calls FileStream.Dis­pose method which closes the file.

Read Text File into String Array

Again, the easy way is to use static class File and it’s method File.ReadAllLi­nes.

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).

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.Re­adLine under the hood.

The code above can be implement also directly using StreamReader.Re­adLine as shows the code bellow.

### 34) Load Text from File to String

To load text from file to string you can use StreamReader.Re­adToEnd 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;`

### 35) Get Files from Directory

Get files from directory

Method Directory.GetFiles returns string array with files names (full paths).

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“.

Get files from directory (including all subdirectories)

If you want to search also in subfolders use parameter SearchOption.A­llDirectories.

### 36) Delete All Files (*.*)

Delete all files

Delete all files (one-row example)

To delete all files using one code line, you can use Array.ForEach with combination of anonymous method.

### 37) Get Application Directory

Following examples show how to get application or assembly folder.

Directory of windows forms application (.exe)

Class Application in System.Window­s.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.

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.GetE­xecutingAssem­bly. To get assembly in which the specified class is defined use method Assembly.GetAs­sembly (with the specified class type as a paramater). The assembly must be loaded. Next get assembly file path using Assembly.CodeBase property.

### 38) File Attributes

Get file attributes

To get file attributes use static method File.GetAttri­butes. The method returns FileAttributes which is a bitwise combination of file attribute flags.

Set file attributes

To set file attributes use static method File.SetAttri­butes. Parameter of the method is a bitwise combination of FileAttributes enumeration.

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.

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.

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).

### 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.GetLastWri­teTime 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.GetLastWri­teTimeUtc.

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.

### 40) Open File With Associated Application

Applications are launched using Process.Start method. The file path or url is passed as a parameter.

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.

Problem Description

This C# Program Implements PhoneBook.

Problem Solution

Reads a file with names and phone numbers and builds a phone book from it and Returns the phone number for a given name.

Program/Source Code

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.

Program Explanation

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’ 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.

Runtime Test Cases

### 42) C# Program to Implement for-each in Interface

This is a C# Program to implement for each in interface.

Problem Description

This C# Program Implements for-each in Inteface.

Problem Solution

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.

Program/Source Code

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.

Program Explanation

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.

Problem Description

This C# Program Calculates Acceleration.

Problem Solution

Here the velocity and time are obtained and acceleration is calculated.

Program/Source Code

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.

Program Explanation

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.

Problem Description

This C# Program Finds a Number using Pythagoras Theorem.

Problem Solution

Here the pythagoras theorem is used to find the other number.

Program/Source Code

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.

Program Explanation

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.

Problem Description

This C# Program Performs Division of Exponents of Same Base.

Problem Solution

Here the power value for all same base is found.

Program/Source Code

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.

Program Explanation

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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.