0% found this document useful (0 votes)
2 views

C- Practical Programs

The document contains a series of C# programs demonstrating various programming concepts such as calculating the hypotenuse of a triangle, performing arithmetic operations, determining the quadrant of coordinates, and checking for vowels. It also includes examples of inheritance, operator overloading, user input handling, and generating Fibonacci series and number patterns. Each program is followed by sample output to illustrate its functionality.

Uploaded by

onlymusic287
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C- Practical Programs

The document contains a series of C# programs demonstrating various programming concepts such as calculating the hypotenuse of a triangle, performing arithmetic operations, determining the quadrant of coordinates, and checking for vowels. It also includes examples of inheritance, operator overloading, user input handling, and generating Fibonacci series and number patterns. Each program is followed by sample output to illustrate its functionality.

Uploaded by

onlymusic287
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Program 1 : Write a simple c# programs to Calculate Hypotenuse of triangle

using dynamic initialization of variables

using System;

class Program
{
static void Main()
{
Console.WriteLine("Enter the lengths of the two sides of a right triangle:");

Console.Write("Side 1: ");
double side1 = Convert.ToDouble(Console.ReadLine());

Console.Write("Side 2: ");
double side2 = Convert.ToDouble(Console.ReadLine());

double hypotenuse = Math.Sqrt(Math.Pow(side1, 2) + Math.Pow(side2, 2));

Console.WriteLine($"The hypotenuse of the triangle is: {hypotenuse}");


}
}

Output :

Enter the lengths of the two sides of a right triangle:


Side 1: 6
Side 2: 10
The hypotenuse of the triangle is: 11.6619037896906
Program 2 : Write a simple c# programs to get input from the user and
perform calculations

using System;

class Program
{
static void Main()
{
Console.WriteLine("Enter the first number:");
double num1 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter the second number:");


double num2 = Convert.ToDouble(Console.ReadLine());

double sum = num1 + num2;


double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;

Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
Console.WriteLine($"Product: {product}");
Console.WriteLine($"Quotient: {quotient}");
}
}

Output :

Enter the first number:


5
Enter the second number:
6
Sum: 11
Difference: -1
Product: 30
Quotient: 0.833333333333333
Program 3 : Write a simple c# programs to Calculate the quadrant for the
coordinates using if..else...ladder

using System;

class Program
{
static void Main()
{
Console.WriteLine("Enter the x-coordinate:");
double x = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Enter the y-coordinate:");


double y = Convert.ToDouble(Console.ReadLine());

if (x > 0 && y > 0)


{
Console.WriteLine("Quadrant I");
}
else if (x < 0 && y > 0)
{
Console.WriteLine("Quadrant II");
}
else if (x < 0 && y < 0)
{
Console.WriteLine("Quadrant III");
}
else if (x > 0 && y < 0)
{
Console.WriteLine("Quadrant IV");
}
else
{
Console.WriteLine("On the axis or origin");
}
}
}
Output :

Enter the x-coordinate:


6
Enter the y-coordinate:
4
Quadrant I
Program 4 : Write a simple c# programs to Check whether the alphabet is a
vowel or not using switch..case…

using System;

class Program
{
static void Main()
{
Console.WriteLine("Enter a character:");
char ch = Convert.ToChar(Console.ReadLine());

switch (char.ToLower(ch))
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
Console.WriteLine("It's a vowel.");
break;
default:
Console.WriteLine("It's not a vowel.");
break;
}
}
}

Output :

Enter a character:
i
It's a vowel.
Program 5 : Write a simple c# programs to understand about for..each loop
and strings

using System;

class Program
{
static void Main()
{
// Define a string
string sentence = "Hello, world!";

// Using a for..each loop to iterate over each character in the string


Console.WriteLine("Characters in the string:");
foreach (char character in sentence)
{
Console.WriteLine(character);
}
}
}

Output :

Characters in the string:


H
e
l
l
o
,

w
o
r
l
d
!
Program 6 : Write a simple c# programs to print the students list using classes
and objects

using System;
using System.Collections.Generic;

class Student
{
public string Name { get; set; }
public int Age { get; set; }

public Student(string name, int age)


{
Name = name;
Age = age;
}

public void DisplayDetails()


{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}

class Program
{
static void Main()
{
// Creating a list of students
List<Student> students = new List<Student>
{
new Student("Rohan", 20),
new Student("Mohan", 21),
new Student("Soham", 19)
};

// Printing the list of students


Console.WriteLine("List of Students:");
foreach (Student student in students)
{
student.DisplayDetails();
}
}
}

Output :

List of Students:
Name: Rohan, Age: 20
Name: Mohan, Age: 21
Name: Soham, Age: 19
Program 7 : Write a simple c# programs to implement Single Inheritance
concepts

using System;

class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating");
}

