C# Console Application
Examples (50+ C# Examples)
4 years ago
2 Comments
by Mike
67,039 views
C# is a simple, modern, general-purpose, object-oriented and high-level programming language
originally developed by Microsoft and released in 2002. This tutorial gives a complete
understanding of C#. This reference will take you through simple and practical approaches while
learning C# Programming language.
There are more over 40 examples in this C# examples list. And C# Examples are listing from
basic to complex
Basic C# Examples
Example 1: C# Program to Print Hello World
1
2
3
4
5
6
7
8
9
10
class Program
{
staticvoid Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.ReadKey();
}
}
Example 2: C# Program to Print an Integer Entered by User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Program
{
staticvoid Main(string[] args)
{
int number;
Console.Write("Enter a number:");
number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You entered :{0}",number);
Console.ReadLine();
}
}
Example 3: C# Program to Add Two Integers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Program
{
staticvoid Main(string[] args)
{
int num1, num2, sum;
Console.WriteLine("Calculate the sum of two numbers:");
Console.Write("Input number1:");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Input number2:");
num2 = Convert.ToInt32(Console.ReadLine());
sum = num1 + num2;
Console.Write("Result:"+sum);
Console.ReadKey();
}
}
Example 4: C# Program to Multiply two Floating Point Numbers Entered by User
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Program
{
staticvoid Main(string[] args)
{
float number1,number2,product;
Console.Write("Enter a number1:");
number1 = Convert.ToSingle(Console.ReadLine());
Console.Write("Enter a number2:");
number2 = Convert.ToSingle(Console.ReadLine());
product = number1 * number2;
Console.WriteLine("{0} * {1} = {2}",number1,number2, product);
Console.ReadLine();
}
}
Example 5: Multiply Two Floating Point Numbers in C# Console
1
2
3
4
5
6
7
8
9
10
class Program
{
staticvoid Main(string[] args)
{
float number1,number2,product;
number1 = 12.45f;
number2 = 10.74f;
product = number1 * number2;
11
12
13
14
15
16
Console.WriteLine("{0} * {1} = {2}",number1,number2, product);
Console.ReadLine();
}
}
Example 6: C# Program to Compute Quotient and Remainder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Program
{
staticvoid Main(string[] args)
{
int dividend = 50, divisor = 8;
int quotient = dividend / divisor;
int remainder = dividend % divisor;
Console.WriteLine("Dividend:{0} Divisor:{1}",dividend,divisor);
Console.WriteLine("Quotient = " + quotient);
Console.WriteLine("Remainder = " + remainder);
Console.ReadLine();
}
}
Example 7: Program To Calculate the Simple Interest in C#
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int P, T;
float R, SI;
Console.Write("Enter Amount :");
P = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Rate :");
R = Convert.ToSingle(Console.ReadLine());
Console.Write("Enter Time :");
T = Convert.ToInt32(Console.ReadLine());
SI = P * R * T / 100;
Console.WriteLine("Interest is :{0}", SI);
Console.ReadKey();
Console.ReadLine();
Output:
Example 8: C# Calculate Rectangle Area
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Program
{
staticvoid Main(string[] args)
{
int area, length, width;
Console.Write("Please write the length of your rectangle: ");
length = Convert.ToInt32(Console.ReadLine());
Console.Write("Please write the width of your rectangle: ");
width = Convert.ToInt32(Console.ReadLine());
area = length * width;
Console.WriteLine("The area of rectangle : {0}", area);
Console.ReadKey();
}
}
Output:
Example 9: C# Square Area and Perimeter Calculator
Code:
1
2
3
4
5
6
7
8
9
10
11
12
staticvoid Main(string[] args)
{
int squareheight,area,perimeter;
Console.Write("What is theheight of your square? :");
squareheight = Convert.ToInt32(Console.ReadLine());
area = squareheight * squareheight;
perimeter = 4 * squareheight;
Console.WriteLine("Area : {0}nPerimeter : {1}",area,perimeter); // "n"--> new line
Console.ReadKey();
}
Output:
Example 10: Area and Perimeter of Circle in C# Console Application
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Program
{
staticvoid Main(string[] args)
{
double r,perimeter, area;
Console.Write("Please write the radius of your circle : ");
r = Convert.ToDouble(Console.ReadLine());
perimeter = 2 * 3.14 * r;
area = 3.14 * Math.Pow(r, 2);//area = 3.14 * r * r;
Console.WriteLine("=============================================");
Console.WriteLine("The perimeter of yor circle : {0}",perimeter);
Console.WriteLine("The area of yor circle : {0}", area);
Console.ReadKey();
}
}
Example 11: Program to finds the average of 3 numbers in C#
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Program
{
staticvoid Main(string[] args)
{
int number1,number2,number3,avarage;
Console.Write("Enter 1st number :");
number1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter 2nd number :");
number2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter 3rd number :");
number3 = Convert.ToInt32(Console.ReadLine());
avarage = (number1 + number2 + number3) / 3;
Console.Write("Avarage of three numbers is {0}",avarage);
Console.ReadKey();
}
}
Output:
Example 12: C# Math.Pow Example
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
double baseNumber, powerNumber;
Console.Write("Enter base number :");
baseNumber = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter exponent number :");
powerNumber = Convert.ToDouble(Console.ReadLine());
double returnNumber = Math.Pow(baseNumber, powerNumber);
Console.WriteLine("{0}^{1} = {2}", baseNumber, powerNumber, returnNumber);
Console.ReadLine();
Output:
Example 13: C# Math.Pow Negative Exponent Example
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
double baseNumber, powerNumber;
Console.Write("Enter base number :");
baseNumber = Convert.ToDouble(Console.ReadLine()); //2
Console.Write("Enter exponent number :");
powerNumber = Convert.ToDouble(Console.ReadLine()); //-2
double returnNumber = Math.Pow(baseNumber, powerNumber);
Console.WriteLine("{0}^{1} = {2}", baseNumber, powerNumber, returnNumber);
Console.ReadLine();
Output:
Example 14: C# Program to Count Number of Words in a String
Code:
1
2
3
4
5
6
7
8
9
10
11
staticvoid Main(string[] args)
{
string sentence;
Console.Write("Enter String : ");
sentence = Console.ReadLine();
string[] words = sentence.Split(' ');
Console.WriteLine("Count of words :"+words.Length);
Console.ReadKey();
}
Output:
Example 15: Convert Dollars to Cents in C#
Solution 1: Calculate in Main Method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Program
{
staticvoid Main(string[] args)
{
double dollar_amount;
int cents;
// int compute_cents;
Console.Write("Enter dollar amount :");
dollar_amount = Convert.ToDouble(Console.ReadLine());
cents =(int) (dollar_amount * 100);
Console.WriteLine("{0} $ = {1} ¢",dollar_amount,cents);
Console.ReadLine();
}
}
Solution 2: Calculate with Custom Method
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
class Program
{
staticvoid Main(string[] args)
{
double dollar_amount;
int cents;
// int compute_cents;
Console.Write("Enter dollar amount :");
dollar_amount = Convert.ToDouble(Console.ReadLine());
cents = compute_cents(dollar_amount);
Console.WriteLine("{0} $ = {1} ¢",dollar_amount,cents);
Console.ReadLine();
}
staticint compute_cents(double dollar_amount)
{
return (int)(dollar_amount * 100);
}
}
Output:
For More Simple Examples
C# Conditional Examples
Example 16: Fibonacci Series in C# with Method
C# Code:
1
2
3
4
5
6
7
8
9
10
11
12
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
staticlong[] numbers;
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
staticlong Fib(int n)
{
if (0 == numbers[n])
{
numbers[n] = Fib(n - 1) + Fib(n - 2);
}
return numbers[n];
}
staticvoid Main()
{
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
numbers = new long[n + 2];
numbers[1] = 1;
numbers[2] = 1;
long result = Fib(n);
Console.WriteLine("fib({0}) = {1}", n, result);
Console.ReadKey();
}
}
}
Output:
Example 17: Find Number is Even or Odd using if else Statement in C#
Code 1:
1
2
3
4
5
6
7
8
9
10
11
staticvoid Main(string[] args)
{
int n;
Console.Write("Enter an integer : ");
n = Int32.Parse(Console.ReadLine());
if(n%2==0)
{
Console.WriteLine("{0} is even",n);
}
else
12
13
14
15
16
17
{
Console.WriteLine("{0} is odd", n);
}
Console.ReadKey();
}
Code 2 (with static method):
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
class Program
{
staticbool IsEvenNumber(int num)
{
if (num % 2 == 0)
{
return true;
}
else
{
return false;
}
}
staticvoid Main(string[] args)
{
int n;
Console.Write("Enter an integer : ");
n = Int32.Parse(Console.ReadLine());
if (IsEvenNumber(n))
{
Console.WriteLine("{0} is even", n);
}
else
{
Console.WriteLine("{0} is odd", n);
}
Console.ReadKey();
}
}
Output:
Example 18: Find Numbers Above and Below the Average in C#
C# Code:
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
staticvoid Main(string[] args)
{
int counter = 0;
int[] numbers = new int[10];
int sum=0,avg=0,low=0,high=0;
for(int i=0;i<10;i++)
{
Console.Write("Number {0}: ",(i+1));
numbers[i] = Convert.ToInt32(Console.ReadLine());
sum += numbers[i];
}
avg = sum / 10;
//avg = sum / numbers.Length;
for (int i=0;i<10;i++)
{
if(numbers[i]<avg)
{
low++;
}
else
{
high++;
}
}
Console.WriteLine("The average is : {0}", avg);
Console.WriteLine("The numbers above the average are: {0}", high);
Console.WriteLine("The numbers below the average are: {0}", low);
Console.ReadKey();
}
Output:
Example 19: C# Program to Print all Prime Numbers in an Interval
Source Code:
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
staticvoid Main(string[] args)
{
int num1, num2,sayac=0;
Console.Write("Enter lower range: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter upper range: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Prime numbers between {0} and {1} are: ",num1,num2);
Console.WriteLine("==============================================");
for(int i=num1;i<num2;i++)
{
sayac = 0;
if(i>1)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
{
sayac = 1;
break;
}
}
if(sayac==0)
{
Console.WriteLine(i);
}
}
}
Console.ReadKey();
}
Output:
Example 20: Finding the biggest of three numbers in C#
C# Code:
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
staticvoid Main(string[] args)
{
int number1, number2, number3;
string result;
Console.Write("Input the first number :");
number1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the second number :");
number2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Input the third number :");
number3 = Convert.ToInt32(Console.ReadLine());
if (number1 > number2 && number1 > number3)
{
result= "The 1st Number is the greatest among three. n";
}
else if (number2 > number1 && number2 > number3)
{
result = "The 2nd Number is the greatest among three n";
}
else
{
result= "The 3rd Number is the greatest among three n";
}
Console.WriteLine(result);
Console.ReadLine();
}
Output:
Example 21: Generates the Sum of N Numbers in C#
Code:
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
class Program
{
staticvoid Main(string[] args)
{
int number, sum=0;
Console.Write("Enter a Number : ");
number = Convert.ToInt32(Console.ReadLine());
if(number<0)
{
Console.Write("Please Enter Positive Number");
}
else
{
while(number>0)
{
sum += number;
number -=1;
}
}
Console.WriteLine("The sum is "+sum);
Console.ReadKey();
}
}
Output:
Example 22: Counting program the total letter in text in C# Console
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
staticvoid Main(string[] args)
{
string myString = Console.ReadLine();
int count = 0;
for (int i = 0; i < myString.Length; i++)
{
// check thechar for whitespace. If char is not whitespace, increase the count variable
if (!char.IsWhiteSpace(myString[i]))
{
count++;
}
}
Console.WriteLine("Total letters: "+ count);
Console.ReadLine();
}
Alternavite code (foreach loop):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
staticvoid Main(string[] args)
{
Console.Write("Enter string :");
string myString = Console.ReadLine();
int count = 0;
foreach (char item in myString)
{
// check thechar for whitespace. If char is not whitespace, increase the count variable
if (!char.IsWhiteSpace(item))
{
count++;
}
}
Console.WriteLine("Total letters: "+ count);
Console.ReadLine();
}
Output:
Example 23: Get Month Name From Month Number – C#(Switch Case)
C# Code:
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
class Program
{
staticvoid Main(string[] args)
{
int monthNumber;
Console.Write("Enter Month Number (1 - 12): ");
monthNumber = Convert.ToInt32(Console.ReadLine());
switch (monthNumber)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
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
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("you did not enter correct value for month name");
break;
}
Console.ReadLine();
}
}
Output:
Example 24: Program Library Fine Calculation in C#
The fee structure is as follows:
1. If the book is returned on before 5 days, no fine will be charged.
2. If the book is returned after the expected return day (between 5 and 10 days) – fine: 0.5$
per day
3. If the book is returned after the expected return day (between 10 and 30 days) fine: 1$ per
day
4. If the book is not returned after 30 days, cancel membership. fine: 1.5$ per day
Code:
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
class Program
{
staticvoid Main(string[] args)
{
int days;
float fine=0;
Console.Write("Enter totaldays:");
days = Convert.ToInt32(Console.ReadLine());
if(days <= 5)
{
fine = 0;
}
else if(days > 5 && days <= 10)
{
fine = (days - 5) * 0.5F;
}
else if(days > 10 && days <=30)
{
// ----5 days--- --between 10 and 30---
fine = 5 * 0.5F + (days - 10) * 1;
}
else
{
// -5 days- -10 , 30- - >30 -
fine = 5 * 0.5F + 20 * 1 + (days-30) * 1.5F;
Console.WriteLine("Canceled your Membership");
}
Console.WriteLine("Your fine:"+fine);
Console.ReadLine();
}
}
Output
Example 25: Program to Find Leap Year in C#
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
staticvoid Main(string[] args)
{
int year;
Console.Write("Enter theYear :");
year = Convert.ToInt32(Console.ReadLine());
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
Console.WriteLine("{0} is Leap Year",year);
else
Console.WriteLine("{0} is not a Leap Year",year);
Console.ReadLine();
}
Output:
For Mode If Else Examples
C# Loop Examples
Example 26: C# program to find min and max in an array
Code:
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
class Program
{
staticvoid Main(string[] args)
{
//www.csharp-console-examples.com
int[] numbers = new int[10];
Random rnd = new Random();
int min, max;
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = rnd.Next(1, 100);
Console.WriteLine(numbers[i]);
}
min = numbers[0];
max = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
if (min > numbers[i])
min = numbers[i];
if (max < numbers[i])
max = numbers[i];
}
Console.WriteLine("=====================================");
Console.WriteLine("The highest number in the array: > > > " + max);
Console.WriteLine("The lowest number in thearray: > > > " + min);
Console.ReadKey();
}
}
Output:
C# program using for loop to find maximum value from an array
Example 27: C# Program to Calculate the Power of a Number Without Using Math.Pow
Code:(With for loop)
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
class Program
{
staticvoid Main(string[] args)
{
int baseNumber, expNumber;
double result = 1;
Console.Write("Base Number : ");
baseNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("exponent Number : ");
expNumber = Convert.ToInt32(Console.ReadLine());
bool sing = false;
if (expNumber > 0) sing = true;
expNumber = Math.Abs(expNumber);
for (int i = 1; i <= expNumber; i++)
{
if(sing)
result = result * baseNumber;
else
result /= baseNumber;
}
Console.WriteLine("Base {0} and exponent {1} Result = {2}", baseNumber, expNumber, result);
Console.ReadLine();
}
}
30
Code: (With While Loop)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Program
{
staticvoid Main(string[] args)
{
int baseNumber, expNumber, result = 1;
Console.Write("Base Number : ");
baseNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("exponent Number : ");
expNumber = Convert.ToInt32(Console.ReadLine());
while (expNumber != 0)
{
result *= baseNumber;
--expNumber;
}
Console.WriteLine("Result = {0}", result);
Console.ReadLine();
}
}
Output:
Example 28: C# Program to Find the Factorial of a Number
Source Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
staticvoid Main(string[] args)
{
int i, number, fact;
Console.WriteLine("Enter theNumber");
number = int.Parse(Console.ReadLine());
fact = number;
for (i = number - 1; i >= 1; i--)
{
fact = fact * i;
}
Console.WriteLine("nFactorial of Given Number is: "+fact);
Console.ReadLine();
}
Output:
Example 29: Display Numbers Between 1 to N Using For Loop
Code:
1
2
3
4
5
6
staticvoid Main(string[] args)
{
int n;
Console.Write("Number :");
n = Convert.ToInt32(Console.ReadLine());
7
8
9
10
11
12
13
for (int i = 1; i <= n; i++)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
Output:
Example 30: Generates the Sum of N Numbers in C#
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Program
{
staticvoid Main(string[] args)
{
int number, sum=0;
Console.Write("Enter a Number : ");
number = Convert.ToInt32(Console.ReadLine());
if(number<0)
{
Console.Write("Please Enter Positive Number");
}
else
{
while(number>0)
{
sum += number;
number -=1;
}
}
Console.WriteLine("The sum is "+sum);
24
25
26
27
28
Console.ReadKey();
}
}
Output:
Example 31: C# Program to Print all Prime Numbers in an Interval
Source Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
staticvoid Main(string[] args)
{
int num1, num2,sayac=0;
Console.Write("Enter lower range: ");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter upper range: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Prime numbers between {0} and {1} are: ",num1,num2);
Console.WriteLine("==============================================");
for(int i=num1;i<num2;i++)
{
sayac = 0;
if(i>1)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
{
sayac = 1;
21
22
23
24
25
26
27
28
29
30
31
32
break;
}
}
if(sayac==0)
{
Console.WriteLine(i);
}
}
}
Console.ReadKey();
}
Output:
Example 32: Nested For Loop in C# (Multiplication Table)
Code 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
staticvoid Main(string[] args)
{ //www.csharp-console-examples.com
for (int i=1;i<=10;i++)
{
for (int j = 0; j <= 10; j++)
{
Console.WriteLine("{0}x{1} = {2}", i, j, i * j);
}
Console.WriteLine("====================");
}
Console.ReadKey();
}
Output:
Code 2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
staticvoid Main(string[] args)
{ //www.csharp-console-examples.com
for (int j = 1; j <= 10; j++)
{
for (int i = 1; i <= 10; i++)
{
Console.Write("{0}*{1}={2}t", i, j, (i * j));
}
Console.WriteLine();
}
Console.ReadKey();
}
Output:
Example 33: Display Armstrong Number Between Two Intervals in C#
Code:
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
staticvoid Main(string[] args)
{
int num1,num2, n, sum, r;
Console.Write("Enter positivenumber1 :");
num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter positivenumber2 :");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Armstrong Number from {0} to {1}",num1,num2);
for (int i = num1; i <= num2; i++)
{
sum = 0;
n = i;
while (n != 0)
{
r = n % 10;
sum = sum + (r * r * r);
n = n / 10;
}
if (i == sum)
Console.WriteLine(i);
}
Console.ReadKey();
}
Example 34: Checking for Palindrome Strings or Numbers in C#
Code:
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
staticvoid Main(string[] args)
{
Console.Write("Enter something for to check that is it palindrome :");
string text = Console.ReadLine();
int len = text.Length;
bool flag = true;
//check palindrome
for (int i = 0; i < len/2; i++)
{
if (text[i] != text[len - (i + 1)])
{
flag = false;
break;
}
}
//if flag true, text is palindrome
if (flag)
{
Console.WriteLine("{0} is palindrome", text);
}
else
{
Console.WriteLine("{0} is not palindrome", text);
}
Console.ReadLine();
}
Example 35: Converting Algorithm of Decimal to Binary in C#
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
class Program
{
staticvoid Main(string[] args)
{
int number;
Console.Write("Enter a Number : ");
number = int.Parse(Console.ReadLine());
int q;
string rem = "";
while (number >= 1)
{
q = number / 2;
rem += (number % 2).ToString();
number = q;
}
string binary = "";
for (int i = rem.Length - 1; i >= 0; i--)
{
binary = binary + rem[i];
}
Console.WriteLine("The Binary format for {0} is {1}",number, binary);
Console.ReadLine();
}
}
Other way: You can convert decimal to number, If you want to without think any algorithm
1
2
3
4
5
class Program
{
staticvoid Main(string[] args)
{
6
7
8
9
10
11
12
13
14
Console.Write("Enter a number : ");
int number = Convert.ToInt32(Console.ReadLine());
string binary = Convert.ToString(number, 2);
Console.WriteLine("The Binary format for {0} is {1}",number, binary);
Console.ReadLine();
}
}
Output:
Example 36: Find The Second Largest Number in Array Using C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
staticvoid Main(string[] args)
{
int n, i, j = 0, largest, secondLargest;
int[] arr1 = new int[50];
Console.Write("nnFind the second largest element in an array :n");
Console.Write("-----------------------------------------n");
Console.Write("Input the sizeof array : ");
n = Convert.ToInt32(Console.ReadLine());
/* Stored values into the array*/
Console.Write("Input {0} elements in the array :n", n);
for (i = 0; i < n; i++)
{
Console.Write("element - {0} : ", i);
arr1[i] = Convert.ToInt32(Console.ReadLine());
}
/* find location of the largest element in the array */
largest = 0;
for (i = 0; i < n; i++)
{
if (largest < arr1[i])
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
{
largest = arr1[i];
j = i;
}
}
/* ignore the largest element and find the 2nd largest element in the array */
secondLargest = 0;
for (i = 0; i < n; i++)
{
if (i == j)
{
i++; /* ignoring the largest element */
i--;
}
else
{
if (secondLargest < arr1[i])
{
secondLargest = arr1[i];
}
}
}
Console.Write("The Second largest element in the array is : {0} nn", secondLargest);
Console.ReadKey();
}
Example 36: Enter Only Numbers in C# Console Application using do-while loop
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
staticvoid Main(string[] args)
{
double val = 0;
string num = "";
Console.Write("Enter Number: ");
ConsoleKeyInfo chr;
do
{
chr = Console.ReadKey(true);
if (chr.Key != ConsoleKey.Backspace)
{
bool control = double.TryParse(chr.KeyChar.ToString(), out val);
if (control)
{
num += chr.KeyChar;
Console.Write(chr.KeyChar);
}
}
else
{
if (chr.Key == ConsoleKey.Backspace && num.Length > 0)
{
num = num.Substring(0, (num.Length - 1));
Console.Write("b b");
}
}
}
while (chr.Key != ConsoleKey.Enter);
Console.ReadKey();
32
33
}
Example 37: C# Program to Calculate the Power of a Number Without Using Math.Pow using
while loop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Program
{
staticvoid Main(string[] args)
{
int baseNumber, expNumber, result = 1;
Console.Write("Base Number : ");
baseNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("exponent Number : ");
expNumber = Convert.ToInt32(Console.ReadLine());
while (expNumber != 0)
{
result *= baseNumber;
--expNumber;
}
Console.WriteLine("Result = {0}", result);
Console.ReadLine();
}
}
Example 38: Fibonacci Series in C# with Method
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test
{
class Program
{
staticlong[] numbers;
staticlong Fib(int n)
{
if (0 == numbers[n])
{
numbers[n] = Fib(n - 1) + Fib(n - 2);
}
return numbers[n];
}
staticvoid Main()
{
Console.Write("n = ");
27
28
29
30
31
32
33
34
35
36
37
int n = int.Parse(Console.ReadLine());
numbers = new long[n + 2];
numbers[1] = 1;
numbers[2] = 1;
long result = Fib(n);
Console.WriteLine("fib({0}) = {1}", n, result);
Console.ReadKey();
}
}
}
Example 39: Calculate Sum and Average of an Array in C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
staticvoid Main()
{
double sum=0, avg=0;
double[] numbers = { 10, 20, 50, 40};
for(int i=0;i<numbers.Length;i++)
{
sum += numbers[i];
}
avg = sum / numbers.Length;
Console.WriteLine("The Sum is : "+sum);
Console.WriteLine("The Average is : "+avg);
Console.ReadKey();
}
Example 40: Find Numbers Above and Below the Average in C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
staticvoid Main(string[] args)
{
int counter = 0;
int[] numbers = new int[10];
int sum=0,avg=0,low=0,high=0;
for(int i=0;i<10;i++)
{
Console.Write("Number {0}: ",(i+1));
numbers[i] = Convert.ToInt32(Console.ReadLine());
sum += numbers[i];
}
avg = sum / 10;
//avg = sum / numbers.Length;
for (int i=0;i<10;i++)
{
if(numbers[i]<avg)
{
low++;
}
else
{
high++;
24
25
26
27
28
29
30
31
32
}
}
Console.WriteLine("The average is : {0}", avg);
Console.WriteLine("The numbers above the average are: {0}", high);
Console.WriteLine("The numbers below the average are: {0}", low);
Console.ReadKey();
}
Find The Longest Word in String
Array
class Program
{
staticvoid Main(string[] args)
{
string[] arr = { "Chsarp", "Console","Examples","www.csharp-console-examples.com" };
string longWord = "";
int Wordcount = 0;
foreach (string item in arr)
{
if (item.Length > Wordcount)
{
Wordcount = item.Length;
longWord = item;
}
}
Console.WriteLine("The longest word: {0} nLetters count : {1}", longWord, Wordcount);
Console.ReadKey();
}
}
Output:
C# console applications.docx

