أخر الاخبار

تحديات do-while في لغة C#: حلول مبتكرة لأسئلة متنوعة

 Q) Write a C# program to find the value of z using do-while statement :

z = {

2xy + x  if i= 1

3xy − x  if i= 2

4xy/x  if i= 3

5xy ∗ x  if i= 4 }

sol//

using System;

public class FindZValue
{
    public static void Main(string[] args)
    {
        int x, y, i;

        Console.Write("Enter the value of x: ");
        x = int.Parse(Console.ReadLine());

        Console.Write("Enter the value of y: ");
        y = int.Parse(Console.ReadLine());

        Console.Write("Enter the value of i (1, 2, 3, or 4): ");
        i = int.Parse(Console.ReadLine());

        int z = 0; // Initialize z to avoid potential errors
        bool isValidInput = false; // Flag to track valid input

        do
        {
            if (i >= 1 && i <= 4)
            {
                isValidInput = true;
                break; // Exit the loop if valid input is received
            }
            Console.WriteLine("Invalid value for i. Please enter 1, 2, 3, or 4.");
            Console.Write("Enter the value of i again: ");
            i = int.Parse(Console.ReadLine());
        } while (!isValidInput);

        // Calculate z based on the value of i (assuming valid input)
        if (i == 1)
        {
            z = 2 * x * y + x;
        }
        else if (i == 2)
        {
            z = 3 * x * y - x;
        }
        else if (i == 3)
        {
            if (x == 0) // Handle division by zero
            {
                Console.WriteLine("Error: Division by zero is not allowed.");
                return;
            }
            z = 4 * x * y / x;
        }
        else if (i == 4)
        {
            z = 5 * x * y * x;
        }

        Console.WriteLine("The value of z is: " + z);
    }
}


Q) Draw a flowchart and write C# program to calculate area for rectangle and test if the area is greater than
50 or not? using do-while..

Sol//

The do-while loop makes the program calculate the area and check the condition at least once. Here's the flowchart:

          +-----------------+
          |     Start       |
          +-----------------+
                   v (do at least once)
          +-----------------+
          |  Enter length   |
          +-----------------+
                   v
          +-----------------+
          |  Enter width    |
          +-----------------+
                   v
          +-----------------+
          | Calculate area   |
          | (length * width) |
          +-----------------+
                   v
          +-----------------+
          |  Area > 50?      |
          +-----------------+
                   v
          +---------+       +---------+
          |  Yes     | ----> |   No    |
          +---------+       +---------+
                   v                   v
          +-----------------+       +-----------------+
          |  Print "Area > 50"|       |Print "Area <= 50"|
          +-----------------+       +-----------------+
                   v (check loop condition)
          +-----------------+
          |  Exit (if i > 0) |  | i--      |
          +-----------------+-------v
                                     +---------+
                                     | i > 0?   |
                                     +---------+
                                              v
                                           (no) /          (yes)
                                                  +---------+
                                                  | Exit     |
                                                  +---------+

C# program

C#
using System;

public class RectangleArea
{
    public static void Main(string[] args)
    {
        int length, width, area;
        int i = 1; // Loop counter (initialized to 1 for do-while execution)

        do
        {
            Console.Write("Enter the length of the rectangle: ");
            length = int.Parse(Console.ReadLine());

            Console.Write("Enter the width of the rectangle: ");
            width = int.Parse(Console.ReadLine());

            area = length * width;

            if (area > 50)
            {
                Console.WriteLine("The area of the rectangle is greater than 50.");
            }
            else
            {
                Console.WriteLine("The area of the rectangle is less than or equal to 50.");
            }

            i--; // Decrement loop counter

        } while (i > 0); // Loop continues as long as i is positive
    }
}


Q) Write C# program to find the value of z using the formula: using do-while
Q) Write C# program to find the value of z using the formula: using do-while


Sol//


C#
using System;

public class FindZValue
{
    public static void Main(string[] args)
    {
        int x, y, i;
        double z; // Use double for floating-point calculations

        do
        {
            Console.Write("Enter the value of x: ");
            x = int.Parse(Console.ReadLine());

            Console.Write("Enter the value of y: ");
            y = int.Parse(Console.ReadLine());

            Console.Write("Enter the value of i (1, 2, or 3): ");
            i = int.Parse(Console.ReadLine());

            if (i < 1 || i > 3)
            {
                Console.WriteLine("Invalid value for i. Please enter 1, 2, or 3.");
            }
            else
            {
                break; // Exit loop if valid input for i is entered
            }
        } while (true); // Loop continues until valid input is received

        switch (i)
        {
            case 1:
                z = Math.Sqrt(Math.Pow(x, 2) * Math.Pow(y, 2) + x * y + 5);
                break;
            case 2:
                z = Math.Abs(3 * Math.Pow(x, 2) - 2 * Math.Pow(y, 2) - 5);
                break;
            case 3:
                if (x == 0)
                {
                    Console.WriteLine("Error: Division by zero is not allowed.");
                    return;
                }
                z = 4.0 * x * y / x; // Cast x to double for division accuracy
                break;
        }

        Console.WriteLine("The value of z is: " + z);
    }
}