public void Sleep()


{
Console.WriteLine("Animal is sleeping");
}
}

class Dog : Animal


{
public void Bark()
{
Console.WriteLine("Dog is barking");
}
}

class Program
{
static void Main(string[] args)
{
Dog myDog = new Dog();

myDog.Eat();
myDog.Sleep();
myDog.Bark();

Console.ReadLine();
}
}
Output :

Animal is eating
Animal is sleeping
Dog is barking
Program 8 : Write a simple c# programs to implement Multilevel Inheritance
concepts

using System;
class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
class Bulldog : Dog
{
public void Guard()
{
Console.WriteLine("Guarding...");
}
}
class Program
{
static void Main(string[] args)
{
Bulldog bulldog = new Bulldog();
bulldog.Eat();
bulldog.Bark();
bulldog.Guard();
Console.ReadKey();
}
}
Output :
Eating...
Barking...
Guarding...
Program 9 : Write a simple c# programs to implement Multiple Inheritance
concepts

using System;

interface ISwimmable
{
void Swim();
}

interface IFlyable
{
void Fly();
}

class Fish : ISwimmable


{
public void Swim()
{
Console.WriteLine("Fish is swimming...");
}
}

class Bird : IFlyable


{
public void Fly()
{
Console.WriteLine("Bird is flying...");
}
}

class Duck : ISwimmable, IFlyable


{
public void Swim()
{
Console.WriteLine("Duck is swimming...");
}

public void Fly()


{
Console.WriteLine("Duck is flying...");
}
}

class Program
{
static void Main(string[] args)
{
Fish fish = new Fish();
Bird bird = new Bird();
Duck duck = new Duck();

fish.Swim();
bird.Fly();
duck.Swim();
duck.Fly();

Console.ReadKey();
}
}

Output :

Fish is swimming...
Bird is flying...
Duck is swimming...
Duck is flying...
Program 10 : Write a simple c# programs to implement Unary operator
overloading concept in C#

using System;

class Number
{
private int value;
public Number(int value)
{
this.value = value;
}

public static Number operator -(Number num)


{
return new Number(-num.value);
}

public static Number operator +(Number num)


{
return new Number(num.value);
}

public void Display()


{
Console.WriteLine("Value: " + value);
}
}

class Program
{
static void Main(string[] args)
{
Number num1 = new Number(10);
Number num2 = -num1;
Number num3 = +num2;

Console.WriteLine("Original value:");
num1.Display();
Console.WriteLine("\nAfter applying unary minus operator:");
num2.Display();

Console.WriteLine("\nAfter applying unary plus operator:");


num3.Display();

Console.ReadKey();
}
}

Output :

Original value:
Value: 10

After applying unary minus operator:


Value: -10

After applying unary plus operator:


Value: -10
Program 11 : Write a simple c# programs to implement Binary operator
overloading concept in C#

using System;

class ComplexNumber
{
private double real;
private double imaginary;

public ComplexNumber(double real, double imaginary)


{
this.real = real;
this.imaginary = imaginary;
}

public static ComplexNumber operator +(ComplexNumber num1, ComplexNumber num2)


{
double realPart = num1.real + num2.real;
double imaginaryPart = num1.imaginary + num2.imaginary;
return new ComplexNumber(realPart, imaginaryPart);
}

public static ComplexNumber operator -(ComplexNumber num1, ComplexNumber num2)


{
double realPart = num1.real - num2.real;
double imaginaryPart = num1.imaginary - num2.imaginary;
return new ComplexNumber(realPart, imaginaryPart);
}

public void Display()


{
Console.WriteLine("Real Part: " + real + ", Imaginary Part: " + imaginary);
}
}

class Program
{
static void Main(string[] args)
{
ComplexNumber num1 = new ComplexNumber(3, 4);
ComplexNumber num2 = new ComplexNumber(2, 5);

ComplexNumber sum = num1 + num2;


ComplexNumber difference = num1 - num2;

Console.WriteLine("Sum:");
sum.Display();

Console.WriteLine("\nDifference:");
difference.Display();

Console.ReadKey();
}
}

Output :

Sum:
Real Part: 5, Imaginary Part: 9

Difference:
Real Part: 1, Imaginary Part: -1
Program 12 : Write a console application that obtains four int values from the
user and displays the product.

using System;

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter four integer values:");

Console.Write("Enter first integer: ");


int num1 = int.Parse(Console.ReadLine());

Console.Write("Enter second integer: ");


int num2 = int.Parse(Console.ReadLine());

Console.Write("Enter third integer: ");


int num3 = int.Parse(Console.ReadLine());

Console.Write("Enter fourth integer: ");


int num4 = int.Parse(Console.ReadLine());

int product = num1 * num2 * num3 * num4;