C# console applications.docx

  • 1.
    C# Console Application Examples(50+ C# Examples) 4 years ago 2 Comments by Mike 67,039 views C# is a simple, modern, general-purpose, object-oriented and high-level programming language originally developed by Microsoft and released in 2002. This tutorial gives a complete understanding of C#. This reference will take you through simple and practical approaches while learning C# Programming language. There are more over 40 examples in this C# examples list. And C# Examples are listing from basic to complex Basic C# Examples Example 1: C# Program to Print Hello World 1 2 3 4 5 6 7 8 9 10 class Program { staticvoid Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadKey(); } } Example 2: C# Program to Print an Integer Entered by User 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Program { staticvoid Main(string[] args) { int number; Console.Write("Enter a number:"); number = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("You entered :{0}",number); Console.ReadLine(); } }
  • 2.
    Example 3: C#Program to Add Two Integers 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Program { staticvoid Main(string[] args) { int num1, num2, sum; Console.WriteLine("Calculate the sum of two numbers:"); Console.Write("Input number1:"); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Input number2:"); num2 = Convert.ToInt32(Console.ReadLine()); sum = num1 + num2; Console.Write("Result:"+sum); Console.ReadKey(); } } Example 4: C# Program to Multiply two Floating Point Numbers Entered by User 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Program { staticvoid Main(string[] args) { float number1,number2,product; Console.Write("Enter a number1:"); number1 = Convert.ToSingle(Console.ReadLine()); Console.Write("Enter a number2:"); number2 = Convert.ToSingle(Console.ReadLine()); product = number1 * number2; Console.WriteLine("{0} * {1} = {2}",number1,number2, product); Console.ReadLine(); } } Example 5: Multiply Two Floating Point Numbers in C# Console 1 2 3 4 5 6 7 8 9 10 class Program { staticvoid Main(string[] args) { float number1,number2,product; number1 = 12.45f; number2 = 10.74f; product = number1 * number2;
  • 3.
    11 12 13 14 15 16 Console.WriteLine("{0} * {1}= {2}",number1,number2, product); Console.ReadLine(); } } Example 6: C# Program to Compute Quotient and Remainder 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Program { staticvoid Main(string[] args) { int dividend = 50, divisor = 8; int quotient = dividend / divisor; int remainder = dividend % divisor; Console.WriteLine("Dividend:{0} Divisor:{1}",dividend,divisor); Console.WriteLine("Quotient = " + quotient); Console.WriteLine("Remainder = " + remainder); Console.ReadLine(); } } Example 7: Program To Calculate the Simple Interest in C# Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 int P, T; float R, SI; Console.Write("Enter Amount :"); P = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter Rate :"); R = Convert.ToSingle(Console.ReadLine()); Console.Write("Enter Time :"); T = Convert.ToInt32(Console.ReadLine()); SI = P * R * T / 100; Console.WriteLine("Interest is :{0}", SI); Console.ReadKey(); Console.ReadLine(); Output:
  • 4.
    Example 8: C#Calculate Rectangle Area Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Program { staticvoid Main(string[] args) { int area, length, width; Console.Write("Please write the length of your rectangle: "); length = Convert.ToInt32(Console.ReadLine()); Console.Write("Please write the width of your rectangle: "); width = Convert.ToInt32(Console.ReadLine()); area = length * width; Console.WriteLine("The area of rectangle : {0}", area); Console.ReadKey(); } } Output:
  • 5.
    Example 9: C#Square Area and Perimeter Calculator Code: 1 2 3 4 5 6 7 8 9 10 11 12 staticvoid Main(string[] args) { int squareheight,area,perimeter; Console.Write("What is theheight of your square? :"); squareheight = Convert.ToInt32(Console.ReadLine()); area = squareheight * squareheight; perimeter = 4 * squareheight; Console.WriteLine("Area : {0}nPerimeter : {1}",area,perimeter); // "n"--> new line Console.ReadKey(); } Output: Example 10: Area and Perimeter of Circle in C# Console Application Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Program { staticvoid Main(string[] args) { double r,perimeter, area; Console.Write("Please write the radius of your circle : "); r = Convert.ToDouble(Console.ReadLine()); perimeter = 2 * 3.14 * r; area = 3.14 * Math.Pow(r, 2);//area = 3.14 * r * r; Console.WriteLine("============================================="); Console.WriteLine("The perimeter of yor circle : {0}",perimeter); Console.WriteLine("The area of yor circle : {0}", area); Console.ReadKey(); } }
  • 6.
    Example 11: Programto finds the average of 3 numbers in C# Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Program { staticvoid Main(string[] args) { int number1,number2,number3,avarage; Console.Write("Enter 1st number :"); number1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter 2nd number :"); number2 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter 3rd number :"); number3 = Convert.ToInt32(Console.ReadLine()); avarage = (number1 + number2 + number3) / 3; Console.Write("Avarage of three numbers is {0}",avarage); Console.ReadKey(); } } Output:
  • 7.
    Example 12: C#Math.Pow Example Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 double baseNumber, powerNumber; Console.Write("Enter base number :"); baseNumber = Convert.ToDouble(Console.ReadLine()); Console.Write("Enter exponent number :"); powerNumber = Convert.ToDouble(Console.ReadLine()); double returnNumber = Math.Pow(baseNumber, powerNumber); Console.WriteLine("{0}^{1} = {2}", baseNumber, powerNumber, returnNumber); Console.ReadLine(); Output:
  • 8.
    Example 13: C#Math.Pow Negative Exponent Example Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 double baseNumber, powerNumber; Console.Write("Enter base number :"); baseNumber = Convert.ToDouble(Console.ReadLine()); //2 Console.Write("Enter exponent number :"); powerNumber = Convert.ToDouble(Console.ReadLine()); //-2 double returnNumber = Math.Pow(baseNumber, powerNumber); Console.WriteLine("{0}^{1} = {2}", baseNumber, powerNumber, returnNumber); Console.ReadLine(); Output:
  • 9.
    Example 14: C#Program to Count Number of Words in a String Code: 1 2 3 4 5 6 7 8 9 10 11 staticvoid Main(string[] args) { string sentence; Console.Write("Enter String : "); sentence = Console.ReadLine(); string[] words = sentence.Split(' '); Console.WriteLine("Count of words :"+words.Length); Console.ReadKey(); } Output:
  • 10.
    Example 15: ConvertDollars to Cents in C# Solution 1: Calculate in Main Method 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Program { staticvoid Main(string[] args) { double dollar_amount; int cents; // int compute_cents; Console.Write("Enter dollar amount :"); dollar_amount = Convert.ToDouble(Console.ReadLine()); cents =(int) (dollar_amount * 100); Console.WriteLine("{0} $ = {1} ¢",dollar_amount,cents); Console.ReadLine(); } } Solution 2: Calculate with Custom Method 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 class Program { staticvoid Main(string[] args) { double dollar_amount; int cents; // int compute_cents; Console.Write("Enter dollar amount :"); dollar_amount = Convert.ToDouble(Console.ReadLine()); cents = compute_cents(dollar_amount); Console.WriteLine("{0} $ = {1} ¢",dollar_amount,cents); Console.ReadLine(); } staticint compute_cents(double dollar_amount) { return (int)(dollar_amount * 100); } } Output:
  • 11.
    For More SimpleExamples C# Conditional Examples Example 16: Fibonacci Series in C# with Method C# Code: 1 2 3 4 5 6 7 8 9 10 11 12 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test { class Program { staticlong[] numbers;
  • 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 staticlong Fib(int n) { if(0 == numbers[n]) { numbers[n] = Fib(n - 1) + Fib(n - 2); } return numbers[n]; } staticvoid Main() { Console.Write("n = "); int n = int.Parse(Console.ReadLine()); numbers = new long[n + 2]; numbers[1] = 1; numbers[2] = 1; long result = Fib(n); Console.WriteLine("fib({0}) = {1}", n, result); Console.ReadKey(); } } } Output: Example 17: Find Number is Even or Odd using if else Statement in C# Code 1: 1 2 3 4 5 6 7 8 9 10 11 staticvoid Main(string[] args) { int n; Console.Write("Enter an integer : "); n = Int32.Parse(Console.ReadLine()); if(n%2==0) { Console.WriteLine("{0} is even",n); } else
  • 13.
    12 13 14 15 16 17 { Console.WriteLine("{0} is odd",n); } Console.ReadKey(); } Code 2 (with static method): 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 class Program { staticbool IsEvenNumber(int num) { if (num % 2 == 0) { return true; } else { return false; } } staticvoid Main(string[] args) { int n; Console.Write("Enter an integer : "); n = Int32.Parse(Console.ReadLine()); if (IsEvenNumber(n)) { Console.WriteLine("{0} is even", n); } else { Console.WriteLine("{0} is odd", n); } Console.ReadKey(); } } Output:
  • 14.
    Example 18: FindNumbers Above and Below the Average in C# C# Code: 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 staticvoid Main(string[] args) { int counter = 0; int[] numbers = new int[10]; int sum=0,avg=0,low=0,high=0; for(int i=0;i<10;i++) { Console.Write("Number {0}: ",(i+1)); numbers[i] = Convert.ToInt32(Console.ReadLine()); sum += numbers[i]; } avg = sum / 10; //avg = sum / numbers.Length; for (int i=0;i<10;i++) { if(numbers[i]<avg) { low++; } else { high++; } } Console.WriteLine("The average is : {0}", avg); Console.WriteLine("The numbers above the average are: {0}", high); Console.WriteLine("The numbers below the average are: {0}", low); Console.ReadKey(); } Output:
  • 15.
    Example 19: C#Program to Print all Prime Numbers in an Interval Source Code: 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 staticvoid Main(string[] args) { int num1, num2,sayac=0; Console.Write("Enter lower range: "); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter upper range: "); num2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Prime numbers between {0} and {1} are: ",num1,num2); Console.WriteLine("=============================================="); for(int i=num1;i<num2;i++) { sayac = 0; if(i>1) { for(int j=2;j<i;j++) { if(i%j==0) { sayac = 1; break; } } if(sayac==0) { Console.WriteLine(i); } } } Console.ReadKey(); } Output:
  • 16.
    Example 20: Findingthe biggest of three numbers in C# C# Code: 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 staticvoid Main(string[] args) { int number1, number2, number3; string result; Console.Write("Input the first number :"); number1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Input the second number :"); number2 = Convert.ToInt32(Console.ReadLine()); Console.Write("Input the third number :"); number3 = Convert.ToInt32(Console.ReadLine()); if (number1 > number2 && number1 > number3) { result= "The 1st Number is the greatest among three. n"; } else if (number2 > number1 && number2 > number3) { result = "The 2nd Number is the greatest among three n"; } else { result= "The 3rd Number is the greatest among three n"; } Console.WriteLine(result); Console.ReadLine(); } Output: Example 21: Generates the Sum of N Numbers in C#
  • 17.
    Code: 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 class Program { staticvoid Main(string[]args) { int number, sum=0; Console.Write("Enter a Number : "); number = Convert.ToInt32(Console.ReadLine()); if(number<0) { Console.Write("Please Enter Positive Number"); } else { while(number>0) { sum += number; number -=1; } } Console.WriteLine("The sum is "+sum); Console.ReadKey(); } } Output:
  • 18.
    Example 22: Countingprogram the total letter in text in C# Console Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 staticvoid Main(string[] args) { string myString = Console.ReadLine(); int count = 0; for (int i = 0; i < myString.Length; i++) { // check thechar for whitespace. If char is not whitespace, increase the count variable if (!char.IsWhiteSpace(myString[i])) { count++; } } Console.WriteLine("Total letters: "+ count); Console.ReadLine(); } Alternavite code (foreach loop): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 staticvoid Main(string[] args) { Console.Write("Enter string :"); string myString = Console.ReadLine(); int count = 0; foreach (char item in myString) { // check thechar for whitespace. If char is not whitespace, increase the count variable if (!char.IsWhiteSpace(item)) { count++; } } Console.WriteLine("Total letters: "+ count); Console.ReadLine(); } Output:
  • 19.
    Example 23: GetMonth Name From Month Number – C#(Switch Case) C# Code: 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 class Program { staticvoid Main(string[] args) { int monthNumber; Console.Write("Enter Month Number (1 - 12): "); monthNumber = Convert.ToInt32(Console.ReadLine()); switch (monthNumber) { case 1: Console.WriteLine("January"); break; case 2: Console.WriteLine("February"); break; case 3: Console.WriteLine("March"); break; case 4: Console.WriteLine("April"); break; case 5: Console.WriteLine("May"); break; case 6: Console.WriteLine("June"); break; case 7: Console.WriteLine("July");
  • 20.
    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 break; case 8: Console.WriteLine("August"); break; case 9: Console.WriteLine("September"); break; case10: Console.WriteLine("October"); break; case 11: Console.WriteLine("November"); break; case 12: Console.WriteLine("December"); break; default: Console.WriteLine("you did not enter correct value for month name"); break; } Console.ReadLine(); } } Output: Example 24: Program Library Fine Calculation in C# The fee structure is as follows: 1. If the book is returned on before 5 days, no fine will be charged. 2. If the book is returned after the expected return day (between 5 and 10 days) – fine: 0.5$ per day 3. If the book is returned after the expected return day (between 10 and 30 days) fine: 1$ per day 4. If the book is not returned after 30 days, cancel membership. fine: 1.5$ per day Code:
  • 21.
    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 class Program { staticvoid Main(string[]args) { int days; float fine=0; Console.Write("Enter totaldays:"); days = Convert.ToInt32(Console.ReadLine()); if(days <= 5) { fine = 0; } else if(days > 5 && days <= 10) { fine = (days - 5) * 0.5F; } else if(days > 10 && days <=30) { // ----5 days--- --between 10 and 30--- fine = 5 * 0.5F + (days - 10) * 1; } else { // -5 days- -10 , 30- - >30 - fine = 5 * 0.5F + 20 * 1 + (days-30) * 1.5F; Console.WriteLine("Canceled your Membership"); } Console.WriteLine("Your fine:"+fine); Console.ReadLine(); } } Output
  • 22.
    Example 25: Programto Find Leap Year in C# Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 staticvoid Main(string[] args) { int year; Console.Write("Enter theYear :"); year = Convert.ToInt32(Console.ReadLine()); if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) Console.WriteLine("{0} is Leap Year",year); else Console.WriteLine("{0} is not a Leap Year",year); Console.ReadLine(); } Output: For Mode If Else Examples C# Loop Examples
  • 23.
    Example 26: C#program to find min and max in an array Code: 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 class Program { staticvoid Main(string[] args) { //www.csharp-console-examples.com int[] numbers = new int[10]; Random rnd = new Random(); int min, max; for (int i = 0; i < numbers.Length; i++) { numbers[i] = rnd.Next(1, 100); Console.WriteLine(numbers[i]); } min = numbers[0]; max = numbers[0]; for (int i = 1; i < numbers.Length; i++) { if (min > numbers[i]) min = numbers[i]; if (max < numbers[i]) max = numbers[i]; } Console.WriteLine("====================================="); Console.WriteLine("The highest number in the array: > > > " + max); Console.WriteLine("The lowest number in thearray: > > > " + min); Console.ReadKey(); } } Output: C# program using for loop to find maximum value from an array
  • 24.
    Example 27: C#Program to Calculate the Power of a Number Without Using Math.Pow Code:(With for loop) 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 class Program { staticvoid Main(string[] args) { int baseNumber, expNumber; double result = 1; Console.Write("Base Number : "); baseNumber = Convert.ToInt32(Console.ReadLine()); Console.Write("exponent Number : "); expNumber = Convert.ToInt32(Console.ReadLine()); bool sing = false; if (expNumber > 0) sing = true; expNumber = Math.Abs(expNumber); for (int i = 1; i <= expNumber; i++) { if(sing) result = result * baseNumber; else result /= baseNumber; } Console.WriteLine("Base {0} and exponent {1} Result = {2}", baseNumber, expNumber, result); Console.ReadLine(); } }
  • 25.
    30 Code: (With WhileLoop) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Program { staticvoid Main(string[] args) { int baseNumber, expNumber, result = 1; Console.Write("Base Number : "); baseNumber = Convert.ToInt32(Console.ReadLine()); Console.Write("exponent Number : "); expNumber = Convert.ToInt32(Console.ReadLine()); while (expNumber != 0) { result *= baseNumber; --expNumber; } Console.WriteLine("Result = {0}", result); Console.ReadLine(); } } Output:
  • 26.
    Example 28: C#Program to Find the Factorial of a Number Source Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 staticvoid Main(string[] args) { int i, number, fact; Console.WriteLine("Enter theNumber"); number = int.Parse(Console.ReadLine()); fact = number; for (i = number - 1; i >= 1; i--) { fact = fact * i; } Console.WriteLine("nFactorial of Given Number is: "+fact); Console.ReadLine(); } Output: Example 29: Display Numbers Between 1 to N Using For Loop Code: 1 2 3 4 5 6 staticvoid Main(string[] args) { int n; Console.Write("Number :"); n = Convert.ToInt32(Console.ReadLine());
  • 27.
    7 8 9 10 11 12 13 for (int i= 1; i <= n; i++) { Console.WriteLine(i); } Console.ReadKey(); } Output: Example 30: Generates the Sum of N Numbers in C# Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Program { staticvoid Main(string[] args) { int number, sum=0; Console.Write("Enter a Number : "); number = Convert.ToInt32(Console.ReadLine()); if(number<0) { Console.Write("Please Enter Positive Number"); } else { while(number>0) { sum += number; number -=1; } } Console.WriteLine("The sum is "+sum);
  • 28.
    24 25 26 27 28 Console.ReadKey(); } } Output: Example 31: C#Program to Print all Prime Numbers in an Interval Source Code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 staticvoid Main(string[] args) { int num1, num2,sayac=0; Console.Write("Enter lower range: "); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter upper range: "); num2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Prime numbers between {0} and {1} are: ",num1,num2); Console.WriteLine("=============================================="); for(int i=num1;i<num2;i++) { sayac = 0; if(i>1) { for(int j=2;j<i;j++) { if(i%j==0) { sayac = 1;
  • 29.
    21 22 23 24 25 26 27 28 29 30 31 32 break; } } if(sayac==0) { Console.WriteLine(i); } } } Console.ReadKey(); } Output: Example 32: NestedFor Loop in C# (Multiplication Table) Code 1: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 staticvoid Main(string[] args) { //www.csharp-console-examples.com for (int i=1;i<=10;i++) { for (int j = 0; j <= 10; j++) { Console.WriteLine("{0}x{1} = {2}", i, j, i * j); } Console.WriteLine("===================="); } Console.ReadKey(); } Output:
  • 30.
    Code 2: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 staticvoid Main(string[]args) { //www.csharp-console-examples.com for (int j = 1; j <= 10; j++) { for (int i = 1; i <= 10; i++) { Console.Write("{0}*{1}={2}t", i, j, (i * j)); } Console.WriteLine(); } Console.ReadKey(); } Output:
  • 31.
    Example 33: DisplayArmstrong Number Between Two Intervals in C# Code: 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 staticvoid Main(string[] args) { int num1,num2, n, sum, r; Console.Write("Enter positivenumber1 :"); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter positivenumber2 :"); num2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Armstrong Number from {0} to {1}",num1,num2); for (int i = num1; i <= num2; i++) { sum = 0; n = i; while (n != 0) { r = n % 10; sum = sum + (r * r * r); n = n / 10; } if (i == sum) Console.WriteLine(i); } Console.ReadKey(); }
  • 32.
    Example 34: Checkingfor Palindrome Strings or Numbers in C# Code: 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 staticvoid Main(string[] args) { Console.Write("Enter something for to check that is it palindrome :"); string text = Console.ReadLine(); int len = text.Length; bool flag = true; //check palindrome for (int i = 0; i < len/2; i++) { if (text[i] != text[len - (i + 1)]) { flag = false; break; } } //if flag true, text is palindrome if (flag) { Console.WriteLine("{0} is palindrome", text); } else { Console.WriteLine("{0} is not palindrome", text); } Console.ReadLine(); }
  • 33.
    Example 35: ConvertingAlgorithm of Decimal to Binary in C# 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 class Program { staticvoid Main(string[] args) { int number; Console.Write("Enter a Number : "); number = int.Parse(Console.ReadLine()); int q; string rem = ""; while (number >= 1) { q = number / 2; rem += (number % 2).ToString(); number = q; } string binary = ""; for (int i = rem.Length - 1; i >= 0; i--) { binary = binary + rem[i]; } Console.WriteLine("The Binary format for {0} is {1}",number, binary); Console.ReadLine(); } } Other way: You can convert decimal to number, If you want to without think any algorithm 1 2 3 4 5 class Program { staticvoid Main(string[] args) {
  • 34.
    6 7 8 9 10 11 12 13 14 Console.Write("Enter a number: "); int number = Convert.ToInt32(Console.ReadLine()); string binary = Convert.ToString(number, 2); Console.WriteLine("The Binary format for {0} is {1}",number, binary); Console.ReadLine(); } } Output: Example 36: Find The Second Largest Number in Array Using C# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 staticvoid Main(string[] args) { int n, i, j = 0, largest, secondLargest; int[] arr1 = new int[50]; Console.Write("nnFind the second largest element in an array :n"); Console.Write("-----------------------------------------n"); Console.Write("Input the sizeof array : "); n = Convert.ToInt32(Console.ReadLine()); /* Stored values into the array*/ Console.Write("Input {0} elements in the array :n", n); for (i = 0; i < n; i++) { Console.Write("element - {0} : ", i); arr1[i] = Convert.ToInt32(Console.ReadLine()); } /* find location of the largest element in the array */ largest = 0; for (i = 0; i < n; i++) { if (largest < arr1[i])
  • 35.
    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 { largest = arr1[i]; j= i; } } /* ignore the largest element and find the 2nd largest element in the array */ secondLargest = 0; for (i = 0; i < n; i++) { if (i == j) { i++; /* ignoring the largest element */ i--; } else { if (secondLargest < arr1[i]) { secondLargest = arr1[i]; } } } Console.Write("The Second largest element in the array is : {0} nn", secondLargest); Console.ReadKey(); } Example 36: Enter Only Numbers in C# Console Application using do-while loop 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 staticvoid Main(string[] args) { double val = 0; string num = ""; Console.Write("Enter Number: "); ConsoleKeyInfo chr; do { chr = Console.ReadKey(true); if (chr.Key != ConsoleKey.Backspace) { bool control = double.TryParse(chr.KeyChar.ToString(), out val); if (control) { num += chr.KeyChar; Console.Write(chr.KeyChar); } } else { if (chr.Key == ConsoleKey.Backspace && num.Length > 0) { num = num.Substring(0, (num.Length - 1)); Console.Write("b b"); } } } while (chr.Key != ConsoleKey.Enter); Console.ReadKey();
  • 36.
    32 33 } Example 37: C#Program to Calculate the Power of a Number Without Using Math.Pow using while loop 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Program { staticvoid Main(string[] args) { int baseNumber, expNumber, result = 1; Console.Write("Base Number : "); baseNumber = Convert.ToInt32(Console.ReadLine()); Console.Write("exponent Number : "); expNumber = Convert.ToInt32(Console.ReadLine()); while (expNumber != 0) { result *= baseNumber; --expNumber; } Console.WriteLine("Result = {0}", result); Console.ReadLine(); } } Example 38: Fibonacci Series in C# with Method 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 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test { class Program { staticlong[] numbers; staticlong Fib(int n) { if (0 == numbers[n]) { numbers[n] = Fib(n - 1) + Fib(n - 2); } return numbers[n]; } staticvoid Main() { Console.Write("n = ");
  • 37.
    27 28 29 30 31 32 33 34 35 36 37 int n =int.Parse(Console.ReadLine()); numbers = new long[n + 2]; numbers[1] = 1; numbers[2] = 1; long result = Fib(n); Console.WriteLine("fib({0}) = {1}", n, result); Console.ReadKey(); } } } Example 39: Calculate Sum and Average of an Array in C# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 staticvoid Main() { double sum=0, avg=0; double[] numbers = { 10, 20, 50, 40}; for(int i=0;i<numbers.Length;i++) { sum += numbers[i]; } avg = sum / numbers.Length; Console.WriteLine("The Sum is : "+sum); Console.WriteLine("The Average is : "+avg); Console.ReadKey(); } Example 40: Find Numbers Above and Below the Average in C# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 staticvoid Main(string[] args) { int counter = 0; int[] numbers = new int[10]; int sum=0,avg=0,low=0,high=0; for(int i=0;i<10;i++) { Console.Write("Number {0}: ",(i+1)); numbers[i] = Convert.ToInt32(Console.ReadLine()); sum += numbers[i]; } avg = sum / 10; //avg = sum / numbers.Length; for (int i=0;i<10;i++) { if(numbers[i]<avg) { low++; } else { high++;
  • 38.
    24 25 26 27 28 29 30 31 32 } } Console.WriteLine("The average is: {0}", avg); Console.WriteLine("The numbers above the average are: {0}", high); Console.WriteLine("The numbers below the average are: {0}", low); Console.ReadKey(); } Find The Longest Word in String Array class Program { staticvoid Main(string[] args) { string[] arr = { "Chsarp", "Console","Examples","www.csharp-console-examples.com" }; string longWord = ""; int Wordcount = 0; foreach (string item in arr) { if (item.Length > Wordcount) { Wordcount = item.Length; longWord = item; } } Console.WriteLine("The longest word: {0} nLetters count : {1}", longWord, Wordcount); Console.ReadKey(); } } Output: