Use Basic Operators In C

CCIntermediate
Practice Now

Introduction

In this lab, you will learn how to use basic operators in C programming, including arithmetic, relational, and logical operators. You will start by introducing the different types of operators, then write sample code to demonstrate arithmetic operations such as addition, subtraction, multiplication, and division. Next, you will explore relational operators for comparison, and implement logical operators like AND, OR, and NOT. Finally, you will build a simple calculator program to put these concepts into practice.

This lab provides a solid foundation for understanding the fundamental operators in C, which are essential for performing calculations, making decisions, and building more complex programs.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("C")) -.-> c/BasicsGroup(["Basics"]) c(("C")) -.-> c/ControlFlowGroup(["Control Flow"]) c(("C")) -.-> c/FunctionsGroup(["Functions"]) c(("C")) -.-> c/UserInteractionGroup(["User Interaction"]) c/BasicsGroup -.-> c/data_types("Data Types") c/BasicsGroup -.-> c/operators("Operators") c/ControlFlowGroup -.-> c/if_else("If...Else") c/ControlFlowGroup -.-> c/switch("Switch") c/FunctionsGroup -.-> c/math_functions("Math Functions") c/UserInteractionGroup -.-> c/user_input("User Input") c/UserInteractionGroup -.-> c/output("Output") subgraph Lab Skills c/data_types -.-> lab-438288{{"Use Basic Operators In C"}} c/operators -.-> lab-438288{{"Use Basic Operators In C"}} c/if_else -.-> lab-438288{{"Use Basic Operators In C"}} c/switch -.-> lab-438288{{"Use Basic Operators In C"}} c/math_functions -.-> lab-438288{{"Use Basic Operators In C"}} c/user_input -.-> lab-438288{{"Use Basic Operators In C"}} c/output -.-> lab-438288{{"Use Basic Operators In C"}} end

Introduce C Operators

In the world of C programming, operators are the fundamental building blocks that allow us to perform various operations on data. Just like mathematical symbols help us calculate and compare values in everyday life, C operators enable programmers to manipulate variables, perform calculations, and make logical decisions in their code.

For beginners, think of operators as special tools in a programmer's toolkit. Each operator has a specific purpose and helps you transform, compare, or combine data in meaningful ways. Understanding these operators is like learning the basic grammar of the C programming language.

1.1 Arithmetic Operators

Arithmetic operators are the mathematical workhorses of C programming. They allow you to perform basic mathematical operations that you're already familiar with from school mathematics. These operators work with numeric data types like integers and floating-point numbers, enabling you to perform calculations directly in your code.

  • +: Addition - combines two numbers
  • -: Subtraction - finds the difference between numbers
  • *: Multiplication - multiplies two numbers
  • /: Division - divides one number by another
  • %: Modulus (remainder) - finds the remainder after division

When you use these operators, C will perform the calculation and return the result, just like a calculator would. This makes mathematical computations straightforward and intuitive in your programs.

1.2 Relational Operators

Relational operators are comparison tools that help you evaluate relationships between values. They always return a boolean result - either true (1) or false (0). These operators are crucial when you want to make decisions in your code, such as checking if one value is larger than another or if two values are equal.

  • >: Greater than - checks if the left value is larger
  • <: Less than - checks if the left value is smaller
  • ==: Equal to - checks if two values are exactly the same
  • >=: Greater than or equal to - checks if the left value is larger or equal
  • <=: Less than or equal to - checks if the left value is smaller or equal
  • !=: Not equal to - checks if two values are different

Relational operators form the backbone of conditional statements and control structures in C programming, allowing your code to make intelligent decisions based on value comparisons.

1.3 Logical Operators

Logical operators are powerful tools for combining multiple conditions and creating complex decision-making logic. They work with boolean values and help you create sophisticated conditions that can control the flow of your program.

  • &&: Logical AND - returns true only if all conditions are true
  • ||: Logical OR - returns true if at least one condition is true
  • !: Logical NOT - reverses the boolean value of a condition

