CodeBlanks Logo Icon CodeBlanks

Summary - Operators

C# course · Beginner · Lesson 29/116

Combine arithmetic, comparison and logical operators to build a grade calculator.

Bringing operators together

In this unit you learned five operator families: arithmetic (+ - * / %), comparison (== != < > <= >=), logical (&& || !), assignment (= += -= *= /= %=) and bitwise (& | ^ ~ << >>).

The real power is using them together in one program. A grade calculator: find the average with arithmetic, check the threshold with comparison, combine extra conditions with logical. A few steps give a real application.

Exercise Compute the grade average

Assign to average the sum of score1, score2 and score3 divided by 3. Then print average with Console.WriteLine. You must use arithmetic operators.

Show example solution
For the average, write int average = (score1 + score2 + score3) / 3;
Example solution:
using System;

class Program
{
    static void Main()
    {
        int score1 = 60;
        int score2 = 70;
        int score3 = 80;
        // Compute the average
        int average = (score1 + score2 + score3) / 3;
        Console.WriteLine(average);
    }
}

Exercise Print the pass/fail status

Write an if with the condition average >= 50. When true, print "passed" with Console.WriteLine; otherwise print "failed". You must use an else branch.

Show example solution
For the status, write if (average >= 50) { ... } else { ... }.
Example solution:
using System;

class Program
{
    static void Main()
    {
        int average = 70;
        // Print the status
        if (average >= 50)
        {
            Console.WriteLine("passed");
        }
        else
        {
            Console.WriteLine("failed");
        }
    }
}

Operator toolkit complete

You now know C#'s core operators. Arithmetic does the math, assignment updates variables, comparison makes decisions, logical combines conditions, and bitwise works with flags.

These five families will appear constantly in the arrays, loops and methods you will learn next. In particular, the short-circuit behavior of && and || is the key to writing safe conditions.

Test yourself

  1. What is the output of Console.WriteLine(2 + 3 * 4);?

    Console.WriteLine(2 + 3 * 4);
    • 20
    • 14
    • 9
    • 24
    Show answer

    14 — Correct. First 3 * 4 = 12, then 2 + 12 = 14.

  2. Write the bitwise AND operator

    int flags = 5;
    int mask = 3;
    int active = flags ____ mask;
    Console.WriteLine(active);
    Show answer
    int flags = 5;
    int mask = 3;
    int active = flags & mask;
    Console.WriteLine(active);

All lessons in Beginner