C# Prac File
C# Prac File
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello");
}
}
Output : Hello
2. Write a program to input number from user c#
using System;
class Program
You entered: 25
3. Write a program to input 2 numbers from user and output of adding, subtracting, multiplying of
numbers in c#
using System
class Program
Addition: 10 + 5 = 15
Subtraction: 10 - 5 = 5
Multiplication: 10 * 5 = 50
int sum = 0;
for (int i = 1; i <= num / 2; i++)
{
if (num % i == 0)
{
sum += i;
}
}
return sum == num;
}
}
Output : Enter a number: 496
496 is a perfect number.
18. Write a program to find factorial of given number using function.
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (number < 0)
{
Console.WriteLine("Factorial is not defined for negative numbers.");
}
else
{
long factorial = CalculateFactorial(number);
Console.WriteLine($"The factorial of {number} is: {factorial}");
}
}
static long CalculateFactorial(int num)
{
long result = 1;
for (int i = 1; i <= num; i++)
{
result *= i; // result = result * i
}
return result;
}
}
Output : Enter a number: 5
The factorial of 5 is: 120
19. Write a program to print Fibonacci series upto n terms in c#
using System;
class Program
{
static void Main()
{
Console.Write("Enter the number of terms: ");
int n = Convert.ToInt32(Console.ReadLine());
if (n <= 0)
{
Console.WriteLine("Please enter a positive integer greater than 0.");
}
else
{
Console.WriteLine($"Fibonacci series up to {n} terms:");
int a = 0, b = 1;
if (n == 1)
{
Console.WriteLine(a);
}
else
{
Console.Write(a + " " + b + " ");
for (int i = 3; i <= n; i++)
{
int nextTerm = a + b; // The next term is the sum of the previous two
Console.Write(nextTerm + " ");
a = b;
b = nextTerm;
}
}
Console.WriteLine();
}
}
}
Output : Enter the number of terms: 7
Fibonacci series up to 7 terms:
0112358
20. Write a program to find given number is Armstrong or not in c#
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
if (IsArmstrong(num))
{
Console.WriteLine($"{num} is an Armstrong number.");
}
else
{
Console.WriteLine($"{num} is not an Armstrong number.");
}
}
static bool IsArmstrong(int num)
{
int originalNumber = num;
int sum = 0;
int numDigits = (int)Math.Floor(Math.Log10(num) + 1);
while (num > 0)
{
int digit = num % 10; // Get the last digit
sum += (int)Math.Pow(digit, numDigits); // Add the digit raised to the power
num /= 10; // Remove the last digit
}
return sum == originalNumber;
}
}
Output : Enter a number: 153
153 is an Armstrong number.