These operators allow you to create intricate decision-making processes, letting your program respond intelligently to different scenarios by combining multiple conditions.

These operators are the foundation for performing calculations, making comparisons, and creating complex decision-making logic in C programs. Understanding their usage is essential for writing effective and efficient C code.

In the following steps, we will demonstrate the use of these operators with sample code, helping you understand how they work in real programming scenarios.

Write Sample Arithmetic Operations (Add, Sub, Mul, Div)

We'll dive deeper into arithmetic operations in C by creating a program that demonstrates various mathematical calculations. We'll write a comprehensive example that shows addition, subtraction, multiplication, and division with different types of numeric values.

Navigate to the project directory and create a new file:

cd ~/project
touch arithmetic_operations.c

Open the file in the WebIDE and add the following code:

#include <stdio.h>

int main() {
    // Integer arithmetic operations
    int a = 20, b = 5;

    // Addition
    int sum = a + b;
    printf("Addition: %d + %d = %d\n", a, b, sum);

    // Subtraction
    int difference = a - b;
    printf("Subtraction: %d - %d = %d\n", a, b, difference);

    // Multiplication
    int product = a * b;
    printf("Multiplication: %d * %d = %d\n", a, b, product);

    // Division
    int quotient = a / b;
    printf("Division: %d / %d = %d\n", a, b, quotient);

    // Modulus (remainder)
    int remainder = a % b;
    printf("Modulus: %d %% %d = %d\n", a, b, remainder);

    // Floating-point arithmetic
    float x = 10.5, y = 3.2;
    float float_sum = x + y;
    float float_difference = x - y;
    float float_product = x * y;
    float float_quotient = x / y;

    printf("\nFloating-point Arithmetic:\n");
    printf("Addition: %.2f + %.2f = %.2f\n", x, y, float_sum);
    printf("Subtraction: %.2f - %.2f = %.2f\n", x, y, float_difference);
    printf("Multiplication: %.2f * %.2f = %.2f\n", x, y, float_product);
    printf("Division: %.2f / %.2f = %.2f\n", x, y, float_quotient);

    return 0;
}

When learning programming, it's essential to understand how different data types impact mathematical operations. This example demonstrates the nuanced behavior of arithmetic operations in C, showcasing the differences between integer and floating-point calculations.

Compile and run the program:

gcc arithmetic_operations.c -o arithmetic_operations
./arithmetic_operations

Example output:

Addition: 20 + 5 = 25
Subtraction: 20 - 5 = 15
Multiplication: 20 * 5 = 100
Division: 20 / 5 = 4
Modulus: 20 % 5 = 0

Floating-point Arithmetic:
Addition: 10.50 + 3.20 = 13.70
Subtraction: 10.50 - 3.20 = 7.30
Multiplication: 10.50 * 3.20 = 33.60
Division: 10.50 / 3.20 = 3.28

As you progress in your programming journey, understanding these fundamental arithmetic operations will help you build more complex algorithms and solve real-world computational problems. Each operator has its unique characteristics and use cases, which you'll discover through practice and exploration.

Key points to note:

  • Integer division truncates the decimal part
  • The modulus operator (%) works only with integers
  • Floating-point arithmetic allows for decimal calculations
  • Use %.2f format specifier to display floating-point numbers with two decimal places

By mastering these basic arithmetic operations, you're laying a strong foundation for your programming skills and preparing yourself for more advanced computational techniques.

Relational Operators For Comparison (>, <, ==)

Relational operators in C provide a powerful way to compare different values, enabling programmers to make decisions and control the flow of their programs. These operators act like mathematical comparison tools, allowing you to check relationships between numbers and determine logical conditions.

Navigate to the project directory and create a new file:

cd ~/project
touch relational_operators.c

When working with relational operators, you'll be exploring how different values relate to each other. The following code demonstrates the core comparison techniques used in C programming:

#include <stdio.h>

int main() {
    int a = 10, b = 20, c = 10;

    // Greater than (>)
    printf("Greater than comparison:\n");
    printf("%d > %d is %d\n", a, b, a > b);
    printf("%d > %d is %d\n", b, a, b > a);

    // Less than (<)
    printf("\nLess than comparison:\n");
    printf("%d < %d is %d\n", a, b, a < b);
    printf("%d < %d is %d\n", b, a, b < a);

    // Equal to (==)
    printf("\nEqual to comparison:\n");
    printf("%d == %d is %d\n", a, b, a == b);
    printf("%d == %d is %d\n", a, c, a == c);

    // Other relational operators
    printf("\nOther comparisons:\n");
    printf("%d >= %d is %d\n", a, c, a >= c);  // Greater than or equal to
    printf("%d <= %d is %d\n", a, b, a <= b);  // Less than or equal to
    printf("%d != %d is %d\n", a, b, a != b);  // Not equal to

    return 0;
}

Compile and run the program to see how these comparisons work in real-time:

gcc relational_operators.c -o relational_operators
./relational_operators

When you run this program, you'll see a detailed breakdown of different comparison scenarios. Each comparison results in either 1 (true) or 0 (false), which is how C represents logical conditions.

Example output:

Greater than comparison:
10 > 20 is 0
20 > 10 is 1

Less than comparison:
10 < 20 is 1
20 < 10 is 0

Equal to comparison:
10 == 20 is 0
10 == 10 is 1

Other comparisons:
10 >= 10 is 1
10 <= 20 is 1
10 != 20 is 1

Key points about relational operators:

  • Relational operators return 1 (true) or 0 (false)
  • > checks if the left value is greater than the right value
  • < checks if the left value is less than the right value
  • == checks if two values are exactly equal
  • >= checks if left value is greater than or equal to right value
  • <= checks if left value is less than or equal to right value
  • != checks if two values are not equal

These operators are the building blocks of decision-making in programming. They allow you to create complex logical conditions, control program flow, and build intelligent algorithms. By mastering these operators, you'll be able to write more dynamic and responsive C programs that can make decisions based on different input conditions.

Implement Logical Operators (And, Or, Not)

In this step, we'll explore logical operators in C, which are essential for creating complex conditional statements and making decisions in your programs. Think of logical operators as the language of decision-making in your code, allowing you to build intricate reasoning paths.

Navigate to the project directory and create a new file:

cd ~/project
touch logical_operators.c

Open the file in the WebIDE and add the following code:

#include <stdio.h>

int main() {
    int x = 5, y = 10, z = 15;

    // Logical AND (&&)
    printf("Logical AND (&&) Demonstrations:\n");
    printf("(x < y) && (y < z) is %d\n", (x < y) && (y < z));
    printf("(x > y) && (y < z) is %d\n", (x > y) && (y < z));

    // Logical OR (||)
    printf("\nLogical OR (||) Demonstrations:\n");
    printf("(x > y) || (y < z) is %d\n", (x > y) || (y < z));
    printf("(x > y) || (y > z) is %d\n", (x > y) || (y > z));

    // Logical NOT (!)
    printf("\nLogical NOT (!) Demonstrations:\n");
    printf("!(x < y) is %d\n", !(x < y));
    printf("!(x > y) is %d\n", !(x > y));

    // Complex logical expressions
    printf("\nComplex Logical Expressions:\n");
    int a = 20, b = 30, c = 40;
    printf("((a < b) && (b < c)) is %d\n", ((a < b) && (b < c)));
    printf("((a > b) || (b < c)) is %d\n", ((a > b) || (b < c)));

    return 0;
}

When working with logical operators, it's crucial to understand how they transform boolean conditions. Each operator has a specific behavior that allows you to create nuanced logical evaluations.

Compile and run the program:

gcc logical_operators.c -o logical_operators
./logical_operators

Example output:

Logical AND (&&) Demonstrations:
(x < y) && (y < z) is 1
(x > y) && (y < z) is 0

