Topics Covered:
Arrays
Strings
How to take user input
Simple Calculator Program
Few Basic Programs on the above topics
Interview Questions on the above topics
Arrays
An array is a collection of elements of the same type.
It is used to store multiple values of the same data type in a single variable.
Each element in the array is identified by an index value, which starts at 0 and goes up to (size of the array - 1).
There are two types of arrays in C#:
Single-dimensional arrays: These arrays have only one dimension and are represented by a single row of elements.
Multidimensional arrays: These arrays have more than one dimension and are represented by multiple rows and columns of elements.
To declare an array in C#, we need to specify the data type of the elements and the number of elements in the array.
Example:
How to declare and initialize an array of integers:
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
How to declare an array without initializing it:
int[] numbers = new int[5];
How to access the elements of an array(we need to use the index value):
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[2]); // Output: 3
How to change the value of an element in an array:
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
numbers[2] = 10;
Console.WriteLine(numbers[2]); // Output: 10
How to pass arrays as arguments to methods in C#:
void PrintArray(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine(arr[i]);
}
}
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
PrintArray(numbers);
We can also use loops to iterate over the elements of an array. Below is an example of using a for
loop:
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
So far we discussed Single-dimensional Arrays.
Let us get into multi-dimensional array
A multi-dimensional array is an array that contains more than one dimension. The most common type of multi-dimensional array is a two-dimensional array, but it is possible to have arrays with three or more dimensions.
To declare a multi-dimensional array in C#, we can use the following syntax:
datatype[,] arrayName = new datatype[rowSize, colSize];
Here, datatype
specifies the data type of the elements in the array, arrayName
is the name of the array, rowSize
specifies the number of rows, and colSize
specifies the number of columns.
For Example to declare a two-dimensional integer array with 3 rows and 4 columns:
int[,] arrayName = new int[3, 4];
Once We declare a multi-dimensional array, we can access its elements using the row and column indices.
For example to assign a value to the element at row 1 and column 2:
arrayName[1, 2] = 10;
You can also initialize the values of a multi-dimensional array using an array initializer.
For example to initialize a two-dimensional integer array with the following values:
1 2 3
4 5 6
We can use the following code:
int[,] arrayName = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
We can also declare and initialize a multi-dimensional array in a single line of code, like this:
int[,] arrayName = { { 1, 2, 3 }, { 4, 5, 6 } };
String
A String is a sequence of characters that is used to represent text.
It is one of the most commonly used data types and is widely used for storing and manipulating textual data.
Here are some important concepts and examples related to strings in C#:
- Declaring a string variable:
To declare a string variable in C#, use the string keyword followed by the name of the variable. Here is an example:
string myString;
- Initializing a string variable:
To initialize a string variable, you can use either double quotes or single quotes. Here is an example:
string myString = "Hello, world!";
- String concatenation:
String concatenation is the process of joining two or more strings together. In C#, you can concatenate strings using the + operator. Here is an example:
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
- String interpolation:
String interpolation is a feature in C# that allows you to embed expressions into a string. It makes it easier to create formatted strings. Here is an example:
string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";
- String comparison:
In C#, you can compare strings using the ==
operator or the Equals
method. However, when comparing strings, it is important to keep in mind that string comparisons are case-sensitive by default. Here is an example:
string s1 = "hello";
string s2 = "HELLO";
bool isEqual = (s1 == s2); // isEqual is false
bool isSame = s1.Equals(s2, StringComparison.OrdinalIgnoreCase); // isSame is true
- String manipulation:
C# provides several methods to manipulate strings. Some of the most commonly used string manipulation methods are:
ToUpper
: Converts all characters in the string to uppercase.ToLower
: Converts all characters in the string to lowercase.Trim
: Removes whitespace from the beginning and end of the string.
Here is an example that demonstrates the use of some of these string manipulation methods:
string myString = " Hello, World! ";
string upperCase = myString.ToUpper(); // upperCase is " HELLO, WORLD! "
string lowerCase = myString.ToLower(); // lowerCase is " hello, world! "
string trimmed = myString.Trim(); // trimmed is "Hello, World!"
String Immutability:
In C#, a string is immutable, which means that once a string object is created, its value cannot be changed. Any modification to the string value results in the creation of a new string object with the modified value. This is because the string object is stored in the memory in read-only mode, and the value cannot be altered.
Example:
string str = "Hello";
str = str + " World"; // Here a new string object is created with value "Hello World"
String Methods:
C# provides various built-in methods to work with strings, some of which are:
Length
: Returns the number of characters in the string.Substring()
: Returns a substring from the specified index to the end of the string or a specific number of characters.ToUpper()
: Converts all the characters in the string to uppercase.ToLower()
: Converts all the characters in the string to lowercase.IndexOf()
: Returns the index of the first occurrence of the specified substring in the string.Replace()
: Replaces all occurrences of a specified character or substring with a new value.Trim()
: Removes all leading and trailing white-space characters from the string.
Example:
string str = "Hello World";
int len = str.Length; // Returns the length of the string
string subStr = str.Substring(6); // Returns a substring starting from index 6
string upperStr = str.ToUpper(); // Converts the string to uppercase
string lowerStr = str.ToLower(); // Converts the string to lowercase
int index = str.IndexOf("World"); // Returns the index of the first occurrence of "World"
string newStr = str.Replace("World", "Universe"); // Replaces all occurrences of "World" with "Universe"
string trimmedStr = str.Trim(); // Removes leading and trailing whitespace characters from the string
How to take user input
To take user input in C# we use the Console.ReadLine() method.
Example 1:
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name + "!");
}
}
In this example, the user is prompted to enter their name using the Console.WriteLine()
method. Then, the Console.ReadLine()
method is used to read the user's input from the console and store it in a string variable named name
. Finally, the program uses the Console.WriteLine()
method again to output a greeting message that includes the user's name.
When you run this program, the console will display the message "Enter your name:" and wait for the user to enter a name. Once the user presses the Enter key, the program will read the user's input, store it in the name
variable, and output a greeting message that includes the user's name.
Example 2:
A program that takes two integer inputs from the user and calculates their sum:
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine("Enter the first number:");
int num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
int num2 = int.Parse(Console.ReadLine());
int sum = num1 + num2;
Console.WriteLine("The sum of {0} and {1} is {2}", num1, num2, sum);
}
}
I took this example to show you some important scenarios.
In C# user input is always taken as String and based upon the requirements that are converted into different data types, by using the Parse
method.
We can use Parse
to convert a string to float
, double
, bool
, DateTime
, and other data types. The syntax and usage of Parse
may vary slightly depending on the data type being converted.
This is the reason why Parse
is used in this code.
Simple Calculator Program
using System;
namespace Calc
{
class SimpleCalci
{
static void Main(string[] args)
{
double num1, num2, result;
char op;
Console.WriteLine("Enter first number: ");
num1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter operator (+, -, *, /): ");
op = char.Parse(Console.ReadLine());
Console.WriteLine("Enter second number: ");
num2 = double.Parse(Console.ReadLine());
switch (op)
{
case '+':
result = num1 + num2;
Console.WriteLine(num1 + " + " + num2 + " = " + result);
break;
case '-':
result = num1 - num2;
Console.WriteLine(num1 + " - " + num2 + " = " + result);
break;
case '*':
result = num1 * num2;
Console.WriteLine(num1 + " * " + num2 + " = " + result);
break;
case '/':
if (num2 == 0)
{
Console.WriteLine("Cannot divide by zero");
}
else
{
result = num1 / num2;
Console.WriteLine(num1 + " / " + num2 + " = " + result);
}
break;
default:
Console.WriteLine("Invalid operator");
break;
}
Console.ReadLine();
}
}
}
The above program implements a simple calculator using C# that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division.
First, the user is prompted to enter the first number using the Console.ReadLine() method and the input is stored in a variable called num1. Similarly, the second number is obtained from the user and stored in the num2 variable.
Next, the user is asked to choose the arithmetic operation they want to perform. The Console.ReadLine() method is used to take input from the user and the input is stored in the operation variable.
After that, the switch statement is used to perform the selected arithmetic operation based on the value of the operation variable.
This program showcases how to take input from the user, use a switch statement to perform different operations based on user input, and display output to the console.
Few Basic Programs
- C# program to find the largest element in an array:
using System;
class Program {
static void Main() {
int[] arr = {10, 25, 35, 48, 62, 77};
int max = arr[0];
for (int i = 1; i < arr.Length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
Console.WriteLine("The largest element in the array is: {0}", max);
}
}
- C# program to count the number of vowels in a string:
using System;
class Program {
static void Main() {
Console.Write("Enter a string: ");
string input = Console.ReadLine();
int count = 0;
string vowels = "aeiouAEIOU";
for (int i = 0; i < input.Length; i++) {
if (vowels.Contains(input[i].ToString())) {
count++;
}
}
Console.WriteLine("The number of vowels in the string is: {0}", count);
}
}
Interview Questions
Arrays:
What is an array in C#?
How do you declare an array in C#?
What is the difference between an array and a List in C#?
What is a jagged array?
How do you find the length of an array in C#?
How do you access elements of an array in C#?
What is an index out-of-range exception in C# and how do you handle it?
How do you iterate through an array in C#?
What is a multidimensional array in C#?
Can you resize an array in C#?
Strings:
What is a string in C#?
How do you declare a string in C#?
What is the difference between a string and a StringBuilder in C#?
How do you concatenate strings in C#?
What is an index out-of-range exception in C# and how do you handle it?
How do you compare strings in C#?
What is string interpolation in C#?
Can you convert a string to an int in C#?
What is the difference between String and string in C#?
What is a null string in C#?
Taking User Input:
How do you take user input in C#?
What is the difference between Console.ReadLine() and Console.Read() in C#?
How do you convert user input from a string to an integer in C#?
How do you handle user input errors in C#?
What is the difference between int.Parse() and int.TryParse() in C#?
How do you take input from a file in C#?
How do you take command-line arguments in C#?
How do you use the System.ArgumentNullException in C#?
How do you validate user input in C#?
How do you limit the amount of user input in C#?
Thank you for reading my Blog. I hope you have learned something from it!
If you find this blog helpful, please like, share, and follow me for more interesting posts like this in the future.