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

C# Practical Ans of Zero Lec

The document contains code examples for creating C# console and ASP.NET applications. It demonstrates how to create programs that perform basic math operations, check for odd/even numbers, find the largest number, and check for leap years. It also shows how to create a registration form, handle exceptions, manage sessions, and create a simple MVC application with a controller and view.

Uploaded by

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

C# Practical Ans of Zero Lec

The document contains code examples for creating C# console and ASP.NET applications. It demonstrates how to create programs that perform basic math operations, check for odd/even numbers, find the largest number, and check for leap years. It also shows how to create a registration form, handle exceptions, manage sessions, and create a simple MVC application with a controller and view.

Uploaded by

badri892002.8055
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Write a program to display the addition, subtraction, multiplication and division of two number using

console application.

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($"Addition: {num1} + {num2} = {sum}");

Console.WriteLine($"Subtraction: {num1} - {num2} = {difference}");

Console.WriteLine($"Multiplication: {num1} * {num2} = {product}");

Console.WriteLine($"Division: {num1} / {num2} = {quotient}");

Console.ReadLine(); // Wait for user to press Enter before closing

Write a Program to check whether entered number is odd or even

using System;

class Program{

static void Main(){

Console.WriteLine("Enter a number:");

int number = Convert.ToInt32(Console.ReadLine());

if (number % 2 == 0){

Console.WriteLine($"{number} is an even number.");

else{

Console.WriteLine($"{number} is an odd number.");

Console.ReadLine(); // Wait for user to press Enter before closing

Write a C# Program to Find the Largest Number using Conditional Operator.

using System;

class Program
{

static void Main()

Console.WriteLine("Enter three numbers:");

int num1 = Convert.ToInt32(Console.ReadLine());

int num2 = Convert.ToInt32(Console.ReadLine());

int num3 = Convert.ToInt32(Console.ReadLine());

int largest = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);

Console.WriteLine($"The largest number among {num1}, {num2}, and {num3} is: {largest}");

Console.ReadLine(); // Wait for user to press Enter before closing

Write a C# program to check leap year using conditional Operator.

using System;

class Program

static void Main()

Console.WriteLine("Enter a year:");

int year = Convert.ToInt32(Console.ReadLine());

bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

string result = isLeapYear ? "Leap year" : "Not a leap year";

Console.WriteLine($"{year} is {result}");

Console.ReadLine(); // Wait for user to press Enter before closing

Create a registration form using different server controls.

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RegistrationForm.aspx.cs"


Inherits="YourNamespace.RegistrationForm" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
<title>Registration Form</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h1>Registration Form</h1>

<div>

<label for="txtFirstName">First Name:</label>

<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>

</div>

<div>

<label for="txtLastName">Last Name:</label>

<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>

</div>

<div>

<label for="txtEmail">Email:</label>

<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

</div>

<div>

<label for="txtPassword">Password:</label>

<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>

</div>

<div>

<label for="ddlCountry">Country:</label>

<asp:DropDownList ID="ddlCountry" runat="server">

<asp:ListItem Text="Select" Value=""></asp:ListItem>

<asp:ListItem Text="USA" Value="USA"></asp:ListItem>

<asp:ListItem Text="Canada" Value="Canada"></asp:ListItem>

<asp:ListItem Text="UK" Value="UK"></asp:ListItem>

</asp:DropDownList>

</div>

<div>

<asp:Button ID="btnRegister" runat="server" Text="Register" OnClick="btnRegister_Click" />

</div>

</div>

</form>

</body>
</html>

CSHARP:

using System;

using System.Web.UI;

namespace YourNamespace

public partial class RegistrationForm : Page

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

// Initialize the form or load data if needed

protected void btnRegister_Click(object sender, EventArgs e)

string firstName = txtFirstName.Text;

string lastName = txtLastName.Text;

string email = txtEmail.Text;

string password = txtPassword.Text;

string country = ddlCountry.SelectedValue;

// Validate and process the registration data (e.g., save to database, send confirmation email, etc.)

// For demonstration purposes, let's just display the registration details

string message = $"Registration Successful!\nFirst Name: {firstName}\nLast Name:


{lastName}\nEmail: {email}\nCountry: {country}";

ClientScript.RegisterStartupScript(this.GetType(), "alert", $"alert('{message}');", true);

Write a program to implement exception handling in C#.

using System;

class Program

static void Main()

try

{
Console.WriteLine("Enter a number:");

int num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter another number:");

int num2 = Convert.ToInt32(Console.ReadLine());

int result = num1 / num2;

Console.WriteLine($"Result of division: {num1} / {num2} = {result}");

catch (FormatException)

Console.WriteLine("Invalid input format. Please enter a valid number.");

catch (DivideByZeroException)

Console.WriteLine("Error: Division by zero is not allowed.");

catch (Exception ex)

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

finally

Console.WriteLine("End of program.");

Console.ReadLine(); // Wait for user to press Enter before closing

Write a program to manage sessions in ASP.NET.

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SessionExample.aspx.cs"


Inherits="YourNamespace.SessionExample" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Session Example</title>

</head>

<body>

<form id="form1" runat="server">


<div>

<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

<br />

<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>

<asp:Button ID="btnSetSession" runat="server" Text="Set Session" OnClick="btnSetSession_Click"


/>

<asp:Button ID="btnClearSession" runat="server" Text="Clear Session"


OnClick="btnClearSession_Click" />

</div>

</form>

</body>

</html>

CSHARP:

using System;

using System.Web.UI;

namespace YourNamespace

public partial class SessionExample : Page

protected void btnSetSession_Click(object sender, EventArgs e)

string username = txtUsername.Text;

Session["Username"] = username;

lblMessage.Text = $"Session variable 'Username' set to: {username}";

protected void btnClearSession_Click(object sender, EventArgs e)

Session.Remove("Username"); // Clear the 'Username' session variable

lblMessage.Text = "Session variable 'Username' cleared.";

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)

if (Session["Username"] != null)
{

string username = Session["Username"].ToString();

lblMessage.Text = $"Welcome back, {username}!";

else

lblMessage.Text = "Session variable 'Username' not set.";

Create a C# console application that prints "Hello, To The Coding World" to the console.

using System;

class Program

static void Main()

Console.WriteLine("Hello, To The Coding World");

Console.ReadLine(); // Wait for user to press Enter before closing

Create an ASP.NET Core MVC project with a controller and a view that displays a simple message.

To create an ASP.NET Core MVC project with a controller and a view that displays a simple message,
follow these steps:

1. **Create a New ASP.NET Core MVC Project**:

Open Visual Studio and create a new project.

- Select "ASP.NET Core Web Application" as the project template.

- Choose a project name and location.

- Select "ASP.NET Core 5.0" as the target framework.

- Choose the "Web Application (Model-View-Controller)" template.

- Click "Create" to create the project.

2. **Add a Controller**:

In the Solution Explorer, right-click on the "Controllers" folder within your project and select "Add" ->
"Controller".

- Choose "MVC Controller - Empty" and click "Add".

- Name the controller (e.g., `HomeController`) and click "Add".


3. **Add an Action Method to the Controller**:

Open the `HomeController.cs` file in the Controllers folder.

- Add an action method that returns a view. For example:

```csharp

using Microsoft.AspNetCore.Mvc;

namespace YourNamespace.Controllers

public class HomeController : Controller

public IActionResult Index()

ViewBag.Message = "Hello, To The Coding World";

return View();

```

4. **Add a View**:

In the Solution Explorer, right-click on the "Views" folder within your project and select "Add" -> "View".

- Choose the "Empty" template and click "Add".

- Name the view (e.g., `Index.cshtml`) and click "Add".

5. **Edit the View to Display the Message**:

Open the `Index.cshtml` file in the Views/Home folder.

- Add the following code to display the message:

```html

@{

ViewData["Title"] = "Home";

<h1>Welcome to My ASP.NET Core MVC Application</h1>

<p>@ViewBag.Message</p>

```
6. **Run the Application**:

Press F5 or click the "Run" button in Visual Studio to build and run your ASP.NET Core MVC application.

- The application will start, and you should see the message "Hello, To The Coding World" displayed on
the homepage.

Implement a sorting algorithm (e.g., Bubble Sort, Quick Sort) in C# for an integer array.

using System;

class Program

static void Main()

int[] numbers = { 5, 2, 9, 1, 5, 6 };

Console.WriteLine("Original Array:");

PrintArray(numbers);

BubbleSort(numbers);

Console.WriteLine("\nSorted Array:");

PrintArray(numbers);

Console.ReadLine(); // Wait for user to press Enter before closing

static void BubbleSort(int[] arr)

int n = arr.Length;

for (int i = 0; i < n - 1; i++)

for (int j = 0; j < n - i - 1; j++)

if (arr[j] > arr[j + 1])

// Swap arr[j] and arr[j + 1]

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

static void PrintArray(int[] arr)

{
foreach (int num in arr)

Console.Write(num + " ");

Console.WriteLine();

Write code that intentionally generates an exception and also solve the exception using try and catch.

using System;

class Program

static void Main()

try

// Intentionally divide by zero to generate an exception

int num1 = 10;

int num2 = 0;

int result = num1 / num2; // This line will throw a DivideByZeroException

Console.WriteLine($"Result: {result}"); // This line won't be executed

catch (DivideByZeroException ex)

Console.WriteLine($"Error: {ex.Message}");

catch (Exception ex)

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

finally

Console.WriteLine("End of program.");

Console.ReadLine(); // Wait for user to press Enter before closing

}
Create a simple class with attributes and methods(Class name should be your favorite subject)

using System;

class ComputerScience

// Attributes

public string SubjectName { get; set; }

public int Year { get; set; }

// Constructor

public ComputerScience(string subjectName, int year)

SubjectName = subjectName;

Year = year;

// Method to display information about the subject

public void DisplaySubjectInfo()

Console.WriteLine($"Subject: {SubjectName}");

Console.WriteLine($"Year: {Year}");

// Method to check if the subject is interesting

public void IsInteresting()

if (Year >= 3)

Console.WriteLine("This subject is quite interesting!");

else

Console.WriteLine("This subject needs more exploration to find its interesting aspects.");

Write a C# program to calculate the total marks, percentage and division of two students.

using System;

class Program

static void Main()


{

// Student 1 data

int student1MathsMarks = 85;

int student1ScienceMarks = 90;

// Student 2 data

int student2MathsMarks = 78;

int student2ScienceMarks = 88;

// Calculate total marks, percentage, and division for Student 1

int student1TotalMarks = student1MathsMarks + student1ScienceMarks;

double student1Percentage = (double)student1TotalMarks / 200 * 100;

string student1Division = GetDivision(student1Percentage);

// Calculate total marks, percentage, and division for Student 2

int student2TotalMarks = student2MathsMarks + student2ScienceMarks;

double student2Percentage = (double)student2TotalMarks / 200 * 100;

string student2Division = GetDivision(student2Percentage);

// Display results for Student 1

Console.WriteLine("Student 1 Results:");

Console.WriteLine($"Total Marks: {student1TotalMarks}");

Console.WriteLine($"Percentage: {student1Percentage}%");

Console.WriteLine($"Division: {student1Division}");

// Display results for Student 2

Console.WriteLine("\nStudent 2 Results:");

Console.WriteLine($"Total Marks: {student2TotalMarks}");

Console.WriteLine($"Percentage: {student2Percentage}%");

Console.WriteLine($"Division: {student2Division}");

Console.ReadLine(); // Wait for user to press Enter before closing

// Method to determine the division based on percentage

static string GetDivision(double percentage)

if (percentage >= 60)

return "First Division";

else if (percentage >= 45)

return "Second Division";


}

else if (percentage >= 33)

return "Third Division";

else

return "Fail";

Implement a simple service and use dependency injection to inject it into a controller in an ASP.NET Core
application.

1. **Create a Service Interface**:

First, create an interface for your service. This interface will define the methods that your service will
implement.

```csharp

public interface IMyService

string GetMessage();

```

2. **Implement the Service**:

Next, create a class that implements the service interface. This class will contain the implementation of
the service methods.

```csharp

public class MyService : IMyService

public string GetMessage()

return "Hello from MyService!";

```
3. **Register the Service with Dependency Injection**:

In the `Startup.cs` file of your ASP.NET Core application, register the service with dependency injection
in the `ConfigureServices` method.

```csharp

public void ConfigureServices(IServiceCollection services)

services.AddSingleton<IMyService, MyService>();

services.AddControllersWithViews();

```

4. **Inject the Service into a Controller**:

Now, you can inject the service into a controller using constructor injection. Create a controller and
include a constructor that accepts the service interface as a parameter.

```csharp

public class HomeController : Controller

private readonly IMyService _myService;

public HomeController(IMyService myService)

_myService = myService;

public IActionResult Index()

string message = _myService.GetMessage();

return View(model: message);

```

5. **Use the Service in a View**:

Create a view file (`Index.cshtml`) for the controller action. In the view, you can display the message
obtained from the service.

```html

@model string
<h1>@Model</h1>

```

6. **Run the Application**:

Start your ASP.NET Core application, and navigate to the controller action (e.g.,
`https://localhost:5001/Home/Index`). The view should display the message obtained from the service.

Implement a simple service and use dependency injection to inject it into a controller in an ASP.NET Core
application.

Sure, let's create a simple service and inject it into a controller using dependency injection in an ASP.NET
Core application.

1. **Create a Service Interface**:

First, create an interface for your service. This interface will define the methods that your service will
implement.

```csharp

public interface IMyService

string GetMessage();

```

2. **Implement the Service**:

Next, create a class that implements the service interface. This class will contain the implementation of
the service methods.

```csharp

public class MyService : IMyService

public string GetMessage()

return "Hello from MyService!";

```

3. **Register the Service with Dependency Injection**:

In the `Startup.cs` file of your ASP.NET Core application, register the service with dependency injection
in the `ConfigureServices` method.

```csharp

public void ConfigureServices(IServiceCollection services)

{
services.AddSingleton<IMyService, MyService>();

services.AddControllersWithViews();

```

4. **Inject the Service into a Controller**:

Now, you can inject the service into a controller using constructor injection. Create a controller and
include a constructor that accepts the service interface as a parameter.

```csharp

public class HomeController : Controller

private readonly IMyService _myService;

public HomeController(IMyService myService)

_myService = myService;

public IActionResult Index()

string message = _myService.GetMessage();

return View(model: message);

```

5. **Use the Service in a View**:

Create a view file (`Index.cshtml`) for the controller action. In the view, you can display the message
obtained from the service.

```html

@model string

<h1>@Model</h1>

```

6. **Run the Application**:

Start your ASP.NET Core application, and navigate to the controller action (e.g.,
`https://localhost:5001/Home/Index`). The view should display the message obtained from the service.

You might also like