0% found this document useful (0 votes)
6 views17 pages

C# Basic Programs with Examples

Basic programs .net

Uploaded by

Sandeep Sandy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

C# Basic Programs with Examples

Basic programs .net

Uploaded by

Sandeep Sandy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Contents

1. SWAPPING PROGRAM IN C# WITH EXAMPLES..........................................................................................2


A. Swapping two numbers using a third variable:........................................................................................2
B. The following program uses * and / to swaps two integer numbers without using the third variable....2
C. The following program uses + and – operator to swaps two integer values without using the third
variable in........................................................................................................................................................3
D. The following program swaps two strings without using the third variable............................................3
2. FIBONACCI SERIES PROGRAM IN C# WITH EXAMPLES...............................................................................4
3. PRIME NUMBERS IN C# WITH EXAMPLES...................................................................................................5
4. PALINDROME PROGRAM (NUMBER AND STRING) IN C# WITH EXAMPLES...............................................7
5. REVERSE A NUMBER AND A STRING IN C# WITH EXAMPLES...................................................................10
6. FACTORIAL NUMBER PROGRAM IN C# WITH EXAMPLES.........................................................................11
A. Factorial Number Program in C# using for loop.....................................................................................11
B. Factorials of a number using while loop................................................................................................11
C. Factorial of a number using Recursive Function....................................................................................11
D. Factorial of a number using the do-while loop......................................................................................12
7. SUM OF DIGITS PROGRAM IN C# WITH EXAMPLES:.................................................................................13
A. Finding the sum of digits of a given number using a loop......................................................................13
B. Using Linq to find the sum of digits of a number...................................................................................13
8. CHARACTER OCCURRENCE IN A STRING IN C# WITH EXAMPLES.............................................................14
9. USING LINQ TO REVERSE EACH WORD IN C#............................................................................................15
10. USING LINQ TO REMOVE DUPLICATE CHARACTERS FROM A STRING:.................................................16
11. HOW TO FIND THE ANGLE BETWEEN THE HOUR AND MINUTE HANDS OF A CLOCK AT ANY GIVEN
TIME IN C#.........................................................................................................................................................17
[Link] PROGRAM IN C# WITH EXAMPLES

A. Swapping two numbers using a third variable:

using System;
namespace LogicalPrograms
{
public class Program
{
public static void Main()
{
int number1 = 10, number2 = 20, temp = 0;
[Link]($"Before SWapping number1= {number1}, number2 = {number2}");
temp = number1; //temp=10
number1 = number2; //number1=20
number2 = temp; //number2=10
[Link]($"After swapping number1= {number1}, number2 = {number2}");
[Link]();
}
}
}

B. The following program uses * and / to swaps two integer


numbers without using the third variable.

number1 = number1 * number2; //number1=200 (10*20)


number2 = number1 / number2; //number2=10 (200/20)
number1 = number1 / number2; //number1=20 (200/10)
C. The following program uses + and – operator to swaps two
integer values without using the third variable in.

number1 = number1 + number2; //number1=30 (10+20)


number2 = number1 - number2; //number2=10 (30-20)
number1 = number1 - number2;

D. The following program swaps two strings without using


the third variable.

// Step1: append 2nd string with the 1st string


name1 = name1 + name2;
//Step2: store intial string name1 in string name2
name2 = [Link](0, [Link] - [Link]);
//Step3: store initial string name2 in string name1
name1 = [Link]([Link]);
[Link] SERIES PROGRAM IN C# WITH
EXAMPLES

using System;
namespace LogicalPrograms
{
public class Program
{
public static void Main()
{
int firstNumber = 0, SecondNumber = 1, nextNumber, numberOfElements;
[Link]("Enter the number of elements to Print : ");
numberOfElements = [Link]([Link]());
if(numberOfElements < 2)
{
[Link]("Please Enter a number greater than two");
}
else
{
//First print first and second number
[Link](firstNumber + " " + SecondNumber + " ");
//Starts the loop from 2 because 0 and 1 are already printed
for(int i = 2; i < numberOfElements; i++)
{
nextNumber = firstNumber + SecondNumber;
[Link](nextNumber + " ");
firstNumber = SecondNumber;
SecondNumber = nextNumber;
}
}
[Link]();
}
}
}

[Link] NUMBERS IN C# WITH EXAMPLES

A. How to check if a given number is prime or not.

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter a Number : ");
int number = [Link]([Link]());
bool IsPrime = true;

for (int i = 2; i <= number/2; i++)


{
if (number % i == 0)
{
[Link](i); // u will get from which table it will be divided
IsPrime = false;
break;
}
}

if (IsPrime)
{
[Link]("Number is Prime.");
}
else
{
[Link]("Number is not Prime.");
}
[Link]();
}
}
}
B. How to display Prints the Prime Numbers between a range of
numbers.

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter The Start Number: ");
int startNumber = [Link]([Link]());
[Link]("Enter the End Number : ");
int endNumber = Convert.ToInt32([Link]());
[Link]($"The Prime Numbers between {startNumber} and {endNumber} are : ");

for (int i = startNumber; i <= endNumber; i++)


{
int counter = 0;

for (int j = 2; j <= i / 2; j++)


{
if (i % j == 0)
{
counter++;
break;
}
}

if (counter == 0 && i != 1)
{
[Link]("{0} ", i);
}
}
[Link]();
}
}
}
[Link] PROGRAM (NUMBER AND STRING)
IN C# WITH EXAMPLES
A. Palindrome Number Program.

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter a Number To Check Palindrome : ");
int number = [Link]([Link]());
int remineder, sum = 0;
int temp = number;
while (number > 0)
{
//Get the remainder by dividing the number with 10
remineder = number % 10;

//multiply the sum with 10 and then add the remainder


sum = (sum * 10) + remineder;

//Get the quotient by dividing the number with 10


number = number / 10;
}
if (temp == sum)
{
[Link]($"Number {temp} is Palindrome.");
}
else
{
[Link]($"Number {temp} is not Palindrome");
}
[Link]();
}
}
}
B. How to check if a given string is Palindrome or not.

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter a string to Check Palindrome : ");
string name = [Link]();
string reverse = [Link];

for (int i = [Link] - 1; i >= 0; i--)


{
reverse += name[i];
}

if (name == reverse)
{
[Link]($"{name} is Palindrome.");
}
else
{
[Link]($"{name} is not Palindrome");
}
[Link]();
}
}
}
C. Another Approach of Implementing Palindrome String Program.

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main()
{
[Link]("Enter a string to Check Palindrome : ");
string name = [Link]();

char[] nameArray = [Link]();


[Link](nameArray);
string reverse = new string(nameArray);

if ([Link](reverse, [Link]))
{
[Link]($"{name} is Palindrome");
}
else
{
[Link]($"{name} is not Palindrome");
}
[Link]();
}
}
}
[Link] A NUMBER AND A STRING IN C# WITH
EXAMPLES

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter a String : ");
string name = [Link]();
string reverse = [Link];

for (int i = [Link] - 1; i >= 0; i--)


{
reverse += name[i];
}

[Link]($"The Reverse string is : {reverse}");


[Link]();
}
}
}

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter a String : ");
string name = [Link]();

char[] nameArray = [Link]();


[Link](nameArray);
string reverse = new string(nameArray);

[Link]($"The Reverse string is : {reverse}");


[Link]();
}
}
}
[Link] NUMBER PROGRAM IN C# WITH
EXAMPLES
A. Factorial Number Program in C# using for loop.

using System;
namespace LogicalPrograms
{
class Program
{
static void Main(string[] args)
{
[Link]("Enter a Number : ");
int number = [Link]([Link]());

int factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial = factorial * i;
}
[Link]($"Factorial of {number} is: {factorial}");

[Link]();
}
}
}

B. Factorials of a number using while loop.

while (number != 1)
{
factorial = factorial * number;
number = number - 1;
}

C. Factorial of a number using Recursive Function.

static long RecursiveFactorial(int number)


{
if (number == 1)
{
return 1;
}
else
{
return number * RecursiveFactorial(number - 1);
}
}

D. Factorial of a number using the do-while loop.

do
{
factorial = factorial * number;
number--;
} while (number > 0);
[Link] OF DIGITS PROGRAM IN C# WITH EXAMPLES:
A. Finding the sum of digits of a given number using a loop.

using System;
namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter the Number : ");
int number = [Link]([Link]());
int sum = 0, reminder;

while (number > 0)


{
reminder = number % 10;
sum = sum + reminder;
number = number / 10;
}

[Link]($"The Sum of Digits is : {sum}");


[Link]();
}
}
}
Output :236
ans = (2+3+6)=11

B. Using Linq to find the sum of digits of a number.

using System;
using [Link];

namespace LogicalPrograms
{
public class Program
{
static void Main(string[] args)
{
[Link]("Enter the Number : ");
int number = [Link]([Link]());

int sum = [Link]().Select(digit => [Link]([Link]())).ToArray().Sum();

[Link]($"The Sum of Digits is : {sum}");


[Link]();
}
}
}
[Link] OCCURRENCE IN A STRING IN C#
WITH EXAMPLES

using System;
namespace LogicalProgram
{
class Program
{
static void Main(string[] args)
{
[Link]("Enter the string : ");
string message = [Link]();

//Remove the empty spaces from the message


message = [Link](" ", [Link]);

while ([Link] > 0)


{
[Link](message[0] + " : ");
int count = 0;
for (int j = 0; j < [Link]; j++)
{
if (message[0] == message[j])
{
count++;
}
}
[Link](count);
message = [Link](message[0].ToString(), [Link]);
}

[Link]();
}
}
}
[Link] LINQ TO REVERSE EACH WORD IN C#

using System;
using [Link];