Logical OR (||) Demonstrations:
(x > y) || (y < z) is 1
(x > y) || (y > z) is 0

Logical NOT (!) Demonstrations:
!(x < y) is 0
!(x > y) is 1

Complex Logical Expressions:
((a < b) && (b < c)) is 1
((a > b) || (b < c)) is 1

Key points about logical operators:

  • && (AND): Returns true only if both conditions are true
  • || (OR): Returns true if at least one condition is true
  • ! (NOT): Inverts the boolean value of a condition
  • Logical operators are often used in conditional statements
  • They help create more complex decision-making logic

These operators are fundamental for creating sophisticated conditional logic in C programs. By mastering these operators, you'll gain the ability to write more intelligent and responsive code that can handle complex scenarios with precision and clarity.

The beauty of logical operators lies in their simplicity and power. They transform simple boolean conditions into complex decision trees, allowing programmers to create intricate logical flows that can solve real-world programming challenges.

Build a Simple Calculator Program

As a beginner programmer, you'll learn how to transform mathematical operations into code and handle various user interaction scenarios. The simple calculator we're about to build will demonstrate the power of basic programming constructs in solving real-world problems.

Navigate to the project directory and create a new file:

cd ~/project
touch simple_calculator.c

Open the file in the WebIDE and add the following code:

#include <stdio.h>

int main() {
    char operator;
    double num1, num2, result;

    // Prompt user for input
    printf("Simple Calculator\n");
    printf("Enter an operator (+, -, *, /): ");
    scanf(" %c", &operator);

    printf("Enter two numbers: ");
    scanf("%lf %lf", &num1, &num2);

    // Perform calculation based on operator
    switch(operator) {
        case '+':
            result = num1 + num2;
            printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
            break;
        case '-':
            result = num1 - num2;
            printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
            break;
        case '*':
            result = num1 * num2;
            printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
            break;
        case '/':
            // Check for division by zero
            if (num2 != 0) {
                result = num1 / num2;
                printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
            } else {
                printf("Error! Division by zero is not allowed.\n");
            }
            break;
        default:
            printf("Error! Operator is not correct\n");
    }

    return 0;
}

This code represents a comprehensive introduction to several key programming concepts. The switch statement allows us to handle multiple operation scenarios efficiently, while the scanf() function enables dynamic user input. We've also incorporated essential error handling to prevent common mathematical pitfalls like division by zero.

Compile the program:

gcc simple_calculator.c -o simple_calculator

Run the calculator and try different operations:

./simple_calculator

Example interactions:

Simple Calculator
Enter an operator (+, -, *, /): +
Enter two numbers: 10 5
10.00 + 5.00 = 15.00

Simple Calculator
Enter an operator (+, -, *, /): *
Enter two numbers: 4 6
4.00 * 6.00 = 24.00

Simple Calculator
Enter an operator (+, -, *, /): /
Enter two numbers: 20 4
20.00 / 4.00 = 5.00

Key features of the calculator:

  • Uses switch statement to handle different operations
  • Handles four basic arithmetic operations
  • Includes error checking for division by zero
  • Uses scanf() for user input
  • Demonstrates use of operators learned in previous steps

The program combines several C programming concepts:

  • User input with scanf()
  • Arithmetic and comparison operators
  • Conditional statements
  • Basic error handling

By working through this example, you've taken an important step in understanding how programming can be used to solve practical problems. Each line of code represents a small but crucial decision that transforms mathematical logic into a functional computer program.

Summary

In this lab, we explored the fundamental operators in C programming, including arithmetic, relational, and logical operators. We started by introducing the different types of operators and demonstrated basic arithmetic operations such as addition, subtraction, multiplication, and division. We then delved into relational operators for comparison, allowing us to perform logical comparisons between values. Furthermore, we implemented logical operators, including AND, OR, and NOT, which are essential for building conditional statements and decision-making in our programs. Finally, we combined these concepts to create a simple calculator program, showcasing the practical application of operators in C.