SlideShare a Scribd company logo
1 of 39
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

More Related Content

Similar to C# console applications.docx

Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Abou Bakr Ashraf
 
Basic VB problems
Basic VB problemsBasic VB problems
Basic VB problemsMukesh Das
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdfchoconyeuquy
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docxrosemarybdodson23141
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to cHattori Sidek
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answersdebarghyamukherjee60
 
Cmis 102 Effective Communication / snaptutorial.com
Cmis 102  Effective Communication / snaptutorial.comCmis 102  Effective Communication / snaptutorial.com
Cmis 102 Effective Communication / snaptutorial.comHarrisGeorg12
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)ExcellenceAcadmy
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)ExcellenceAcadmy
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manualAnil Bishnoi
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignmentSaket Pathak
 
Cmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.comCmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.comStephenson22
 
Cmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.comCmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.comWilliamsTaylorza48
 
Computer Project For Class XII Topic - The Snake Game
Computer Project For Class XII Topic - The Snake Game Computer Project For Class XII Topic - The Snake Game
Computer Project For Class XII Topic - The Snake Game Pritam Samanta
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184Mahmoud Samir Fayed
 

Similar to C# console applications.docx (20)

Hems
HemsHems
Hems
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
Basic VB problems
Basic VB problemsBasic VB problems
Basic VB problems
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdf
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
1 c introduction
1 c introduction1 c introduction
1 c introduction
 
Class 12 computer sample paper with answers
Class 12 computer sample paper with answersClass 12 computer sample paper with answers
Class 12 computer sample paper with answers
 
Cmis 102 Effective Communication / snaptutorial.com
Cmis 102  Effective Communication / snaptutorial.comCmis 102  Effective Communication / snaptutorial.com
Cmis 102 Effective Communication / snaptutorial.com
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
 
College1
College1College1
College1
 
Programming with c language practical manual
Programming with c language practical manualProgramming with c language practical manual
Programming with c language practical manual
 
C++
C++C++
C++
 
C++ lab assignment
C++ lab assignmentC++ lab assignment
C++ lab assignment
 
Cmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.comCmis 102 Enthusiastic Study / snaptutorial.com
Cmis 102 Enthusiastic Study / snaptutorial.com
 
Cmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.comCmis 102 Success Begins / snaptutorial.com
Cmis 102 Success Begins / snaptutorial.com
 
Computer Project For Class XII Topic - The Snake Game
Computer Project For Class XII Topic - The Snake Game Computer Project For Class XII Topic - The Snake Game
Computer Project For Class XII Topic - The Snake Game
 
The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184The Ring programming language version 1.5.3 book - Part 91 of 184
The Ring programming language version 1.5.3 book - Part 91 of 184
 
C fundamentals
C fundamentalsC fundamentals
C fundamentals
 

More from MehwishKanwal14

CS410 Visual Programming Master of Information Technology VU University Past ...
CS410 Visual Programming Master of Information Technology VU University Past ...CS410 Visual Programming Master of Information Technology VU University Past ...
CS410 Visual Programming Master of Information Technology VU University Past ...MehwishKanwal14
 
14420-Article Text-17938-1-2-20201228.pdf
14420-Article Text-17938-1-2-20201228.pdf14420-Article Text-17938-1-2-20201228.pdf
14420-Article Text-17938-1-2-20201228.pdfMehwishKanwal14
 
Wajid Shah-MCS143027.pdf
Wajid Shah-MCS143027.pdfWajid Shah-MCS143027.pdf
Wajid Shah-MCS143027.pdfMehwishKanwal14
 
Comp App Lect 5 part 2.pptx
Comp App  Lect 5 part 2.pptxComp App  Lect 5 part 2.pptx
Comp App Lect 5 part 2.pptxMehwishKanwal14
 
Comp App lect 3 (Software).ppt
Comp App lect 3 (Software).pptComp App lect 3 (Software).ppt
Comp App lect 3 (Software).pptMehwishKanwal14
 
Comp App Lect 2 System Unit.pptx
Comp App Lect 2 System Unit.pptxComp App Lect 2 System Unit.pptx
Comp App Lect 2 System Unit.pptxMehwishKanwal14
 

More from MehwishKanwal14 (11)

CS410 Visual Programming Master of Information Technology VU University Past ...
CS410 Visual Programming Master of Information Technology VU University Past ...CS410 Visual Programming Master of Information Technology VU University Past ...
CS410 Visual Programming Master of Information Technology VU University Past ...
 
14420-Article Text-17938-1-2-20201228.pdf
14420-Article Text-17938-1-2-20201228.pdf14420-Article Text-17938-1-2-20201228.pdf
14420-Article Text-17938-1-2-20201228.pdf
 
projects2021C3.pdf
projects2021C3.pdfprojects2021C3.pdf
projects2021C3.pdf
 
Wajid Shah-MCS143027.pdf
Wajid Shah-MCS143027.pdfWajid Shah-MCS143027.pdf
Wajid Shah-MCS143027.pdf
 
Comp App Lect 5 part 2.pptx
Comp App  Lect 5 part 2.pptxComp App  Lect 5 part 2.pptx
Comp App Lect 5 part 2.pptx
 
Comp App Lect 4.pptx
Comp App Lect 4.pptxComp App Lect 4.pptx
Comp App Lect 4.pptx
 
Comp App Lect 1.ppt
Comp App Lect 1.pptComp App Lect 1.ppt
Comp App Lect 1.ppt
 
Comp App Lect 3.pptx
Comp App Lect 3.pptxComp App Lect 3.pptx
Comp App Lect 3.pptx
 
Comp App lect 3 (Software).ppt
Comp App lect 3 (Software).pptComp App lect 3 (Software).ppt
Comp App lect 3 (Software).ppt
 
Comp App Lect 2 System Unit.pptx
Comp App Lect 2 System Unit.pptxComp App Lect 2 System Unit.pptx
Comp App Lect 2 System Unit.pptx
 
Comp App Lect 2.pptx
Comp App Lect 2.pptxComp App Lect 2.pptx
Comp App Lect 2.pptx
 

Recently uploaded

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

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: 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:
  • 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: 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:
  • 11. 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;
  • 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: 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:
  • 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: 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#
  • 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: 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:
  • 19. 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");
  • 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; 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:
  • 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: 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
  • 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 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:
  • 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: 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:
  • 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: 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(); }
  • 32. 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(); }
  • 33. 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) {
  • 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: