Wednesday, March 05, 2025

Practical Examples of Using Operators in the C Programming Language

In the C programming language, operators are symbols that enable the execution of specific operations on data, such as mathematical calculations, logical comparisons, or bit manipulations. Operators are symbols that instruct the compiler what to do with operands in an expression. Understanding operators is crucial for writing efficient and effective code. The C programming language is known for its simplicity and direct hardware control, which is reflected in its set of operators. C programming language operators reflect its low-level and efficiency philosophy. Unlike higher-level languages such as Python or JavaScript, the C programming language does not have operators for advanced functionalities like exponentiation ** in the Python programming language because it focuses on simplicity and control. Bitwise and pointer operators make the C programming language powerful for system programs, while the lack of logical types or automatic memory management requires greater programmer attention compared to modern languages. Essentially, C programming language operators are the foundation for many other languages, but their directness and minimalism remain unique.

Operators in the C programming language require deeper knowledge

Operators in the C programming language require deeper knowledge

The C programming language supports a wide range of operators used for various data operations. Each operator has its own specific behavior and rules of application, which allows programmers to manipulate data in various ways and execute complex operations. Correct use of operators can significantly improve code performance and readability. Operators in C programming language can be categorized into several types:
  • Arithmetic Operators
  • Assignment Operator
  • Compound Assignment Operators
  • Relational (Comparison) Operators
  • Logical Operators
  • Bitwise Operators
  • Unary Operators
  • Ternary Operators
  • Pointer Operators
  • Size and Type Operators
  • Etc.

Basic Arithmetic Operators in the C Programming Language: Everything You Need to Know

Arithmetic operators enable the execution of basic mathematical operations such as addition, subtraction, multiplication, and division. They also include operators for obtaining the remainder of division. Used for basic mathematical operations:

+  Adds the numbers.

-  Subtracts the second from the first.

*  Multiplies them.

/  Divides the first by the second.

%  Gives the remainder, we cast to int because modulo only works with integers in C

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir arithmetic_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd arithmetic_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial/arithmetic_operators$ code .

Create a file and name it arithmetic.c, then type the following code.

#include <stdio.h>

