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

C# Language Fundamentals Hands-On-Lab-Guide - (Questions and Answers)

This document contains 15 questions and solutions related to C# programming language fundamentals. The questions cover topics like string manipulation, arrays, dates, file handling and more. Complete solutions are provided for each question in C# code.

Uploaded by

nani031nani
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)
20 views

C# Language Fundamentals Hands-On-Lab-Guide - (Questions and Answers)

This document contains 15 questions and solutions related to C# programming language fundamentals. The questions cover topics like string manipulation, arrays, dates, file handling and more. Complete solutions are provided for each question in C# code.

Uploaded by

nani031nani
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
You are on page 1/ 15

C# Language Fundamentals Hands-On-Lab-Guide- (Questions and Answers)

Note: Objective of this exercise is come out with a different solution based on the answer for each
question.

1. Write a C# program to accept a string from the user


and interchange the last character with first character
like below
Example : If the user inputs “HelloWorld” it should
display “delloWorlh”

Solution:

using System;
using System.Collections.Generic;

public class Exe1 {


static void Main(string[] args)
{
Console.WriteLine(first_last("w3resource"));
Console.WriteLine(first_last("Python"));
Console.WriteLine(first_last("x"));
}
public static string first_last(string ustr)
{
return ustr.Length > 1
? ustr.Substring(ustr.Length - 1) +
ustr.Substring(1, ustr.Length - 2) + ustr.Substring(0, 1) : ustr;
}
}

Note : Base on the above solution pls find an alternate solution


Hint: maybe you can use foreach loop or forloop.

1. Write a C# program to accept two integer values and


return true if one is negative and one is positive.
using System;
using System.Collections.Generic;

public class Ex1 {


static void Main(string[] args)
{
Console.WriteLine("\nInput first integer:");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Input second integer:");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Check if one is negative and one is positive:");
Console.WriteLine((x < 0 && y > 0) || (x > 0 && y < 0));
}
}

1. Write a program to accept a string and display the longest word in the given
string.
For Example: It is a new generation of world
Now display longest word which is generation

using System;
public class Ex4
{
public static void Main()
{
string line = " It is a new generation of world ”;
string[] words = line.Split();
string word = "";
int ctr = 0;
foreach (String s in words)
{
if (s.Length > ctr)
{
word = s;
ctr = s.Length;
}
}

Console.WriteLine(word);

}
}

1. Write a C# program to find the size of a specified file


in bytes.

using System;
using System.Collections.Generic;
using System.IO;

public class Exe2 {


public static void Main() {
FileInfo f = new FileInfo(@"C:\NewFolder\abc.txt");
Console.WriteLine("\nSize of a file:
"+f.Length.ToString());
}
}
1. Write a C# program to multiply corresponding
elements of two arrays of integers.
Example : [1,3,-5,4]
[1,4,-5,-2]
Output is : 1,12,25,8

using System;
using System.Collections.Generic;

public class Exe3 {


public static void Main() {
int[] first_array = {1, 3, -5, 4};
int[] second_array = {1, 4, -5, -2};

Console.WriteLine("\nArray1: [{0}]", string.Join(", ",


first_array));
Console.WriteLine("Array2: [{0}]", string.Join(", ",
second_array));

Console.WriteLine("\nMultiply corresponding elements of two


arrays: ");

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


{

Console.Write(first_array[i] * second_array[i]+" ");


}
Console.WriteLine("\n");
}
}

6.) Write a C# program to check to accept a string NewWorld


Of Computers and check if World appears in the given string
and remove world and display rest of the given string.

Solution : Note: Code is given as clue for the answer try modifying
the code to get the desired output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Ex7 {


static void Main(string[] args)
{
string str= "NewWorld Of Computers”;
Console.WriteLine((str.Substring(1, 2).Equals("World") ?
str.Remove(1, 2) : str));
}
}
7.) Write a C# program to check if the first element and the
last element are equal of an array of integers and the length is
1 or more.
For Example : [1,2,3,4,5,6,5,4,3,3,4,5,1]
Display True if the first element and last element in the given
array are same.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Ex8


{
public static void Main()
{
int[] nums = {1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 8, 8,
1};
Console.WriteLine((nums.Length >= 1) &&
(nums[0].Equals(nums[nums.Length - 1])));
}
}

8.) Write a C# program to get the larger value between first


and last element of an array.

For Example : [1,2,4,5,7,8]


Largest value between 1st and last element including 1st and
last element need be checked and display the largest.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Ex9


{
public static void Main()
{
int[] nums = {1, 2, 5, 7, 8};
Console.WriteLine("\nArray1: [{0}]", string.Join(", ", nums));
var h_val = nums[0];
for (var i = 0; i < nums.Length; i++)
{
if (nums[i] > nums[0])
h_val = nums[i];
}
Console.WriteLine("\nHighest value between first and last values of
the said array: {0}", h_val);

}
}

9.) Write a C# program to create an new array, containing the


middle elements of three arrays (each length 3) of integers.
For Example :[1,2,3]
[5,6,7]
[9,8,3]
Output : [2,6,8]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Ex10


{
public static void Main()
{
int[] array1 = {1, 2, 5};
Console.WriteLine("\nArray1: [{0}]", string.Join(", ", array1));
int[] array2 = {0, 3, 8};
Console.WriteLine("\nArray2: [{0}]", string.Join(", ", array2));
int[] array3 = {-1, 0, 2};
Console.WriteLine("\nArray3: [{0}]", string.Join(", ", array3));
int[] new_array = { array1[1], array2[1], array3[1] };
Console.WriteLine("\nNew array: [{0}]", string.Join(", ", new_array));

}
}

10.) Write a C# Sharp program to get the day of the week for a
specified date.
using System;

public class Ex10


{
public static void Main()
{
// Assume the current system is en-US.
DateTime dt = new DateTime(2016, 7, 11);
Console.WriteLine("The day of the week for {0:d} is {1}.", dt, dt.DayOfWeek);
}
}
11.) Write a C# Sharp program to calculate what day of the
week is 40 days from this moment.
using System;
public class Ex11
{
public static void Main()
{

System.DateTime today = System.DateTime.Now;


System.Console.WriteLine("Today = "+System.DateTime.Now);
System.TimeSpan duration = new System.TimeSpan(40, 0, 0, 0);
System.DateTime answer = today.Add(duration);
System.Console.WriteLine("{0:dddd}", answer);
}
}

12. ) Write a C# Sharp program to display the date of past and


future fifteen years of a specified date.

using System;
public class Example15
{
public static void Main()
{
DateTime baseDate = new DateTime(2016, 2, 29);
Console.WriteLine(" Base Date: {0:d}\n", baseDate);

// Show dates of previous fifteen years.


for (int ctr = -1; ctr >= -15; ctr--)
Console.WriteLine("{0,2} year(s) ago: {1:d}",
Math.Abs(ctr), baseDate.AddYears(ctr));
Console.WriteLine();

// Show dates of next fifteen years.


for (int ctr = 1; ctr <= 15; ctr++)
Console.WriteLine("{0,2} year(s) from now: {1:d}",
ctr, baseDate.AddYears(ctr));
}
}

13.) Write a C# Sharp program that compares two dates.


using System;

public class Ex12


{
public static void Main()
{
DateTime date1 = new DateTime(2016, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2016, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;

if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";
0
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);
}
}

14.) Write a C# Sharp program to display the string


representation of a date using the long date format.

using System;
public class Ex13
{
public static void Main()
{
DateTime august14 = new DateTime(2009, 8, 14, 5, 23, 15);

// Get the long date formats using the current culture.


string [] longaugust14Formats =
august14.GetDateTimeFormats('D');

// Display all long date formats.


foreach (string format in longaugust14Formats) {
Console.WriteLine(format);
}
}
}

15.) Write a C# Sharp program to display the string


representations of a date using the short date format
using System;
public class Ex14
{
public static void Main(String[] argv){
DateTime may12 = new DateTime(2016, 5, 12, 5, 23, 15, 16);

IFormatProvider culture =
new System.Globalization.CultureInfo("ja-JP", true);
// Get the short date formats using the "ja-JP" culture.
string [] frenchmay12Formats =
may12.GetDateTimeFormats(culture);

// Display may12 in various formats using "ja-JP" culture.


foreach (string format in frenchmay12Formats) {
Console.WriteLine(format);
}
}
}
16.) Write a C# Sharp program to get the difference between
two dates in days
using System;
class Ex15
{
public static void Main()
{
//establish DateTimes
DateTime start = new DateTime(2010, 6, 14);
DateTime end = new DateTime(2016, 08, 14);

TimeSpan difference = end - start; //create TimeSpan object

Console.WriteLine("Difference in days: " + difference.Days);


//Extract days, write to Console.
}
}

17.) Write a C# Sharp program to convert the value of the


current DateTime object to local time
using System;

class Ex17
{
static void Main()
{
DateTime localDateTime, univDateTime;

Console.WriteLine("Enter a date and time.");


string strDateTime = Console.ReadLine();

try {
localDateTime = DateTime.Parse(strDateTime);
univDateTime = localDateTime.ToUniversalTime();

Console.WriteLine("{0} local time is {1} universal time.",


localDateTime,
univDateTime);
}
catch (FormatException) {
Console.WriteLine("Invalid format.");
return;
}

Console.WriteLine("Enter a date and time in universal time.");


strDateTime = Console.ReadLine();

try {
univDateTime = DateTime.Parse(strDateTime);
localDateTime = univDateTime.ToLocalTime();

Console.WriteLine("{0} universal time is {1} local time.",


univDateTime,
localDateTime);
}
catch (FormatException) {
Console.WriteLine("Invalid format.");
return;
}

}
}

Write a program in C# Sharp to check whether the entered


18.)
year, month and day are current matching with current
year,month,day

using System;

class dttimeex18
{
static void Main()
{
int yr, mn, dt;

Console.Write("\n\n Check whether the given year, month and day


is the current or not :\n");
Console.Write("-----------------------------------------------
-------------------------\n");

Console.Write(" Input the Day : ");


dt = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Month : ");
mn = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Year : ");
yr = Convert.ToInt32(Console.ReadLine());
DateTime value = new DateTime(yr, mn, dt);
Console.WriteLine(" The formatted Date is :
{0}",value.ToString("dd/MM/yyyy"));
Console.WriteLine(" The current date status : {0}\n",value ==
DateTime.Today);
}
}

19.) Write a program in C# Sharp to compute what day was


yesterday.
using System;

class dttimeex19
{
static void Main()
{
Console.Write("\n\n Compute what day was Yesterday :\n");
Console.Write("--------------------------------------\n");
Console.WriteLine(" Today is : {0}",
DateTime.Today.ToString("dd/MM/yyyy"));
DateTime yd = GetYesterday();
Console.WriteLine(" The Yesterday was : {0} \n",
yd.ToString("dd/MM/yyyy"));
}
static DateTime GetYesterday()
{
return DateTime.Today.AddDays(-1);
}
}

20.) Write a program in C# Sharp to compute what day will be


tomorrow
using System;

class dttimeex20
{
static void Main()
{
Console.Write("\n\n Compute what day will be Tomorrow :\n");
Console.Write("----------------------------------------\n");
Console.WriteLine(" Today is : {0}",
DateTime.Today.ToString("dd/MM/yyyy"));
DateTime dt = GetTomorrow();
Console.WriteLine(" The Tomorrow will be : {0} \n",
dt.ToString("dd/MM/yyyy"));
}
static DateTime GetTomorrow()
{
return DateTime.Today.AddDays(1);
}
}

21.)Write a program in C# Sharp to get the number of days of a


given month for a year.
using System;
using System.Globalization;

