How to Do Percentage Calculation in C#

Muhammad Zeeshan Feb 02, 2024
How to Do Percentage Calculation in C#

This article will demonstrate how to calculate percentages in the C# programming language.

Create a Program That Will Calculate Percentage Using C#

To begin, we must import the following libraries.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Then construct four double type variables named sub1, sub2, sub3 and sub4. There will also be a variable called total that will store the total marks for all subjects.

Also, create a double type percentage variable named per.

double sub1, sub2, sub3, sub4, total;
double per;

We can now calculate the percentage using the formula provided.

per = total / 4;  // Here "total" holds the total marks of all subjects, and "4" is the total number
                  // of subjects.

Full Source Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class PercentageCalculation {
  static void Main(string[] args) {
    double sub1, sub2, sub3, sub4, total;
    double per;
    Console.Write("Enter marks of subjects to find out the percentage. \n");
    Console.Write("Input  the marks of Subject1: ");
    sub1 = Convert.ToInt32(Console.ReadLine());
    Console.Write("Input  the marks of Subject2: ");
    sub2 = Convert.ToInt32(Console.ReadLine());
    Console.Write("Input  the marks of Subject3: ");
    sub3 = Convert.ToInt32(Console.ReadLine());
    Console.Write("Input  the marks of Subject4: ");
    sub4 = Convert.ToInt32(Console.ReadLine());
    total = sub1 + sub2 + sub3 + sub4;
    per = total / 4;
    Console.Write("Percentage = {0}%\n", per);
  }
}

Output:

Enter marks of subjects to find out the percentage.
Input  the marks of Subject1: 34
Input  the marks of Subject2: 45
Input  the marks of Subject3: 56
Input  the marks of Subject4: 45
Percentage = 45%
Muhammad Zeeshan avatar Muhammad Zeeshan avatar

I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.

LinkedIn