Console.WriteLine($"The product of {num1}, {num2}, {num3}, and {num4} is:


{product}");

Console.ReadKey();
}
}

Output :
Enter four integer values:
Enter first integer: 4
Enter second integer: 6
Enter third integer: 8
Enter fourth integer: 10
The product of 4, 6, 8, and 10 is: 1920
Program 13 : Write a console application that checks two integers stored in
variables var1 and var2 is greater than 10 or not.

using System;

class Program
{
static void Main(string[] args)
{
int var1 = 15;
int var2 = 7;

if (var1 > 10)


{
Console.WriteLine("var1 is greater than 10");
}
else
{
Console.WriteLine("var1 is not greater than 10");
}

if (var2 > 10)


{
Console.WriteLine("var2 is greater than 10");
}
else
{
Console.WriteLine("var2 is not greater than 10");
}

Console.ReadKey();
}
}

Output :

var1 is greater than 10


var2 is not greater than 10
Program 14 : Write a console application that places double quotation marks
around each word in a string .

using System;

class Program
{
static void Main(string[] args)
{
string inputString = "Hello world! This is a test string.";

string[] words = inputString.Split(' ');

string result = "";

foreach (string word in words)


{
result += "\"" + word + "\" ";
}

Console.WriteLine("Original string: " + inputString);


Console.WriteLine("String with double quotation marks around each word: " +
result.Trim());

Console.ReadKey();
}
}

Output :

Original string: Hello world! This is a test string.


String with double quotation marks around each word: "Hello" "world!" "This" "is" "a"
"test" "string."
Program 15 : Write an application that uses two command-line arguments to
place values into a string and an integer variable, respectively. Then display
these values.

using System;

class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: Program.exe <string_value> <integer_value>");
return;
}

string stringValue = args[0];


int intValue;

if (!int.TryParse(args[1], out intValue))


{
Console.WriteLine("Second argument must be an integer.");
return;
}

Console.WriteLine("String value: " + stringValue);


Console.WriteLine("Integer value: " + intValue);

Console.ReadKey();
}
}

Output :

String value: Hello


Integer value: 42
Program 16 : Write an application that receives the following information
from a set of students:
Student Id:
Student Name:
Course Name:
Date of Birth:
The application should also display the information of all the students once
the data is Entered.
Implement this using an Array of Structures.

using System;

namespace StudentInformationApp
{
class Program
{
struct Student
{
public int Id;
public string Name;
public string Course;
public DateTime DateOfBirth;
}

static void Main(string[] args)


{
const int MaxStudents = 5;

Student[] students = new Student[MaxStudents];

for (int i = 0; i < MaxStudents; i++)


{
Console.WriteLine($"Enter information for student {i + 1}:");
Console.Write("Student Id: ");
students[i].Id = int.Parse(Console.ReadLine());

Console.Write("Student Name: ");


students[i].Name = Console.ReadLine();
Console.Write("Course Name: ");
students[i].Course = Console.ReadLine();

Console.Write("Date of Birth (MM/DD/YYYY): ");


students[i].DateOfBirth = DateTime.Parse(Console.ReadLine());
}

Console.WriteLine("\nStudent Information:");
foreach (var student in students)
{
Console.WriteLine($"ID: {student.Id}, Name: {student.Name}, Course:
{student.Course}, Date of Birth: {student.DateOfBirth.ToShortDateString()}");
}

Console.ReadLine();
}
}
}

Output :

Enter information for student 1:


Student Id: 121
Student Name: Sajid
Course Name: C#
Date of Birth (MM/DD/YYYY): 11/12/2000
Enter information for student 2:
Student Id: 122
Student Name: soham
Course Name: java
Date of Birth (MM/DD/YYYY): 01/02/2002
Program 17 : Write programs using conditional statements and loops:
Generate Fibonacci series.

using System;

namespace FibonacciSeries
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the number of terms in Fibonacci series:");
int n = int.Parse(Console.ReadLine());

Console.WriteLine("\nFibonacci Series:");
GenerateFibonacciSeries(n);
}

static void GenerateFibonacciSeries(int n)


{
int first = 0, second = 1, next;

if (n >= 1)
Console.Write(first + " ");

if (n >= 2)
Console.Write(second + " ");

for (int i = 3; i <= n; i++)


{
next = first + second;
Console.Write(next + " ");
first = second;
second = next;
}
}
}
}
Output :

Enter the number of terms in Fibonacci series:


15

Fibonacci Series:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Program 18 : Write programs using conditional statements and loops:
Generate various patterns (triangles, diamond and other patterns) with
numbers.

using System;

namespace NumberPatterns
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the number of rows for the patterns:");
int rows = int.Parse(Console.ReadLine());