namespace LogicalPrograms
{
class Program
{
static void Main(string[] args)
{
[Link]("Enter a String : ");
string originalString = [Link]();

string reverseWordString = [Link](" ", originalString


.Split(' ')
.Select(x => new String([Link]().ToArray())));

[Link]($"Reverse Word String : {reverseWordString}");


[Link]();
}
}
}
output: welcome to home
emoclew ot emoh
10. USING LINQ TO REMOVE DUPLICATE
CHARACTERS FROM A STRING:

using [Link];
using System;
namespace LogicalPrograms
{
class Program
{
static void Main(string[] args)
{
[Link]("Enter a String : ");
string inputString = [Link]();

var uniqueCharArray = [Link]().Distinct().ToArray();


var resultString = new string(uniqueCharArray);

[Link]("After Removing Duplicates : " + resultString);


[Link]();
}
}
}
output: GOOGLE
GOLE
11. HOW TO FIND THE ANGLE BETWEEN THE
HOUR AND MINUTE HANDS OF A CLOCK AT ANY
GIVEN TIME IN C#

using System;
namespace LogicalPrograms
{
class Program
{
static void Main(string[] args)
{
[Link]("Enter the hours : ");
int hours = [Link]([Link]());
[Link]("Enter the Minutes : ");
int minutes = [Link]([Link]());

double hourInDegrees = (hours * 30) + (minutes * 30.0 / 60);


double minuteInDegrees = minutes * 6;

double diff = [Link](hourInDegrees - minuteInDegrees);

if (diff > 180)


{
diff = 360 - diff;
}

[Link]($"Angle between {hours} hour and {minutes} minute is {diff} degrees");


[Link]();
}
}
}
output: 9 hours 30 minutes
angle is 105 degrees

Common questions

Powered by AI

The program determines if a number is a palindrome by reversing its digits. It calculates the remainder of the number divided by ten to extract each digit, forms a reversed number by multiplying the current reversed number by ten and adding the extracted digit, then divides the number by ten to process the next digit. After reversing, it checks if the reversed number equals the original number .

Optimizing a string shift involves splitting the string into the segments: the last few characters and the rest. Using LINQ, reversing the string, selecting segments based on positions, and then reversing back to concatenate them efficiently achieves this. This approach eliminates the repeated overhead of manual shifting. A potential trade-off is the constant overhead in managing the transformations required by LINQ operations like Reverse and String.Join, particularly for large strings or small shifts where simpler logic would suffice .

The program first multiplies the two numbers (number1 = number1 * number2), which combines them into a product held in one of the original number variables. It then divides this product by the second number to restore the first number (number2 = number1 / number2), and finally, divides the product again by the new second number to restore the second number (number1 = number1 / number2). This operation swaps the values without the need of a third variable, but it is only applicable when neither of the numbers is zero .

Using LINQ allows for a more declarative style by converting the number to its string representation, selecting each digit, converting each back to an integer, and summing them directly. Compared to a traditional loop which iteratively extracts digits and adds them, LINQ offers a concise, readable method and potentially fewer lines of code, though it may incur additional overhead through multiple data conversions .

Using recursion to calculate a factorial involves a function calling itself with a decremented value until reaching the base case of 1. This approach can be elegant and easy to read but may consume more memory due to the function call stack, especially for large numbers . Iteration, on the other hand, involves looping through numbers multiplying them thus consuming less stack memory and being generally quicker, especially for large-scale computations .

The recursive approach to factorial calculation is straightforward to implement but is limited by stack size as each recursive call adds to the call stack. Its time complexity is O(n) due to n recursive calls needed to compute the factorial. However, each call operates at O(1), providing no advantage over iterative methods in terms of time complexity, and the lack of conservation of space compared to iterative methods hinders its scalability for very large n .

The calculation involves finding the degree positions of both hands separately. The hour hand moves 30 degrees per hour plus 0.5 degrees per minute passed. The minute hand moves 6 degrees per minute. The absolute difference between these two positions gives the angle, and if the computed angle exceeds 180 degrees, converting it to the smaller supplementary angle ensures the shortest distance is returned .

LINQ is used to reverse each word by first splitting the sentence into words based on spaces. It then applies a reverse operation on each word by selecting each character of the word and using the string's ToCharArray and Reverse methods. Finally, it joins these reversed words back into a single string with spaces in between . This approach utilizes LINQ's ability to query and manipulate sequences in a concise and readable manner.

The provided implementation uses a loop to iterate through the string, replacing already accounted characters with an empty space, thus counting unique character occurrences. While effective for small strings, this approach involves repeated string manipulation and could be improved by using a Dictionary to store character counts, reducing time complexity and improving performance for larger inputs .

The method involves iterating over each number in the user-specified range and checking divisibility by any number up to half its value. While straightforward, it can be inefficient as it does not utilize more efficient techniques like the Sieve of Eratosthenes. Checking only till the square root of the number would reduce the number of iteration steps required, thereby optimizing it .

You might also like