Assgnment21 466

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

DATA TYPES:

1. Printing the square

using System;

class Program
{
static void Main()
{
Console.WriteLine("Enter the size of the square:");
int size = int.Parse(Console.ReadLine());
int area = size * size;
Console.WriteLine("The area of the square is: " + area);
}
}
=========================================================================
================
2.Create a console application that finds number of digits and alphabets
in a given string

using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a string:");
string input = Console.ReadLine();
int digitCount = 0;
int alphabetCount = 0;

for (int i = 0; i < input.Length; i++)


{
char ch = input[i];
if (ch >= '0' && ch <= '9')
{
digitCount++;
}
else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <=
'Z'))
{
alphabetCount++;
}
}
Console.WriteLine("Number of digits: " + digitCount);
Console.WriteLine("Number of alphabets: " + alphabetCount);
}
}
=========================================================================
=============
3:Create a console application that accepts a string and increments each
character in the string by 1 and toggle all characters in the new string
to UPPER CASE or LOWER CASE

using System;

class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter the input string");
string inputString =Console.ReadLine();
string increasedString = IncreaseCharacters(inputString);
string toggledString = ToggleCase(increasedString);
Console.WriteLine("After toggling case: " + toggledString);
}
static string IncreaseCharacters(string str)
{
char[] chars = str.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
chars[i]++;
}
return new string(chars);
}
static string ToggleCase(string str)
{
char[] chars = str.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (chars[i] >= 65 && chars[i] <= 90)
{
chars[i] = (char)(chars[i] + 32);

}
else
{
chars[i] = (char)(chars[i] - 32);
}
}
return new string(chars);
}
}
=========================================================================
==============
4. Various string operations

using System;

class Program
{
static void Main()
{
Console.WriteLine("Enter a string:");
string input = Console.ReadLine();

// Printing the string in reverse order


char[] charArray = input.ToCharArray();
Array.Reverse(charArray);
string reversedString = new string(charArray);
Console.WriteLine("Reversed string: " + reversedString);

// substring from pos 2 to the end


string substring = input.Substring(1);
Console.WriteLine("Substring from 2nd position: " + substring);
// replacing given char with $
Console.WriteLine("Enter a character to replace:");
char charToReplace = Console.ReadLine()[0];
string replacedString = input.Replace(charToReplace, '$');
Console.WriteLine("String after replacement: " + replacedString);

// copying and modifying


string copiedString = input;
string modifiedString = copiedString + " - Modified";
Console.WriteLine("Original string: " + copiedString);
Console.WriteLine("Modified string: " + modifiedString);
}
}
=========================================================================
=================
OPERATORS

1. Post and pre increment

using System;

class Program
{
static void Main()
{

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


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

//1 assigning to num2 by pre-incrementing num1


num2 = ++num1;
Console.WriteLine("After pre-incrementing num1 and assigning to
num2:");
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);

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

//2 post-incrementing num1


num2 = num1++;
Console.WriteLine("After post-incrementing num1 and assigning to
num2:");
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);

//3 Swapping
int temp = num1;
num1 = num2;
num2 = temp;
Console.WriteLine("After swapping ");
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);
}
}
=========================================================================
============================
CONTROL STATEMENTS:

1.Write a program which asks the user for his login and password. Both
must be strings. After 3 wrong attempts, the user will be rejected.

