0% found this document useful (0 votes)
7 views8 pages

C# Programs for Basic Operations

Uploaded by

yosefmuluye42
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)
7 views8 pages

C# Programs for Basic Operations

Uploaded by

yosefmuluye42
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

1. Write a C# program that prints the first 10 even numbers using a for loop.

Answer
using System;
public class EvenNumberPrinter
{
public static void Main()
{
for (int i = 2; i <= 10; i += 2)
{
[Link](i);
Output
2
4
6
8
10
2. Write a C# program that takes a number (1 to 7) as input and prints the corresponding day
of the week using a switch statement.
Answer
using System;
public class DayOfTheWeekPrinter
{
public static void Main()
{
[Link]("Enter a number (1-7): ");
int dayNumber = [Link]([Link]());
switch (dayNumber)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid input. Please enter a number between 1 and 7.");
break;
}
}
}
Example of Out put
if the user enters 5 out put is Friday

3. Write a C# program that takes two integers as input and prints whether their
sum is positive, negative, or zero. Use nested if statements.
Answer
using System;
public class SumAnalyzer
{
public static void Main()
{
[Link]("Enter the first number: ");
int num1 = [Link]([Link]());
[Link]("Enter the second number: ");
int num2 = [Link]([Link]());
int sum = num1 + num2;
if (sum > 0)
{
[Link]($"The sum of {num1} and {num2} is positive: {sum}");
}
else
{
if (sum < 0)
{
[Link]($"The sum of {num1} and {num2} is negative: {sum}");
}
else
{
[Link]($"The sum of {num1} and {num2} is zero: {sum}");
}
}
}
}
Example of Out put
For example, if the user enters 5 and 3, the program will output:
The sum of 5 and 3 is positive: 8
If the user enters -2 and 4, the program will output:
The sum of -2 and 4 is positive: 2
If the user enters 0 and 0, the program will output:
The sum of 0 and 0 is zero: 0
4. Write a C# program that creates an array of integers and prints its length.

Answer
using System;
public class ArrayLengthPrinter
{
public static void Main()
{
// Create an array of integers
int[] numbers = { 10, 20, 30, 40, 50 };

// Get the length of the array


int arrayLength = [Link];
// Print the length of the array
[Link]($"The length of the array is: {arrayLength}");
}
}

Out put
The length of the array is: 5

5. Write a C# program that creates a 3x3 matrix (2D array) of integers and
performs the following operations:
 Populate the matrix with random numbers between 1 and 10.
 Print the matrix.
 Find the sum of all elements in the matrix.
 Find the maximum value in the matrix.
 Transpose the matrix (convert rows to columns and vice versa) and print the transposed
matrix.
Answer
using System;
public class MatrixOperations
{
public static void Main()
{
// Create a 3x3 matrix of integers
int[,] matrix = new int[3, 3];
// Populate the matrix with random numbers between 1 and 10
Random random = new Random();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
matrix[i, j] = [Link](1, 11);
}
}

// Print the matrix


[Link]("The matrix:");
PrintMatrix(matrix);
// Find the sum of all elements in the matrix
int sum = FindMatrixSum(matrix);
[Link]($"The sum of all elements in the matrix is: {sum}");
// Find the maximum value in the matrix
int maxValue = FindMatrixMax(matrix);
[Link]($"The maximum value in the matrix is: {maxValue}");
// Transpose the matrix and print the transposed matrix
int[,] transposedMatrix = TransposeMatrix(matrix);
[Link]("The transposed matrix:");
PrintMatrix(transposedMatrix);
}
// Helper method to print the matrix
private static void PrintMatrix(int[,] matrix)
{
for (int i = 0; i < [Link](0); i++)
{
for (int j = 0; j < [Link](1); j++)
{
[Link]($"{matrix[i, j]} ");
}
[Link]();
}
[Link]();
}

// Helper method to find the sum of all elements in the matrix


private static int FindMatrixSum(int[,] matrix)
{
int sum = 0;
for (int i = 0; i < [Link](0); i++)
{
for (int j = 0; j < [Link](1); j++)
{
sum += matrix[i, j];
}
}
return sum;
}
// Helper method to find the maximum value in the matrix
private static int FindMatrixMax(int[,] matrix)
{
int maxValue = [Link];
for (int i = 0; i < [Link](0); i++)
{
for (int j = 0; j < [Link](1); j++)
{
if (matrix[i, j] > maxValue)
{
maxValue = matrix[i, j];
}
}
}
return maxValue;
}
// Helper method to transpose the matrix
private static int[,] TransposeMatrix(int[,] matrix)
{
int[,] transposedMatrix = new int[[Link](1), [Link](0)];
for (int i = 0; i < [Link](0); i++)
{
for (int j = 0; j < [Link](1); j++)
{
transposedMatrix[j, i] = matrix[i, j];
}
}
return transposedMatrix;
}
}
Example Out put
 The matrix:
384
619
275
 The sum of all elements in the matrix is: 45
 The maximum value in the matrix is: 9
 The transposed matrix:
362
817
495

Common questions

Powered by AI

The nested if statement in C# evaluates whether the computed sum of two integers is greater than, less than, or equal to zero. Initially, an if condition checks if the sum (num1 + num2) is greater than zero, printing it as positive. If the sum is not greater than zero, the program proceeds to an else block containing another if condition. This nested if checks if the sum is less than zero, in which case it prints the sum as negative. If neither condition is met, the program defaults to an else statement for zero, printing that the sum is zero .

Populating a C# matrix with random numbers between 1 and 10 involves creating a Random object and using its Next method within nested loops to assign a random integer to each matrix element. This approach is useful in scenarios requiring simulation or testing with non-specific data, ensuring varied and unpredictable content within the matrix to validate functionality of operations like summation or transposition .

Array length in C# is determined by the number of elements needed to be stored and is accessible through the Length property. Practical considerations include memory management, access time, and the specific application requirements. Knowing the array's length is crucial for iterating over elements safely and avoiding index out-of-bound errors, thus enhancing performance and reliability of operations on array data .

To find the largest integer within a 3x3 matrix in C#, iterate over each element using nested loops, keeping track of the maximum value found. Initialize a variable with the smallest possible integer value, then update this variable whenever a larger value is encountered during iteration. This traversal assures that at the end of the process, the variable holds the maximum value within the matrix .

The matrix sum provides an aggregate measure of all elements, useful for understanding overall trends or checking constraints like resource limitations. In contrast, the maximum value helps identify outliers or peak usage points. Both metrics serve complementary roles in data analysis, offering insights into total magnitude versus individual extremity, guiding decisions based on holistic versus critical factor evaluations .

The main steps in transposing a 3x3 matrix in C# involve: initializing a new 2D array to hold the transposed matrix, iterating through each element of the original matrix using two nested loops, and assigning the element at position [i, j] of the original matrix to position [j, i] of the transposed matrix. This effectively swaps rows and columns. A helper method can be used to perform and print the transposition .

A C# console program manages user interaction by reading inputs as strings, converting them to required data types (like int), and subsequently using structures like if-statements or switch-cases for decision-making. Input validation ensures meaningful interaction; for instance, ensuring numbers fall within an expected range (e.g., 1-7 for weekdays) prevents runtime errors and glean correct information. Feedback is provided through console outputs that guide or correct the user, enhancing usability and robustness of the application .

Helper methods in matrix operations within C# programs significantly enhance code modularity and readability. They encapsulate repetitive or complex functionality, such as printing a matrix or calculating a matrix's sum, into reusable blocks. This structure aids maintenance, reduces redundancy, and allows programmers to focus on higher-level logic without compromising on detail or precision of the underlying operations .

The switch statement in C# takes an integer input and uses it to select a corresponding case block to execute. Each case represents a day of the week, where the input number 1 corresponds to "Monday", 2 to "Tuesday", and so on. If a valid case is matched, the corresponding day is printed. An optional default block handles invalid inputs, informing the user to enter a number between 1 and 7 .

In a C# loop to iterate through only even numbers, one can start the loop counter at the smallest even number and increment by 2 in each iteration. This ensures only even numbers are processed, effectively optimizing the loop by skipping unnecessary computations for odd numbers. This technique is especially efficient when dealing with significant ranges of numbers .

You might also like