Exercise
Function Factorial (Iterative)
Objective
Write an C# iterative (non-recursive) function to calculate the factorial of the number specified as parameter:
Console.Write ( Factorial (6) );
would display
720
Write Your C# Exercise
C# Exercise Example
// Importing necessary namespaces
using System;
class Program
{
// Main method to drive the program
public static void Main()
{
// Calling the Factorial function with the number 6
Console.WriteLine(Factorial(6)); // Output will be 720
}
// Iterative function to calculate the factorial of a number
public static int Factorial(int n)
{
// Initialize the result variable to 1 (since factorial of 0 is 1)
int result = 1;
// Iterate through numbers from 1 to n and multiply them together
for (int i = 1; i <= n; i++)
{
result *= i; // Multiply the current result by i
}
// Return the calculated factorial value
return result;
}
}
More C# Programming Exercises of Functions
Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.
In this exercise of C#, you will learn how to create a function named "WriteTitle" that writes a text centered on the screen, in uppercase, with extra spaces, ...
In this exercise of C#, you will learn how to create a program in which you can use the WriteTitle function to write a title that the user will specify ...
In this exercise of C#, you will learn how to create a function that calculates the amount of numeric digits and vowels a text string contains. The function...
In this exercise of C#, you will learn how to create a function that tells if a character is alphabetic (from A to Z) or not. This function should be us...
In this exercise of C#, you will learn how to create a function that tells if a text string represents an integer number. This function should be used l...
In this exercise of C#, you will learn how to create a program that performs mathematical operations such as addition, subtraction, multiplication, or division...