Q) Draw a flowchart to read two numbers x and y , and swap the two numbers if x divided by 4 using do-while.

Sol//


+----------------+
| Start           |
+----------------+
         v
+----------------+
| Read number x   |
+----------------+
         v
+----------------+
| Read number y   |
+----------------+
         v
+----------------+  +----------------+
| Is x divisible  |  |  Yes (Swap)    |
| by 4 (x % 4==0)? | ----> |               |
+----------------+         v
         v                 +----------------+
+----------------+         | Swap values of  |
|        No       | ----> | x and y         |
+----------------+         v
         v                 +----------------+
+----------------+         | Print x and y   |
| Print x and y   | ----> | (unchanged)      |
+----------------+         v
         v                 +----------------+
+----------------+         | End             |
|                 |         v
+----------------+         +----------------+


Q/ Write a C# program to read two integer numbers (a, b) and swap the two numbers if a and b are odd and a is divided by 5.using do-while?

Sol//

using System;

public class SwapIfOddAndDivisibleByFive_DoWhileLoop
{
    public static void Main(string[] args)
    {
        // Read two integer numbers from the user
        Console.Write("Enter the first number (a): ");
        int a = int.Parse(Console.ReadLine());

        Console.Write("Enter the second number (b): ");
        int b = int.Parse(Console.ReadLine());

        bool swapped = false; // Flag to track if swap happened

        do
        {
            // Check if both a and b are odd and a is divisible by 5
            if (a % 2 != 0 && b % 2 != 0 && a % 5 == 0)
            {
                // Swap the values of a and b
                int temp = a;
                a = b;
                b = temp;

                swapped = true; // Set flag to indicate swap
                break; // Exit loop after swap
            }

        } while (!swapped); // Loop until swapped

        if (swapped)
        {
            Console.WriteLine("Numbers swapped (both odd and first is divisible by 5):");
        }
        else
        {
            Console.WriteLine("Numbers not swapped (conditions not met):");
        }

        // Print the swapped or original values
        Console.WriteLine($"a = {a}");
        Console.WriteLine($"b = {b}");
    }
}


Q / Write a C# program to read the student’s name, gender, three scores and find the average of the scores then print “pass” when the average is greater than 50, otherwise print “failed”. using do-while?

Sol//
using System;

public class StudentResult_DoWhileLoop
{
    public static void Main(string[] args)
    {
        string name;
        char gender;
        double score1, score2, score3, average;
        bool validInput = false;

        do
        {
            // Read student information
            Console.Write("Enter student name: ");
            name = Console.ReadLine();

            Console.Write("Enter student gender (M/F): ");
            gender = char.ToUpper(Console.ReadKey().KeyChar); // Read and convert to uppercase

            Console.WriteLine(); // New line for better formatting

            // Read three scores with input validation
            validInput = true;
            do
            {
                try
                {
                    // Read score 1
                    Console.Write("Enter score 1: ");
                    score1 = double.Parse(Console.ReadLine());

                    // Read score 2
                    Console.Write("Enter score 2: ");
                    score2 = double.Parse(Console.ReadLine());

                    // Read score 3
                    Console.Write("Enter score 3: ");
                    score3 = double.Parse(Console.ReadLine());

                    break; // Exit inner loop if all scores are valid doubles
                }
                catch (FormatException)
                {
                    Console.WriteLine("Invalid score input. Please enter numerical scores.");
                    validInput = false; // Continue inner loop if any score is not a double
                }
            } while (!validInput);

            // Calculate average score
            average = (score1 + score2 + score3) / 3;

            // Ask user if they want to enter information for another student
            Console.WriteLine("\nEnter information for another student? (y/n)");
            string repeat = Console.ReadLine().ToLower();

            validInput = repeat == "y"; // Only continue the loop if user enters "y"
        } while (validInput);

        // Print student information and result for each entered student
        do
        {
            // Determine result (pass/fail)
            string result;
            if (average > 50)
            {
                result = "Pass";
            }
            else
            {
                result = "Fail";
            }

            // Print student information and result
            Console.WriteLine($"\nStudent Name: {name}");
            Console.WriteLine($"Gender: { (gender == 'M') ? "Male" : "Female" }"); // Ternary operator for gender
            Console.WriteLine($"Average Score: {average:F2}"); // Format average to two decimal places
            Console.WriteLine($"Result: {result}");

            // Ask user if they want to see results for another student (optional)
            if (!validInput) // Only ask if not already in the do-while loop
            {
                Console.WriteLine("\nSee results for another student? (y/n)");
                repeat = Console.ReadLine().ToLower();
                validInput = repeat == "y";
            }
        } while (validInput);
    }
}