using System;
public class HelloWorld
{
public static void Main(string[] args)
{
string correctLogin = "user";
string correctPassword = "password";
int attempts = 0;
Console.WriteLine("Welcome to the login system!");
while (attempts < 3)
{
Console.Write("Enter your login: ");
string login = Console.ReadLine();
Console.Write("Enter your password: ");
string password = Console.ReadLine();
if (login == correctLogin && password == correctPassword)
{
Console.WriteLine("Login successful!");
break; // Exit the loop if login is successful
}
else
{
attempts++;
Console.WriteLine($"Invalid login or password. Attempts
left: {3 - attempts}");
}
}
if (attempts >= 3)
{
Console.WriteLine("Login attempts exceeded. Access denied.");
}
}
}
=========================================================================
=============================================

2. 2nd numbers position in 1st number

using System;

class Program
{
static void Main()
{
string num1Str = Console.ReadLine();
string num2Str = Console.ReadLine();

int position = -1;

for (int i = 0; i < num1Str.Length; i++)


{
if (num1Str[i].ToString() == num2Str)
{
position = num1Str.Length - i;
break;
}
}

if (position == -1)
{
Console.WriteLine("2nd number is not found ");
}
else
{
switch (position)
{
case 1:
Console.WriteLine("unit's place.");
break;
case 2:
Console.WriteLine("ten's place");
break;
case 3:
Console.WriteLine(" hundred's place ");
break;
case 4:
Console.WriteLine("thousand's place");
break;
default:
Console.WriteLine("beyond thousand's place");
break;
}
}
}
}
=========================================================================
=======================================================
ARRAYS:

1 NO OF ELEMETNS
using System;

class Program
{
static void Main()
{
int[] array = { 1, 2, 3, 4, 5, 6, 7 };

int count = 0;
try
{
while (true)
{
int element = array[count];
count++;
}
}
catch (IndexOutOfRangeException)
{

}
Console.WriteLine($"Number of elements in the array: {count}");
}
}
=========================================================================
==========================================================
2. Operations on arrays:

using System;

class Program
{
static void Main()
{
const int size = 10;
int[] array = new int[size];

Console.WriteLine("Enter 10 integers:");

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


{
array[i] = int.Parse(Console.ReadLine());
}

PrintDescending(array);
FindMinMax(array);
CalculateSum(array);
}

static void PrintDescending(int[] array)


{
int[] sortedArray = new int[array.Length];
Array.Copy(array, sortedArray, array.Length);

Array.Sort(sortedArray);
Array.Reverse(sortedArray);

Console.WriteLine("Elements in descending order:");


foreach (int num in sortedArray)
{
Console.Write(num + " ");
}
Console.WriteLine();
}

static void FindMinMax(int[] array)


{
int min = array[0];
int max = array[0];

foreach (int num in array)


{
if (num < min)
{
min = num;
}
if (num > max)
{
max = num;
}
}

Console.WriteLine("Min value: " + min);


Console.WriteLine("Max value: " + max);
}

static void CalculateSum(int[] array)


{
int sum = 0;

foreach (int num in array)


{
sum += num;
}

Console.WriteLine("Sum of all numbers: " + sum);


}
}
=========================================================================
==================
METHODS AND PROPERTIES

1. Employee info

using System;

public class Employee


{

public string EmployeeName { get; set; }


public decimal BasicSalary { get; set; }
public decimal HRA { get; private set; }
public decimal DA { get; private set; }
public decimal TAX { get; private set; }
public decimal GrossPay { get; private set; }
public decimal NetSalary { get; private set; }

public Employee(string employeeName, decimal basicSalary)


{
EmployeeName = employeeName;
BasicSalary = basicSalary;
}

public void CalculateNetPay()


{
HRA = BasicSalary * 0.15M;
DA = BasicSalary * 0.10M;
GrossPay = BasicSalary + HRA + DA;
TAX = GrossPay * 0.08M;
NetSalary = GrossPay - TAX;
}
public void Display()
{
Console.WriteLine($"Employee Name: {EmployeeName}");
Console.WriteLine($"Basic Salary: {BasicSalary:C}");
Console.WriteLine($"HRA: {HRA:C}");
Console.WriteLine($"DA: {DA:C}");
Console.WriteLine($"Gross Pay: {GrossPay:C}");
Console.WriteLine($"TAX: {TAX:C}");
Console.WriteLine($"Net Salary: {NetSalary:C}");
}
}

class Program
{
static void Main()
{
Employee employee = new Employee("CVR Employee", 96996M);
employee.CalculateNetPay();
employee.Display();
}
}

=========================================================================
=============================

2. Stock class

using System;

public class Stock


{
public string StockName { get; set; }
public string StockSymbol { get; set; }
public double PreviousClosingPrice { get; set; }
public double CurrentClosingPrice { get; set; }

public Stock(string stockName, string stockSymbol, double


previousClosingPrice, double currentClosingPrice)
{
StockName = stockName;
StockSymbol = stockSymbol;
PreviousClosingPrice = previousClosingPrice;
CurrentClosingPrice = currentClosingPrice;
}

public double GetChangePercentage()


{
return ((CurrentClosingPrice - PreviousClosingPrice) /
PreviousClosingPrice) * 100;
}

public void Display()


{
Console.WriteLine($"Stock Name: {StockName}");
Console.WriteLine($"Stock Symbol: {StockSymbol}");
Console.WriteLine($"Previous Closing Price:
{PreviousClosingPrice:C}");
Console.WriteLine($"Current Closing Price:
{CurrentClosingPrice:C}");
Console.WriteLine($"Change Percentage:
{GetChangePercentage():F2}%");
}
}

class Program
{
static void Main()
{
try
{
Stock stock = new Stock("CVR Stockk", "AAPL", 150.00,
155.00);
stock.Display();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}

=========================================================================
=======================

3. Random Helper

using System;

public static class RandomHelper


{
private static readonly Random random = new Random();

public static int RandInt(int min, int max)


{
return random.Next(min, max + 1);
}

public static double RandDouble(int min, int max)


{
return min + (random.NextDouble() * (max - min));
}
}

class Program
{
static void Main()
{

int randomInt = RandomHelper.RandInt(1, 10);


double randomDouble = RandomHelper.RandDouble(1, 10);

Console.WriteLine($"Random Integer between 1 and 10 (inclusive):


{randomInt}");
Console.WriteLine($"Random Double between 1 and 10 (1 <= x < 10):
{randomDouble:F2}");
}
}
=========================================================================
=========================
1. Inheritances, covering all the asked implementations.

using System;

public interface IPayable


{
void CalculatePay();
}

class Person
{
private string FirstName;
private string LastName;
private string EmailAddress;
private DateTime DateOfBirth;

public Person(string firstName, string lastName, string email,


DateTime dateOfBirth)
{
FirstName = firstName;
LastName = lastName;
EmailAddress = email;
DateOfBirth = dateOfBirth;
}

public bool IsAdult => (DateTime.Today.Year - DateOfBirth.Year) >=


18;

public string SunSign


{
get
{
DateTime birthdayThisYear = new DateTime(DateTime.Today.Year,
DateOfBirth.Month, DateOfBirth.Day);
DateTime nextBirthday = birthdayThisYear > DateTime.Today ?
birthdayThisYear : birthdayThisYear.AddYears(1);
switch (DateOfBirth.Month)
{
case 1:
return DateOfBirth.Day <= 19 ? "Capricorn" :
"Aquarius";
// other cases with the western horoscopic signs.
default:
return "";
}
}
}

public bool IsBirthDay => DateOfBirth.Month == DateTime.Today.Month


&& DateOfBirth.Day == DateTime.Today.Day;

public string ScreenName


{
get
{
string month = DateOfBirth.Month.ToString().PadLeft(2, '0');
string day = DateOfBirth.Day.ToString().PadLeft(2, '0');
string year = DateOfBirth.Year.ToString().Substring(2, 2);
string initials = (FirstName.Substring(0, 1) +
LastName.Substring(0, 1)).ToLower();
return initials + month + day + year;
}
}
}

class Employee : Person


{
public Employee(string firstName, string lastName, string email,
DateTime dateOfBirth)
: base(firstName, lastName, email, dateOfBirth)
{
}
}

class HourlyEmployee : Employee, IPayable


{
public double HoursWorked { get; set; }
public double PayPerHour { get; set; }
public double TotalPay { get; set; }

public HourlyEmployee(string firstName, string lastName, string


email, DateTime dateOfBirth, double hoursWorked, double payPerHour)
: base(firstName, lastName, email, dateOfBirth)
{
HoursWorked = hoursWorked;
PayPerHour = payPerHour;
}

public void CalculatePay()


{
TotalPay = HoursWorked * PayPerHour;
}
}

class PermanentEmployee : Employee, IPayable


{
public double HRA { get; set; }
public double DA { get; set; }
public double Tax { get; set; }
public double NetPay { get; set; }
public double TotalPay { get; set; }
public PermanentEmployee(string firstName, string lastName, string
email, DateTime dateOfBirth, double hra, double da, double tax)
: base(firstName, lastName, email, dateOfBirth)
{
HRA = hra;
DA = da;
Tax = tax;
}

public void CalculatePay()


{
TotalPay = HRA + DA - Tax;
NetPay = TotalPay - Tax; // Assuming tax deduction from total pay
}
}

class Program
{
static void Main()
{

HourlyEmployee hourlyEmp = new HourlyEmployee("CVR", "Ok",


"WiproCvr@cvr.com", new DateTime(1990, 5, 15), 40, 25);
hourlyEmp.CalculatePay();
Console.WriteLine($"Hourly Employee Total Pay:
{hourlyEmp.TotalPay}");

PermanentEmployee permEmp = new PermanentEmployee("CVR22222",


"Ok2", "WiproCvr@cvr.com", new DateTime(1985, 8, 10), 2000, 1500, 500);
permEmp.CalculatePay();
Console.WriteLine($"Permanent Employee Total Pay:
{permEmp.TotalPay}");
Console.WriteLine($"Permanent Employee Net Pay:
{permEmp.NetPay}");
}
}
=========================================================================
==========================================================
POLYMORPHISM:

1. Function overloading to calc. area:

using System;

class Shape
{

public double Area(double radius)


{
return Math.PI * radius * radius;
}

public double Area(double base, double height)


{
return 0.5 * base * height;
}
public double Area(double length, double width)
{
return length * width;
}
}

class Program
{
static void Main()
{
Shape shape = new Shape();

double circleArea = shape.Area(5);


Console.WriteLine($"Area of Circle: {circleArea}");

double triangleArea = shape.Area(4, 6);


Console.WriteLine($"Area of Triangle: {triangleArea}");

double rectangleArea = shape.Area(7, 3);


Console.WriteLine($"Area of Rectangle: {rectangleArea}");
}
}
=========================================================================
==============================================
FILE HANDLING:

1 using System;
using System.IO;

class Program
{
static void Main()
{
try
{

string filePath = "testfile.txt";

Console.WriteLine("Enter content:");
string content = Console.ReadLine();

using (StreamWriter writer = new StreamWriter(filePath))


{
writer.WriteLine(content);
}

Console.WriteLine("file created");

Console.WriteLine("Press any key to exit");


Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
=========================================================================
=================================================

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy