Group
Functions in C#
Objective
1. Define a function named "Double" that accepts an integer parameter by reference using the `ref` keyword.
2. Inside the function, multiply the input integer by 2.
3. As the function is a "void" function, it does not return anything but modifies the value of the parameter directly.
4. In the Main method, declare an integer variable and pass it to the "Double" function using the `ref` keyword.
5. Display the result using Console.Write.
Write a C# function named "Double" to calculate the double of an integer number, and modify the data passed as an argument. It must be a "void" function and you must use "reference parameters". For example, x = 5; Double(ref x); Console.Write(x); would display 10.
public static void Main()
{
int x = 5;
Double(ref x); // Pass x by reference to the Double function
Console.Write(x); // This should print 10
}
Example C# Exercise
Show C# Code
using System;
class Program
{
// Main method where the program execution begins
public static void Main()
{
// Declare an integer variable x and initialize it with 5
int x = 5;
// Call the Double function with x passed by reference
Double(ref x); // This will modify the value of x to 10
// Display the modified value of x
Console.Write(x); // This should print 10
}
// Function to double the value of the input integer using reference parameter
public static void Double(ref int number)
{
// Multiply the input number by 2 and update the value directly
number *= 2; // This will modify the value of number
}
}
Output
10