int main() {

    float num1, num2; // Using float for decimal numbers

    // Get input from the user

    printf("Enter first number: ");

    scanf("%f", &num1);

    printf("Enter second number: ");

    scanf("%f", &num2);

    printf("\n");

    // Perform and display all arithmetic operations

    printf("%.2f + %.2f = %.2f\n", num1, num2, num1 + num2); // Addition

    printf("%.2f - %.2f = %.2f\n", num1, num2, num1 - num2); // Subtraction

    printf("%.2f * %.2f = %.2f\n", num1, num2, num1 * num2); // Multiplication

    printf("%.2f / %.2f = %.2f\n", num1, num2, num1 / num2); // Division

    printf("%d %% %d = %d\n", (int)num1, (int)num2, (int)num1 % (int)num2); // Modulo 

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/arithmetic_operators

$ gcc arithmetic.c -o arithmetic

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/arithmetic_operators

$ ./arithmetic

Enter first number: 18

Enter second number: 13

 

18.00 + 13.00 = 31.00

18.00 - 13.00 = 5.00 

18.00 * 13.00 = 234.00

18.00 / 13.00 = 1.38 

18 % 13 = 5

You can also watch a video of how the program is coded.


C Tutorial - 8. Arithmetic Operators in C Programming Language

How the Assignment Operator Works in the C Programming Language


In the C programming language, the assignment operator = is one of the most important and frequently used operators. It allows assigning a value from the right side of the operator to a variable located on the left side of the operator. Understanding the assignment operator is crucial for writing efficient and readable code in the C programming language. By using the assignment operator, you can easily manipulate variable values and manage data in your program. Used to assign values to variables:

=   Assign value

Example:

int x = 10;  // Assigns 10 to x

Learning Compound Assignment Operators: Step by Step

In addition to the basic assignment operator, C programming language also supports compound assignment operators that combine arithmetic or bitwise operations with assignment. Compound assignment operators, or simply combined operators, are a special type of operator in programming languages that combine arithmetic, logical, or bitwise operations with the assignment operation. These operators allow for shorter and more readable code, as they perform two things in one line: execute an operation and assign the result to the same variable. These combine an arithmetic operation with assignment:

+=   Add and assign

-=   Subtract and assign

*=   Multiply and assign

/=   Divide and assign

%=   Modulo and assign

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir compound_assignment_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd compound_assignment_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial/compound_assignment _operators$ code .

Create a file and name it assignment.c, then type the following code.

#include <stdio.h>

int main() {

    float num1, num2, temp1, temp2; 

    // Get input from the user

    printf("Enter first number: ");

    scanf("%f", &num1);

    printf("Enter second number: ");

    scanf("%f", &num2);

    printf("\n");

    // Use compound assignment operators with temporary variables

    temp1 = num1; // Store original num1 for each operation

    temp2 = num2; // Store original num2 though we won't modify num2 here

    temp1 += num2; // Addition and assignment

    printf("%.2f += %.2f becomes %.2f\n\n", num1, num2, temp1);


    temp1 = num1; // Reset temp1

    temp1 -= num2; // Subtraction and assignment

    printf("%.2f -= %.2f becomes %.2f\n\n", num1, num2, temp1);

 

    temp1 = num1; // Reset temp1

    temp1 *= num2; // Multiplication and assignment

    printf("%.2f *= %.2f becomes %.2f\n\n", num1, num2, temp1);

 

    temp1 = num1; // Reset temp1

    temp1 /= num2; // Division and assignment

    printf("%.2f /= %.2f becomes %.2f\n\n", num1, num2, temp1);

 

    // For modulo, we need integers

    int int_num1 = (int)num1; // Cast to int

    int int_temp1 = (int)int_num1; // Temp to modulo

    int int_num2 = (int)num2;

 

    int_temp1 %= int_num2; // Modulo and assignment

    printf("%d %%= %d becomes %d\n", int_num1, int_num2, int_temp1);

    return 0;

    printf("\n");

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/compound_assignment_operators

$ gcc assignment.c -o assignment

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/compound_assignment_operators

$ ./assignment

Enter first number: 18

Enter second number: 13


18.00 += 13.00 becomes 31.00

18.00 -= 13.00 becomes 5.00 

18.00 *= 13.00 becomes 234.00

18.00 /= 13.00 becomes 1.38 

18 %= 13 becomes 5

You can also watch a video of how the program is coded.


C Tutorial - 9. Compound Assignment Operators in C Programming Language

How Relational Operators Work in the C Programming Language?

Relational operators in the C programming language allow for the comparison of two values, which can be numbers, characters, and even pointers in some cases. They return a value of type int, where 1 means the condition is met true, and 0 means the condition is not met false. This is important to understand because the C programming language does not have an explicit bool data type in the traditional sense, prior to the C99 standard; instead, logical values are represented as integers. Relational operators are most commonly used in conditional statements and loops, and are often combined with logical operators. Used for comparing values:

==   Equal to

!=   Not equal to

>   Greater than

<   Less than

>=   Greater than or equal to

<=   Less than or equal to

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir arithmetic_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd relational_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial/relational_operators$ code .

Create a file and name it relational.c, then type the following code.

#include <stdio.h>

int main() {

    float num1, num2; // Using float to allow decimal numbers

    // Get input from the user

    printf("Enter first number: ");

    scanf("%f", &num1);

    printf("Enter second number: ");

    scanf("%f", &num2);

    printf("\n");

   

    // Demonstrate all relational operators

    printf("Relational Operators Results:\n");

    printf("\n");

    printf("%.2f == %.2f : %d\n", num1, num2, num1 == num2); // Equal to

    printf("%.2f != %.2f : %d\n", num1, num2, num1 != num2); // Not equal to

    printf("%.2f < %.2f : %d\n", num1, num2, num1 < num2); // Less than

    printf("%.2f > %.2f : %d\n", num1, num2, num1 > num2); // Greater than

    printf("%.2f <= %.2f : %d\n", num1, num2, num1 <= num2); // Less than or equal to

    printf("%.2f >= %.2f : %d\n", num1, num2, num1 >= num2); // Greater than or equal to

    printf("\n");

    return 0;

 }

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/relational_operators

$ gcc relational.c -o relational

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/relational_operators

$ ./relational

Enter first number: 18

Enter second number: 13

 

Relational Operators Results:

 

18.00 == 13.00 : 0

18.00 != 13.00 : 1

18.00 < 13.00 : 0

18.00 > 13.00 : 1

18.00 <= 13.00 : 0

18.00 >= 13.00 : 1

You can also watch a video of how the program is coded.


C Tutorial - 10. Relational Operators in C Programming Language

Effective Use of Logical Operators in C Programming

Logical operators are operators that enable the combination or manipulation of logical expressions. In the C programming language, logical operators return a result of type int, where 1 represents true, and 0 represents false. It's important to note that C, prior to the C99 standard, does not have an explicit bool data type, so logical values are interpreted through integers (int). Logical operators are often used together with relational operators to form complex conditions. Used for logical operations:

&&  Logical AND

||  Logical OR

!  Logical NOT

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir logical_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd logical_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial/logical_operators$ code .

Create a file and name it logical.c, then type the following code.

#include <stdio.h>

int main() {

    int temperature;

    int isRaining;

    // Get user input

    printf("Enter the temperature (in Celsius): ");

    scanf("%d", &temperature);

    printf("Is it raining? (1 for yes, 0 for no): ");

    scanf("%d", &isRaining);

    printf("\n");


    // Logical expressions without if statements

    int isWarm = (temperature > 20);  // True if temp is above 20°C

    int isCold = (temperature < 10);  // True if temp is below 10°C

    int isDry = !isRaining;  // True if it's not raining (negation)


    // Combining logical operators and printing results directly

    printf("Is it warm AND dry? %d\n", isWarm && isDry); // AND example

    printf("Is it cold OR raining? %d\n", isCold || isRaining); // OR example

    printf("Is it NOT raining? %d\n", !isRaining); // NOT example


    // A more complex combination

    printf("Is it warm AND (dry OR cold)? %d\n", isWarm && (isDry || isCold));

    printf("\n");

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/logical_operators

$ gcc logical.c -o logical

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/logical_operators

$ ./logical

Enter the temperature (in Celsius): 18

Is it raining? (1 for yes, 0 for no): 0

 

Is it warm AND dry? 0

Is it cold OR raining? 0      

Is it NOT raining? 1

Is it warm AND (dry OR cold)? 0

You can also watch a video of how the program is coded.


C Tutorial - 11. Logical Operators in C Programming Language

In-depth Understanding of Bitwise Operators in C Language

Bitwise operators in the C programming language allow for the manipulation of data at the level of individual bits in memory. These operators are particularly useful in situations where it is necessary to work directly with binary data, for example in system programming, performance optimization, hardware interaction, or the implementation of algorithms that require bit manipulation. Bitwise operators perform operations directly on the bits of variables, such as int, char, etc. In the C programming language, all values are internally represented as sequences of bits, for example 32 bits for an int on most architectures, and bitwise operators allow for the manipulation of these bits in a logical or arithmetic manner. Unlike logical operators, which operate on the level of entire values and return logical results, bitwise operators operate on each bit individually and return a new value of the same type as the operands. Used for bit-level operations:

&  Bitwise AND

|  Bitwise OR

^  Bitwise XOR

~  Bitwise NOT

<<  Left shift

>>  Right shift

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir bitwise_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd bitwise_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial/bitwise_operators$ code .

Create a file and name it bitwise.c, then type the following code.

#include <stdio.h>

// Function to display the binary form of a number

void printBinary(unsigned int num) {

    for (int i = 31; i >= 0; i--) {

        printf("%d", (num >> i) & 1);

        if (i % 4 == 0) printf(" "); // Space for readability

    }

    printf("\n");

}

int main() {

    unsigned int a = 29;    // 0001 1101 in binary

    unsigned int b = 14;    // 0000 1110 in binary

   

    printf("Values:\n");

    printf("a = %u\n", a);

    printf("b = %u\n", b);

    printf("\n");

 

    // Bitwise AND (&)

    printf("Bitwise AND (a & b):\n");

    printBinary(a);

    printBinary(b);

    printf("Result: ");

    printBinary(a & b);  // 0000 1100 = 12

    printf("Decimal: %u\n\n", a & b);

 

    // Bitwise OR (|)

    printf("Bitwise OR (a | b):\n");

    printBinary(a);

    printBinary(b);

    printf("Result: ");

    printBinary(a | b);  // 0001 1111 = 31

    printf("Decimal: %u\n\n", a | b);

 

    // Bitwise XOR (^)

    printf("Bitwise XOR (a ^ b):\n");

    printBinary(a);

    printBinary(b);

    printf("Result: ");

    printBinary(a ^ b);  // 0001 0011 = 19

    printf("Decimal: %u\n\n", a ^ b);

 

    // Bitwise NOT (~)

    printf("Bitwise NOT (~a):\n");

    printBinary(a);

    printf("Result: ");

    printBinary(~a);     // 1110 0010

    printf("Decimal: %u\n\n", ~a);

 

    // Left Shift (<<)

    printf("Left Shift (a << 2):\n");

    printBinary(a);

    printf("Result: ");

    printBinary(a << 2); // 0111 0100 = 116

    printf("Decimal: %u\n\n", a << 2);

 

    // Right Shift (>>)

    printf("Right Shift (a >> 1):\n");

    printBinary(a);

    printf("Result: ");

    printBinary(a >> 1); // 0000 1110 = 14

    printf("Decimal: %u\n", a >> 1);

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/bitwise_operators

$ gcc bitwise.c -o bitwise

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/bitwise_operators

$ ./bitwise

Values:

a = 29

b = 14

 

Bitwise AND (a & b):

0000 0000 0000 0000 0000 0000 0001 1101

0000 0000 0000 0000 0000 0000 0000 1110

Result: 0000 0000 0000 0000 0000 0000 0000 1100

Decimal: 12

 

Bitwise OR (a | b):

0000 0000 0000 0000 0000 0000 0001 1101

0000 0000 0000 0000 0000 0000 0000 1110

Result: 0000 0000 0000 0000 0000 0000 0001 1111

Decimal: 31

 

Bitwise XOR (a ^ b):

0000 0000 0000 0000 0000 0000 0001 1101

0000 0000 0000 0000 0000 0000 0000 1110

Result: 0000 0000 0000 0000 0000 0000 0001 0011

Decimal: 19

 

Bitwise NOT (~a):

0000 0000 0000 0000 0000 0000 0001 1101

Result: 1111 1111 1111 1111 1111 1111 1110 0010

Decimal: 4294967266

 

Left Shift (a << 2):

0000 0000 0000 0000 0000 0000 0001 1101

Result: 0000 0000 0000 0000 0000 0000 0111 0100

Decimal: 116

 

Right Shift (a >> 1):

0000 0000 0000 0000 0000 0000 0001 1101

Result: 0000 0000 0000 0000 0000 0000 0000 1110

Decimal: 14 

You can also watch a video of how the program is coded.


C Tutorial - 12. Bitwise Operators in C Programming Language

Unary Operators in the C Programming Language: An Introduction

Unary operators are operators in the C programming language that operate on only one operand. They are used in various contexts in C, from basic arithmetic manipulations to working with memory and logical expressions. They differ from binary operators like +, -, * which operate on two operands, and ternary operators like ?. Unary operators are used for various purposes, including sign change, incrementing, decrementing, logical negation, bitwise negation, memory address access, and pointer dereferencing. Although they are simple to use, they require care with complex expressions, especially increment/decrement and bitwise negation. Understanding their behavior and precedence is crucial for writing efficient and correct code.

+  Positive number

-  Negation

++ Increment

--  Decrement

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir unary_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd unary_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial/unary_operators$ code .

Create a file and name it unary.c, then type the following code.

#include <stdio.h>

int main() {

    // Declare and initialize some variables

    int a = 10;

    int b = -5;

    int flag = 1; // For logical NOT demo

 

    // Unary Plus (+) and Minus (-) Operators

    printf("Original value of a: %d\n", a);

    printf("Unary plus (+a): %d\n", +a); // Unary plus (doesn't change the value)

    printf("Original value of b: %d\n", b);

    printf("Unary minus (-b): %d\n", -b); // Unary minus (negates the value)

 

    // Increment (++) and Decrement (--) Operators

    printf("\nBefore increment, a: %d\n", a);

    a++; // Post-increment: increments a after using its value

    printf("After post-increment (a++), a: %d\n", a);

   

    ++a; // Pre-increment: increments a before using its value

    printf("After pre-increment (++a), a: %d\n", a);

 

    printf("\nBefore decrement, a: %d\n", a);

    a--; // Post-decrement: decrements a after using its value

    printf("After post-decrement (a--), a: %d\n", a);

   

    --a; // Pre-decrement: decrements a before using its value

    printf("After pre-decrement (--a), a: %d\n", a);

 

    // Logical NOT (!) Operator

    printf("\nOriginal value of flag: %d\n", flag);

    printf("Logical NOT (!flag): %d\n", !flag); // Returns 0 if flag is non-zero, 1 if flag is 0

   

    flag = 0; // Change flag to 0

    printf("New value of flag: %d\n", flag);

    printf("Logical NOT (!flag): %d\n", !flag); // Now returns 1 since flag is 0 

    // Sizeof Operator (also a unary operator)

    printf("\nSize of variable a (int) in bytes: %zu\n", sizeof(a));  

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/unary_operators

$ gcc unary.c -o unary

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/unary_operators

$ ./unary

Original value of a: 10

Unary plus (+a): 10

Original value of b: -5

Unary minus (-b): 5

 

Before increment, a: 10

After post-increment (a++), a: 11

After pre-increment (++a), a: 12

 

Before decrement, a: 12

After post-decrement (a--), a: 11

After pre-decrement (--a), a: 10

 

Original value of flag: 1

Logical NOT (!flag): 0

New value of flag: 0

Logical NOT (!flag): 1

 

Size of variable a (int) in bytes: 4

You can also watch a video of how the program is coded.


C Tutorial - 13. Unary Operators in C Programming Language

What Is the Ternary Operator in the C Programming Language?

The ternary operator is a conditional operator that allows for decision-making based on a condition in a single line of code, instead of using a standard if-else structure. The ternary operator in the C programming language is the only operator that uses three operands. Due to its compactness, it is often called the conditional operator because it functions as a shorter notation for simple if-else statements. In the C programming language, the ternary operator has the syntax condition ? expression1 : expression2, where one of the two expressions is chosen for evaluation based on the condition. Its compactness and inline usability make it popular in many situations, but it requires caution to avoid compromising code readability, especially with nested expressions. Understanding its behavior and limitations allows for effective use in the right situations. The only ternary operator in C is ? : .

? :  Ternary Operator

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir ternary_operator

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd ternary_operator

manuel@manuel-virtual-machine:/tutorials/c_tutorial/ternary_operator$ code .

Create a file and name it ternary.c, then type the following code.

#include <stdio.h>

int main() {

    // Declare some variables

    int age = 20;

    int num1 = 15, num2 = 10;


    // Using ternary operator to check if a person is eligible to vote

    printf("Age: %d\n", age);

    char *votingEligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";

    printf("Voting eligibility: %s\n", votingEligibility);


    // Change age to demonstrate the other case

    age = 16;

    printf("\nAge: %d\n", age);

    votingEligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";

    printf("Voting eligibility: %s\n", votingEligibility);

 

    // Using ternary operator to find the larger of two numbers

    printf("\nnum1: %d, num2: %d\n", num1, num2);

    int max = (num1 > num2) ? num1 : num2;

    printf("Larger number: %d\n", max);

 

    // Nested ternary operator, equivalent to nested if-else

    // Check if a number is positive, negative, or zero

    int number = -5;

    printf("\nNumber: %d\n", number);

    char *sign = (number > 0) ? "Positive" : (number < 0) ? "Negative" : "Zero";

    printf("Sign of the number: %s\n", sign);

 

    // Change number to demonstrate other cases

    number = 0;

    printf("\nNumber: %d\n", number);

    sign = (number > 0) ? "Positive" : (number < 0) ? "Negative" : "Zero";

    printf("Sign of the number: %s\n", sign);

     return 0;  

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/ternary_operator

$ gcc ternary.c -o ternary

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/ternary_operator

$ ./ternary

Age: 20

Voting eligibility: Eligible to vote   

Age: 16

Voting eligibility: Not eligible to vote

num1: 15, num2: 10

Larger number: 15

Number: -5

Sign of the number: Negative

Number: 0

Sign of the number: Zero

You can also watch a video of how the program is coded.


C Tutorial - 14. A Ternary Operator in C Programming Language

A Practical Guide to Pointers, Size, and Types in the C Programming Language

In the C programming language, operators related to pointers, size, and types are crucial for working with memory, manipulating data, and controlling data types. Pointers are variables that store the memory address of other variables. In the C programming language, there are two main operators used in conjunction with pointers: the address operator and the dereference operator. These operators are crucial for dynamic memory management and low-level data manipulation. For more on pointers, see the previous blog post, here. The sizeof operator is a unary operator that returns the size of an operand in bytes. It can be used on variables, data types, or even expressions. This operator is particularly useful for determining how much memory a particular piece of data occupies, which is important for dynamic memory allocation and working with arrays. Operators related to data types in the C programming language include explicit type conversion, type casting, which is not an operator in the classical sense, but is used to change the data type of an operand. The syntax for explicit conversion is type.

&   Address

*   Dereferencing

sizeof   Size of type

_Alignof   Alignment of type

Open your terminal and type the following code.

manuel@manuel-virtual-machine:~$ sudo apt-get update

manuel@manuel-virtual-machine:~$ sudo apt-get upgrade

manuel@manuel-virtual-machine:~$ clear

manuel@manuel-virtual-machine:~$ ls

manuel@manuel-virtual-machine:~$ cd tutorials

manuel@manuel-virtual-machine:/tutorials$ ls

manuel@manuel-virtual-machine:/tutorials$ cd c_tutorial

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ ls

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ mkdir pointer_size_type_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial$ cd pointer_size_type_operators

manuel@manuel-virtual-machine:/tutorials/c_tutorial/ pointer_size_type_operators$ code .

Create a file and name it pstoperators.c, then type the following code.

#include <stdio.h>

int main() {

    // Declare some variables of different types

    int num = 42;

    float pi = 3.14159;

    double largeNum = 123456.789;

 

    // 1. Pointer Operators: & (address-of) and * (dereference)

    printf("=== Pointer Operators ===\n");

 

    // Using & to get the address of a variable

    int *numPtr = &num; // numPtr stores the address of num

    printf("Value of num: %d\n", num);

    printf("Address of num (using &num): %p\n", (void*)&num);

    printf("Value of numPtr (address it holds): %p\n", (void*)numPtr);

 

    // Using * to dereference the pointer and access the value at that address

    printf("Value at address stored in numPtr (using *numPtr): %d\n", *numPtr);

 

    // Modify the value through the pointer

    *numPtr = 100;

    printf("New value of num after modifying through pointer: %d\n", num);

 

    // 2. Size Operator: sizeof

    printf("\n=== Size Operator (sizeof) ===\n");

 

    // Using sizeof to determine the size of variables and types in bytes

    printf("Size of int variable (num): %zu bytes\n", sizeof(num));

    printf("Size of float variable (pi): %zu bytes\n", sizeof(pi));

    printf("Size of double variable (largeNum): %zu bytes\n", sizeof(largeNum));

    printf("Size of pointer (numPtr): %zu bytes\n", sizeof(numPtr)); // Pointer size depends on architecture

 

    // Using sizeof with data types directly

    printf("Size of type int: %zu bytes\n", sizeof(int));

    printf("Size of type float: %zu bytes\n", sizeof(float));

    printf("Size of type double: %zu bytes\n", sizeof(double));

 

    // 3. Type Operators: Type Casting

    printf("\n=== Type Casting ===\n");

 

    // Implicit type casting (done automatically by compiler)

    int a = 10;

    float b = a; // Implicit cast from int to float

    printf("Integer a: %d\n", a);

    printf("Float b after implicit casting from int: %.2f\n", b);

 

    // Explicit type casting (manually cast one type to another)

    double d = 123.456;

    int truncated = (int)d; // Explicit cast from double to int (truncates decimal part)

    printf("Double d: %.3f\n", d);

    printf("Integer truncated after explicit casting: %d\n", truncated);

 

    // Casting pointer types (example of reinterpretation)

    float f = 5.75;

    int *intPtr = (int*)&f; // Cast float pointer to int pointer (dangerous, for demo only)

    printf("\nFloat f: %.2f\n", f);

    printf("Value interpreted as int (undefined behavior, for demo): %d\n", *intPtr);

    return 0;

}

When you execute the given code, you will get similar following result.

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/pointer_size_type_operators

$ gcc pstoperators.c -o pstoperators

 

manue@DESKTOP-E2QR9K9 MINGW64 /d/tutorials/c_tutorials/pointer_size_type_operators

$ ./pstoperators

=== Pointer Operators ===

Value of num: 42

Address of num (using &num): 000000EA5D3FF7B4       

Value of numPtr (address it holds): 000000EA5D3FF7B4

Value at address stored in numPtr (using *numPtr): 42

New value of num after modifying through pointer: 100

 

=== Size Operator (sizeof) ===

Size of int variable (num): 4 bytes

Size of float variable (pi): 4 bytes

Size of double variable (largeNum): 8 bytes

Size of pointer (numPtr): 8 bytes

Size of type int: 4 bytes

Size of type float: 4 bytes

Size of type double: 8 bytes

 

=== Type Casting ===

Integer a: 10

Float b after implicit casting from int: 10.00

Double d: 123.456

Integer truncated after explicit casting: 123

 

Float f: 5.75

Value interpreted as int (undefined behavior, for demo): 1085800448

You can also watch a video of how the program is coded.


C Tutorial - 15. A Pointer, Size and Type Operators in C Programming Language


 

 

 

 

 

No comments:

Post a Comment