class dttimeex22
{
static void Main()
{

int mn,yr;

Console.Write("\n\n Find the number of days of a given month for a year :\


n");
Console.Write("----------------------------------------------------------
-\n");
Console.Write(" Input the Month No. : ");
mn = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Year : ");
yr = Convert.ToInt32(Console.ReadLine());
DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
string mnum = dinfo.GetMonthName(mn);
int nodays = DateTime.DaysInMonth(yr,mn);
Console.WriteLine(" The Number of days in the month {0} is : {1} \
n",mnum,nodays);

}
}
22.) Write a program in C# Sharp to create a file and move the
file into the same directory to with different name.
using System;
using System.IO;
using System.Text;

public class SimpleFileMove


{
static void Main()
{

string sfileName = @"mytest.txt";


string tfileName = @"mynewtest.txt";

/* string sourcefolder = "path"; // you can mention the path of source


folder
string targetfolder = "path"; // you can mention the path of
target folder
string sourceFile = System.IO.Path.Combine(sourcefolder,
sfileName); // combine the source file with path
string targetFile = System.IO.Path.Combine(targetfolder,
tfileName); // combine the target file with path */

if (File.Exists(sfileName))
{
File.Delete(sfileName);
}
if (File.Exists(tfileName))
{
File.Delete(tfileName);
}
Console.Write("\n\n Create a file and move the file in
same folder to another name :\n");
Console.Write("------------------------------------------
----------------------------\n");
// Create the file.
using (StreamWriter fileStr = File.CreateText(sfileName))
{
fileStr.WriteLine(" Hello and Welcome");
fileStr.WriteLine(" It is the first content");
fileStr.WriteLine(" of the text file mytest.txt");
}
using (StreamReader sr = File.OpenText(sfileName))
{
string s = "";
Console.WriteLine(" Here is the content of the
file {0} : ",sfileName);
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
Console.WriteLine("");
}
System.IO.File.Move(sfileName, tfileName); // move a file to another name
in same location:
Console.WriteLine(" The file {0} successfully moved to the name {1} in the
same directory.",sfileName,tfileName );

using (StreamReader sr = File.OpenText(tfileName))


{
string s = "";
Console.WriteLine(" Here is the content of the
file {0} : ",tfileName);
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
Console.WriteLine("");
}
Console.ReadKey();
}
}

23.)Write a program in C# Sharp to create and read the last


line of a file.
using System;
using System.IO;

class filexercise22
{
static void Main()
{
string fileName = @"mytest.txt";
string[] ArrLines ;
int n,i;

Console.Write("\n\n Create and read the last line of a file :\n");


Console.Write("-----------------------------------------------\
n");

if (File.Exists(fileName))
{
File.Delete(fileName);
}
Console.Write(" Input number of lines to write in the file :");
n= Convert.ToInt32(Console.ReadLine());
ArrLines=new string[n];
Console.Write(" Input {0} strings below :\n",n);
for(i=0;i<n;i++)
{
Console.Write(" Input line {0} : ",i+1);
ArrLines[i] = Console.ReadLine();
}
System.IO.File.WriteAllLines(fileName, ArrLines);
Console.Write("\n The content of the last line of the file {0} is :\
n",fileName);
if (File.Exists(fileName))
{
string[] lines = File.ReadAllLines(fileName);
Console.WriteLine(" {0}",lines[n-1]);
}
Console.WriteLine();
}
}

24.) Write a program in C# Sharp to read a specific line from a


file

using System;
using System.IO;

class filexercise24
{
static void Main()
{
string fileName = @"mytest.txt";
string[] ArrLines ;
int n,i,l;

Console.Write("\n\n Read a specific line from a file :\n");


Console.Write("----------------------------------------\n");

if (File.Exists(fileName))
{
File.Delete(fileName);
}
Console.Write(" Input number of lines to write in the file :");
n= Convert.ToInt32(Console.ReadLine());
ArrLines=new string[n];
Console.Write(" Input {0} strings below :\n",n);
for(i=0;i<n;i++)
{
Console.Write(" Input line {0} : ",i+1);
ArrLines[i] = Console.ReadLine();
}
System.IO.File.WriteAllLines(fileName, ArrLines);

Console.Write("\n Input which line you want to display :");


l = Convert.ToInt32(Console.ReadLine());
if(l>=1 && l<=n)
{
Console.Write("\n The content of the line {0} of the file {1} is : \
n",l,fileName);
if (File.Exists(fileName))
{
string[] lines = File.ReadAllLines(fileName);
Console.WriteLine(" {0}",lines[l-1]);
}}
else
{
Console.WriteLine(" Please input the correct
line no.");
}

Console.WriteLine();
}
}

25.) Write a program in C# Sharp to count the number of lines in


a file
using System;
using System.IO;
using System.Text;

class filexercise25
{
public static void Main()
{
string fileName = @"mytest.txt";
int count;

try
{
// Delete the file if it exists.
if (File.Exists(fileName))
{
File.Delete(fileName);
}
Console.Write("\n\n Count the number of lines in a file :\n");
Console.Write("------------------------------------------\
n");
// Create the file.
using (StreamWriter fileStr = File.CreateText(fileName))
{
fileStr.WriteLine(" test line 1");
fileStr.WriteLine(" test line 2");
fileStr.WriteLine(" Test line 3");
fileStr.WriteLine(" test line 4");
fileStr.WriteLine(" test line 5");
fileStr.WriteLine(" Test line 6");
}
using (StreamReader sr = File.OpenText(fileName))
{
string s = "";
count=0;
Console.WriteLine(" Here is the content of the
file mytest.txt : ");
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
count++;
}
Console.WriteLine("");
}
Console.Write(" The number of lines in the file {0} is : {1} \n\
n",fileName,count);
}
catch (Exception MyExcep)
{
Console.WriteLine(MyExcep.ToString());
}
}
}

You might also like