Console.WriteLine("\nRight-Angle Triangle:");
PrintRightAngleTriangle(rows);

Console.WriteLine("\nEquilateral Triangle:");
PrintEquilateralTriangle(rows);

Console.WriteLine("\nDiamond:");
PrintDiamond(rows);

Console.WriteLine("\nStaircase:");
PrintStaircase(rows);
}

static void PrintRightAngleTriangle(int rows)


{
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}
}
static void PrintEquilateralTriangle(int rows)
{
for (int i = 1; i <= rows; i++)
{
for (int j = rows - i; j >= 1; j--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(k + " ");
}
Console.WriteLine();
}
}

static void PrintDiamond(int rows)


{
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= rows - i; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= 2 * i - 1; k++)
{
Console.Write(k + " ");
}
Console.WriteLine();
}

for (int i = rows - 1; i >= 1; i--)


{
for (int j = 1; j <= rows - i; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= 2 * i - 1; k++)
{
Console.Write(k + " ");
}
Console.WriteLine();
}
}

static void PrintStaircase(int rows)


{
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write(j + " ");
}
Console.WriteLine();
}
}
}
}

Output :
Enter the number of rows for the patterns:
5

Right-Angle Triangle:
1
12
123
1234
12345

Equilateral Triangle:
1
12
123
1234
12345
Diamond:
1
123
12345
1234567
123456789
1234567
12345
123
1

Staircase:
1
12
123
1234
12345
Program 19 : Write programs using conditional statements and loops: Test for
prime numbers.

using System;

namespace PrimeNumberTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number to check if it's prime:");
int number = int.Parse(Console.ReadLine());

bool isPrime = IsPrime(number);

if (isPrime)
{
Console.WriteLine($"{number} is a prime number.");
}
else
{
Console.WriteLine($"{number} is not a prime number.");
}
}

static bool IsPrime(int number)


{
if (number <= 1)
{
return false;
}

if (number == 2)
{
return true;
}

if (number % 2 == 0)
{
return false;
}

for (int i = 3; i <= Math.Sqrt(number); i += 2)


{
if (number % i == 0)
{
return false;
}
}

return true;
}
}
}

Output :

Enter a number to check if it's prime:


5
5 is a prime number.
Program 20 : Write a program to declare a class „staff‟ having data members
as name and post.accept this data 5 for 5 staffs and display names of staff who
are HOD.

using System;

namespace StaffManagement
{
class Staff
{
public string Name { get; set; }
public string Post { get; set; }
}

class Program
{
static void Main(string[] args)
{
Staff[] staffs = new Staff[5];

// Accepting data for 5 staff members


for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Enter details for Staff {i + 1}:");
Console.Write("Name: ");
string name = Console.ReadLine();

Console.Write("Post: ");
string post = Console.ReadLine();

staffs[i] = new Staff { Name = name, Post = post };


}

// Displaying names of staff who are HOD


Console.WriteLine("\nNames of HODs:");
foreach (var staff in staffs)
{
if (staff.Post.ToLower() == "hod")
{
Console.WriteLine(staff.Name);
}
}
}
}
}

Output :

Enter details for Staff 1:


Name: Amit
Post: JR Engineer
Enter details for Staff 2:
Name: rohan
Post: JR Engineer
Program 21 : Write a program to declare class „Distance‟ have data members
dist1,dist2 ,dist3. Initialize the two data members using constructor and store
their addition in third data member using function and display addition.

using System;

namespace DistanceProgram
{
class Distance
{
private double dist1;
private double dist2;
private double dist3;

public Distance(double distance1, double distance2)


{
dist1 = distance1;
dist2 = distance2;
}

public void CalculateAddition()


{
dist3 = dist1 + dist2;
}

public void DisplayAddition()


{
Console.WriteLine($"Addition of {dist1} and {dist2} is: {dist3}");
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter distance 1:");
double distance1 = double.Parse(Console.ReadLine());

Console.WriteLine("Enter distance 2:");


double distance2 = double.Parse(Console.ReadLine());
Distance distanceObj = new Distance(distance1, distance2);

distanceObj.CalculateAddition();

distanceObj.DisplayAddition();
}
}
}

Output :

Enter distance 1:
2
Enter distance 2:
4
Addition of 2 and 4 is: 6
Program 22 : Write a program to accept a number from the user and throw
an exception if the number is not an even number.

using System;
namespace ExceptionHandling
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Enter a number:");
int number = int.Parse(Console.ReadLine());

if (number % 2 != 0)
{
throw new Exception("Number must be even.");
}

Console.WriteLine($"You entered an even number: {number}");


}
catch (FormatException)
{
Console.WriteLine("Invalid input. Please enter a valid integer.");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}

Output :
Enter a number:
5
ERROR!
Error: Number must be even.

You might also like