Q/ Write C# program to find the count of all numbers less than 50 and find the summation of all numbers greater than or equal 50 , in a set of numbers ended by zero number. using do-while?

Sol//

using System;

class Program
{
    static void Main(string[] args)
    {
        int countLessThan50 = 0;
        int sumGreaterThanOrEqualTo50 = 0;
        int num;

        Console.WriteLine("Enter a set of numbers (enter 0 to end):");

        do
        {
            num = Convert.ToInt32(Console.ReadLine());

            if (num < 50 && num != 0)
            {
                countLessThan50++;
            }
            else if (num >= 50)
            {
                sumGreaterThanOrEqualTo50 += num;
            }
        } while (num != 0);

        Console.WriteLine($"Count of numbers less than 50: {countLessThan50}");
        Console.WriteLine($"Summation of numbers greater than or equal to 50: {sumGreaterThanOrEqualTo50}");
    }
}



Q/ Write C# program to find the value of z using the formula: using do-while

Q3/ Write C# program to find the value of z using the formula:


Sol//

using System;

public class CalculateZ_DoWhile
{
    public static void Main(string[] args)
    {
        // Read values for a, b, and n
        double a, b, n;
        do
        {
            Console.Write("Enter the value of a: ");
            a = double.Parse(Console.ReadLine());

            Console.Write("Enter the value of b (cannot be zero): ");
            b = double.Parse(Console.ReadLine());

            // Input validation for non-zero b
            if (b == 0)
            {
                Console.WriteLine("Error: b cannot be zero. Please enter a non-zero value for b: ");
            }
        } while (b == 0);

        do
        {
            Console.Write("Enter the value of n (positive integer): ");
            n = double.Parse(Console.ReadLine());

            // Input validation for positive n
            if (n <= 0)
            {
                Console.WriteLine("Error: n must be a positive integer. Please enter a positive value for n: ");
            }
        } while (n <= 0);

        // Calculate the value of z
        double z = 0;
        int i = 2;
        do
        {
            double term = i * (a + b) / ((i + 1) * b);
            z += term;
            i++;
        } while (i <= n + 1);

        // Print the result
        Console.WriteLine($"\nThe value of z is: {z:F2}");
    }
}


Q/ Write C# program to find the value of z using the formula: using do-while

Q2/ Write C# program to find the value of z using the formula:


Sol//

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the value of x:");
        double x = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Enter the value of y:");
        double y = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Enter the value of n:");
        int n = Convert.ToInt32(Console.ReadLine());

        double z = 0;
        int i = 2;

        do
        {
            if (i == 2)
            {
                z += (2 * Math.Pow(x, 3)) / (2 + y);
            }
            else
            {
                z += (i * Math.Pow(x, i + 1)) / (i + y);
            }
            i++;
        } while (i <= n);

        Console.WriteLine($"The value of z is: {z}");
    }
}


Q) Write a C# program to find the value of Y? using do-while.


Sol//

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the value of X:");
        double x = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Enter the value of n:");
        int n = Convert.ToInt32(Console.ReadLine());

        double y = 5;
        int i = 1;

        do
        {
            switch (i)
            {
                case 1:
                    y += (2 * Math.Pow(x, i)) / i;
                    break;
                case 2:
                    y += (4 * Math.Pow(x, i)) / i;
                    break;
                default:
                    y += ((i + 1) * Math.Pow(x, i)) / i;
                    break;
            }
            i++;
        } while (i <= n);

        Console.WriteLine($"The value of Y is: {y}");
    }
}


Q) Write C# program to find the average of set numbers ended by number divided by 3. using do-while?

Sol//

using System;

class Program
{
    static void Main(string[] args)
    {
        int sum = 0;
        int count = 0;

        Console.WriteLine("Enter numbers (end with a number divisible by 3):");

        int num;
        do
        {
            num = Convert.ToInt32(Console.ReadLine());

            // Check if the number is divisible by 3
            if (num % 3 == 0)
            {
                break; // Exit the loop if divisible by 3
            }

            sum += num;
            count++;
        } while (true);

        // Calculate and display the average
        if (count > 0)
        {
            double average = (double)sum / count;
            Console.WriteLine($"Average of the numbers: {average}");
        }
        else
        {
            Console.WriteLine("No numbers entered.");
        }
    }
}


تعليقات



حجم الخط
+
16
-
تباعد السطور
+
2
-