This C#.NET program demonstrates how to create and use a user-defined function to calculate the sum of two numbers. It helps in understanding function creation, parameter passing, and method calling in C#.
Slip 3 Q.A) Write a program in C# .Net to create a function for the sum of two numbers. 15 Marks
Answer:
Algorithm / Logic
- Start the program.
- Create a function named
Sum()that accepts two integer parameters. - Inside the function, add the two numbers and return the result.
- In the
Main()method, accept two numbers from the user. - Call the
Sum()function by passing the two numbers as arguments. - Display the returned result.
- Stop the program.
Source Code
using System;
namespace SumOfTwoNumbers
{
class Program
{
static int AddTwoNumbers(int num1, int num2)
{
return num1 + num2;
}
static void Main(string[] args)
{
int number1 = 10;
int number2 = 20;
int sum = AddTwoNumbers(number1, number2);
Console.WriteLine("The sum of " + number1 + " and " + number2 + " is: " + sum);
Console.ReadLine();
}
}
}
FAQ Section
Q1. What is a function in C#?
A function is a block of code that performs a specific task and can be reused.
Q2. Why are functions used?
Functions improve code reusability, readability, and modularity.
Q3. What is a user-defined function?
A function created by the programmer to perform a specific task.
Q4. What is the return type of the Sum() function?
The return type is int.
Q5. What are parameters?
Parameters are variables used to receive values passed to a function.