0% found this document useful (0 votes)
28 views47 pages

Understanding Programming Languages

Uploaded by

rprathyushadcme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views47 pages

Understanding Programming Languages

Uploaded by

rprathyushadcme
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming Language

What Is A Programming Language?

A programming language is a set of instructions written by a programmer to deliver


instructions to the computer to perform and complete a task.

These languages are generally divided into two main categories:

1. Low Level Languages

2. High Level Languages

1. Low-Level Languages

These are closer to the machine's native language (binary), and they are
interpreted directly by the hardware.

There are two main types of low level languages:

1. Machine Language:

Machine language consists of sequence of instructions written in the form of


binary numbers to which computer responds directly. The machine only
understand the binaries digit 01, this is what we call the machine language.

All programs need to be translated into machine code before a computer can
understand and execute them.
Ex:- computer can understand only o ,1 language we convert into 0,1 form
through high level language.

24 —–> 11000

14 ——> 01110

Advantages:

1. Fast & efficient as statements are directly written in binary language.

2. No translator is required.

Disadvantages:

1. Difficult to learn binary codes.

2. Difficult to understand - both programs & where the error occurred.

2. Assembly Language

Assembly language contains human-readable codes that can be further converted


to machine language using an assembler.

• Uses short codes (like MOV, ADD, etc.)

NOTE:

• The assembler acts as a translator, converting human-readable assembly


instructions into machine language (0s and 1s.).

Example 1: Add Two Numbers

• MOV AL, 05 : Move value 5 into register AL

• MOV BL, 03 : Move value 3 into register BL

• ADD AL, BL : Add values in AL and BL (5 + 3)

Advantages:

 Compared to machine language, an assembly language is easier to


understand by humans.
 The code written in an assembly language is easier to edit.
 You can easily locate errors and fix them.

Disadvantages: it is require an assembler.


2. High-Level Language
High-level languages are programming languages that are used for
writing programs or software that can be understood by humans and computers.
High-level languages are easier to understand for humans because they use a lot
of symbols, letters to represent logic and instructions in a program.

Examples of Some High-Level Languages


 Python
 Java
 C++
 C
 JavaScript
Introduction to C Programming Language

C is a general-purpose, procedural programming language developed in the early 1972s by


Dennis Ritchie at Bell Labs.

History of the C programming language

Year Language Developer(s)


1960 ALGOL International Group
1963 CPL (Combined Programming Language) Cambridge & London
Universities
1967 BCPL (Basic Combined Programming Language) Martin Richards
1970 B Ken Thompson (Bell Labs)
1972 C Dennis Ritchie (Bell Labs), USA

Why Learn C?

 C is one of the most popular and foundational programming languages in the world.
 Learning C makes it easier to learn languages like Java, Python, C++, and C#, as many
share similar syntax.
 C helps you understand how computer memory and low-level operations
work(Controlling how data is stored in RAM).
 C is faster than many other high-level languages like Java or Python.
 It can be used in both applications and technologies(like games, text editors, and
databases.)
Features of C Language
1. Simplicity
o C has a simple syntax with a limited number of keywords and data types, making it easy to
learn and use.
2. Mid-level Language
o C combines the features of both high-level and low-level languages.
3. Portability
o C programs are portable, meaning code written on one system can be run on another with
minimal changes.
4. Modularity
o Code in C can be broken into functions and reused in different parts of the program or other
programs.
5. Structured Language
o C allows the use of functions, control structures (like if-else, loops), and decision-making
statements to create well-organized programs.
6. Extensibility
o New features or functionalities can be easily added to a C program without affecting the
existing code.

Applications of C programming

1. Operating Systems – Used to develop system software like Windows and UNIX.
2. Compilers – Helps build compilers for other programming languages.
3. Device Drivers – Used to write drivers for hardware devices.
4. Game Development – Provides high-performance code for game engines.
5. Database Systems – Used in creating database software like MySQL, Oracle, SQL server.
6. System Utilities – Creates utility programs like file managers and editors.
7. Scientific Computing – Used in simulations, calculations, and research tools.
Steps to Solve Problems (in Programming):

To solve a problem using programming, follow these general steps:

1. Understand the Problem


o Read and analyze the problem carefully.
o Identify inputs, processes, and expected outputs.
2. Plan the Solution
o Design an algorithm.
o Use tools like pseudocode or flowcharts.
3. Write the Code
o Translate the algorithm into a programming language.
4. Test the Program
o Run the program with different inputs to check correctness.
5. Debug if Needed
o Fix any logical or syntax errors.
6. Document and Maintain
o Add comments and documentation.
Algorithm
An algorithm is a step-by-step procedure to solve a problem.
Example:
Problem: Find the largest of two numbers.
Algorithm:
1. Start
2. Read two numbers A and B
3. If A > B, then print A is larger
4. Else print B is larger
5. Stop
2. Example Problem:
Check if a Number is Even or Odd
Algorithm (Step-by-step):
1. Start
2. Read the number (let's call it N)
3. Divide N by 2 and find the remainder
4. If the remainder is 0, then
o Print "Number is Even"
5. Else
o Print "Number is Odd"
6. Stop

What is Pseudocode?

Pseudocode is a simple, plain-language way to describe the steps or algorithm.

Example of Pseudocode
Problem:
Find the largest of two numbers.
Pseudocode:
START
Input number A
Input number B
IF A > B THEN
Print "A is larger"
ELSE
Print "B is larger"
END IF
STOP
What is a Flowchart?
A flowchart is a visual diagram that shows the steps of a process or algorithm using
different shapes and arrows. It helps us understand the flow of the logic clearly.
Flowchart Symbols
Various symbols represent different operations in a C Language Flowchart. Each symbol
plays a specific role:
1. Oval: Represents start and end points.

2. Rectangle: Indicates a processing step.

3. Diamond: Used for decision-making operations.

4. Parallelogram: Symbolizes input/output operations.

5. Arrow Lines: Shows the direction of flow between different operations.

6. Circle: Used to connect different parts of the flowchart

7. Hexagon : shows initialization, condition, and incrementation of loop variable

8. Document: Shows the data that is ready for printout


Example: Flow Chart

Given below is the flowchart for finding an average of three numbers ?


Program Development
Program development is the process of designing, writing, testing, and
maintaining the source code of computer programs. It involves several
stages:
1. Problem Analysis
This is the first and most important step. It involves understanding the
problem you want to solve, gathering requirements, and clearly defining
what the program should do.
Example:
Suppose you need to develop a program to calculate the average of three
numbers.
 What is the problem? Calculate the average.
 What input is required? Three numbers from the user.
 What is the expected output? The average value of the three
numbers.
2. Algorithm Design
Once the problem is understood, you plan the steps (or logic) required to
solve it. This plan is called an algorithm.
Example:
For the average calculator:
 Step 1: Read three numbers from the user.
 Step 2: Add the three numbers.
 Step 3: Divide the sum by 3 to get the average.
 Step 4: Display the average.
3. Coding
Translate the algorithm into a programming language. This means writing
the actual code.
4. Testing and Debugging
Run the program with different inputs to check if it works correctly. If
errors or bugs are found, identify and fix them.
5. Documentation
Write explanations about how the program works, how to use it, and any
important details. Good documentation helps others understand and
maintain the program.
6. Maintenance
After the program is delivered, it might need updates or improvements
based on user feedback or changing requirements.

Programming Environments:
A programming environment is the set of tools and software that
programmers use to write, test, and debug their code. Common
programming environments include:
 Text Editors: Simple tools for writing code (e.g., Notepad++, Sublime
Text).
 Integrated Development Environments (IDEs): Comprehensive
software that includes a code editor, compiler, debugger, and other
tools (e.g., Visual Studio, Eclipse, PyCharm).
 Compilers and Interpreters: Programs that translate source code
into machine code or directly execute the code.
Example: Cling (Interpreter), gcc (Compilers)
Basic Structure OF C Language:
Each C Program is consists of 6 main sections, these sections are named
as Documentation Section, Link Section, Definition Section, Global
Declaration Section, Main Function Section, Subprogram Section. You will
find a brief explanation about each section below.

1. Documentation Section:
The Documentation Section consists of a set of comment lines giving the
name of the Programmer, date, and other details about the program. The
documentation section helps anyone to get an overview of the program.
Comments may appear anywhere within a program. The text between
/* */ appears as a comment in C.
Example: /* This is a comment */
2. Link section or Preprocessor Directives or Header Files :
The Link Section refers to the part of a C program where header files are
included using the #include directive. These header files contain
declarations for functions, macros, constants, and data types that are part
of the C Standard Library or user-defined libraries.
Header files like <stdio.h>, <stdlib.h>, and <string.h> provide prototypes
for standard functions.

Example:
<stdio.h> : printf(), scanf()
<stdlib.h> : malloc() Note: For memory allocation.
<string.h> : strlen ().
<math.h> : The math.h header file contains declarations for mathematical
functions.

3. Definition Section
The Definition Section is the part of a C program where constants are
defined using the #define directive. These are typically written at the
beginning of the program, before the main() function.

4. Global Declaration:
The Global Declaration Section is the part of a C program where variables,
functions or structures are declared outside of all functions, typically above
the main() function. They are accessible to all functions and variables in the
program.
5. Main() Function
main() function is mandatory for any program and it includes two parts,
1. declaration part
2. executable part.
6. Subprograms:
In C programming, subprograms refer to functions or procedures that
perform a specific task.
Example:

/* Documentation Section
File : age.c
Author : You
Date: [Link]
Description : A program to calculate age based on the year of birth.
*/

// Link Section
#include <stdio.h>

// Definition Section
#define BORN 2000

// Global Declaration Section


int age(int current);

// Main() Function
int main(void)
{
// Declaration Part
int current = 2021;

// Executable Part
printf("Age: %d\n", age(current));

return 0;
}
// Subprograms Section (User-defined Function)
int age(int current) {
return current - BORN;
}
C Comments:
The comments in C are human-readable notes in the source code of a C
program used to make the program easier to read and understand. They are not
a part of the executable program by the compiler or an interpreter.
Two Types of Comments in C
1. Single-line Comments :
Single-line comments are used to comment out a single line of code or a part
of it. The single line comments in C start with two forward slashes (//), and
everything after the slashes on that line is considered a comment.
Syntax: // your comment here
Example:
#include <stdio.h>
int main()
{
// create integer variable
int age = 25;
// print the age variable
printf("Age: %d", age);
return 0;
}

2. Multi-line Comments:
Multi-line comments in C are used write comments that span more than one
line. They are generally used for longer descriptions or for commenting out
multiple lines of code. In C language, these comments begin with /* and end
with */. Everything between these markers is treated as a comment.
Syntax: /* your comment here*/
Example:
/*
Name: Anu
Date: 2-08-2025
Program name: Display Text
*/
#include <stdio.h>
int main()
{
printf("Welcome to GeeksforGeeks");
return 0;
}
C Hello World Program
The “Hello World” program is the first step towards learning any
programming language. It is also one of the simplest programs that is used to
introduce aspiring programmers to the programming language. It typically
outputs the text "Hello, World!" to the console screen.
Example:
// Header file for input output functions
#include <stdio.h>
// Main function: entry point for execution
int main()
{
// Writing print statement to print hello world
printf("Hello World");
return 0;
}
Keywords in C?
Keywords in C are reserved words that have a special meaning to the [Link]
cannot use them as names for variables, functions, or identifiers. All these words
are the 32 reserved keywords of c language. Keywords are predefined. These
reserved words have special meanings to the compiler.

int volatile void unsigned union typedef switch struct

for sizeof signed short auto while long register


if goto static float extern enum else double

do default const continue char case break return

Keyword Meaning (Simple Explanation)


int Used to declare an integer variable (whole numbers)
float Used to declare a variable that holds decimal numbers
char Used to declare a character (single letter)
if Starts a condition: "If this is true, do something..."
else What to do if the if condition is false
while Repeats code while a condition is true
for A loop that runs a specific number of times
return Sends a value back from a function
void Used for functions that return nothing
break Exits a loop or switch statement early
continue Skips to the next loop iteration
switch Selects one block of code to run from many options
case Defines a possible value in a switch statement
default The code that runs if no case matches
struct Groups different types of variables together
const Declares a variable as constant (cannot change)
C Identifiers
In this guide, you will learn about C identifiers. As the name suggests an identifier
in C is a unique name that is used to identify a variable, array, function, structure
etc.
Example:
int num =10; declaration, name “num” is an identifier for this int type variable.
Identifier must be unique so that it can identify an entity during the execution of
the program.
Rules for C identifiers
As the identifier is chosen by the programmer, there are certain rules in place to
remind programmer and to prevent execution of the program until these rules are
fulfilled.
Rules for naming identifiers in C

● The first letter of an identifier should be either alphabet or underscore.

● The alphabet can be either in uppercase or lowercase.

● The first identifier can not start with the digit.

● After the first letter identifier can have character, digit, underscore.

● Identifiers are case sensitive, uppercase and lowercase letters are distinct.

● Commas and blank space are invalid while naming an identifier.

● Maximum length of the identifier is 31 characters.

● Keywords can not be named as an identifier.

● Identifiers should be short, meaningful and easy to understand.


Valid Identifiers Invalid Identifiers Reason for Invalidity
Total 1x Begins with a digit
Sum char Reserved keyword
Average x+y Contains special character +
_x
_sum_
a_
Mark_Maths
X1

Keywords Identifiers
Keywords are predefined word that Identifiers are the values used to define
gets reserved for working program different programming items such as
that have special meaning and variables, integers, structures, unions and
cannot get used anywhere else. others and mostly have an alphabetic
character.
Specify the type/kind of entity. Identify the name of a particular entity.
It always starts with a lowercase First character can be a uppercase,
letter. lowercase letter or underscore.
A keyword should be in lower case An identifier can be in upper case or lower
and can only contains alphabetical case and can consist of alphabetical
characters. characters, digits and underscores.
They help to identify a specific They help to locate the name of the entity
property that exists within a that gets defined along with a keyword.
computer language.
int, char, if, while, do, class etc. Test, count1, high_speed, etc.
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the
variable can store like integer, character, floating, double, etc.
Example:
int number;

void
1. Primary (Basic) Data Types in C:

Data Size Description Range Example Format


Type (Bytes) Specifier
int 4 Stores integers –2,147,483,648 to int age = 25; %d or
2,147,483,647 %i
char 1 Stores a single –128 to 127 char grade = 'A'; %c
character
float 4 Stores single ~±3.4E–38 to ±3.4E+38 float pi = 3.14f; %f
precision decimal
numbers 6,7
double 8 Stores double ~±1.7E–308 to ±1.7E+308 double g = 9.81; %lf
precision decimal
numbers
void 0 Represents no N/A void display(); (none)
value / no return
unsigned 4 Stores only 0 to 4,294,967,295 unsigned int x = %u
int positive integers 100;
short int 2 Smaller range –32,768 to 32,767 short int s = 1000; %hd
than int
unsigned 2 Positive values 0 to 65,535 unsigned short int %hu
short int only (smaller u = 50000;
range)
long int 4 or 8 Larger range –2,147,483,648 to long int big = %ld
than int 2,147,483,647 (4B) or 1000000000;
±9,223,372,036,854,775,807
(8B)
Example:
#include <stdio.h>
void greet()
{
printf("Hello from a void function!\n");
}

int main()
{
int age = 25;
char grade = 'A';
float pi = 3.14f;
double gravity = 9.80665;
unsigned int items = 100;
short int temp = -300;
unsigned short int speed = 60000;
long int population = 1500000000L;

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


printf("Grade: %c \n", grade);
printf("Pi: %.2f \n", pi);
printf("Gravity: %lf \n", gravity);
printf("Items: %u \n", items);
printf("Temperature: %hd \n", temp);
printf("Speed: %hu \n", speed);
printf("Population: %ld \n", population);
greet(); // void function
return 0;
}
2. Derived data types:

Data Type Explanation Example Code Snippet


Array An array stores multiple elements of int arr[5] = {1, 2, 3, 4, 5};
the same data type. Size is determined
printf("%d", arr[0]);
by the type and number of elements.
Pointer A pointer is a variable that holds the int x = 10;
address of another variable.
int *ptr = &x;

printf("%d", *ptr);
Function A block of code that performs a specific #include <stdio.h>
task and can return a value.
// Function definition
int add(int a, int b)
{
return a + b;
}

int main()
{

// Function call
int result = add(5, 3);
printf("The sum is: %d", result);
return 0;
}
3. User-Defined Data Types :
Data Type Description Example
struct A structure groups different struct Person
data types into a single unit. {
Each member has its own int age;
memory. char name[20];
char address[100];
};

struct Person p = {30, "John","123 Main


St, Anytown"};
union A union groups different data union Data
types, but all members share {
the same memory. Only one int i;
member can hold data at a float f;
time. };
union Data d;
d.i = 10;
enum An enumeration defines a set #include <stdio.h>
of named integer constants. enum Day { Sun = 10, Mon = 20, Tue =
The default starts from 0, but 30, Wed = 40, Thu = 50, Fri = 60, Sat = 70
custom values can be set. };
int main() {
enum Day today = Wed;
printf("The value of today is: %d\n",
today);
return 0;
}
// Output: 40
I/O Statements in C
I/O statements are used to receive input from the user and display output
on the screen. These functions are part of the Standard Input/Output
(I/O) Library in the C language.
There are two types of I/O functions available:
1. Formatted I/O functions
a. printf() :
 The printf() function is used to display output on the screen.
 It can print text, numbers, and other data.
Example 1:
int x=10;
printf("The number is: %d\n", x);
b. scanf():
 The scanf() function is used to take input from the user.
 It can read integers, characters, strings, etc.
Note: It is used to get the memory address of a variable.
Example 1:
int age;
scanf("%d", &age); // User enters a number
printf("You entered: %d\n", age);
2. Unformatted I/O functions
1. getchar()
Reads a single character from standard input.
Example:
char ch;
ch = getchar(); // reads a single character
printf("Enter a character: %c",ch);
2. putchar()
Writes a single character to standard output.
Example:
putchar(ch); // prints the character
[Link]()
Reads a whole line (string) from input.
Example:
char name[100];
gets(name);
printf("Enter a string: %s", name);
4. puts()
 Outputs a string to the console followed by a newline.
Example:
puts("The message is:");
What is a Variable?
A variable is a name given to a memory location that stores data. It acts as
a container to store values that your program can use and manipulate.
Syntax:
datatype variable_name;
Example:
int a = 10;
Rules for Naming Variables in C

• A variable name must only contain letters, digits, and underscores.


• It must start with an alphabet or an underscore only. It cannot start
with a digit.
• No white space is allowed within the variable name.
• A variable name must not be any reservedwordor keyword.
• The name must be unique in the program.

Valid Variable Why Valid Invalid Why Invalid


Names Variable
Names
age Starts with a letter 1age Starts with a digit
_value Starts with an float Reserved keyword in
underscore C
total_sum Letters and my-variable Contains a hyphen -
underscore (invalid character)
marks123 Letters and digits @score Starts with @ (invalid
character)
StudentName Camel case, valid int Keyword in C
characters
x Single character, void Keyword in C
valid
sum1 Valid combination Total No white space is
allowed
C Variable Initialization:
Once we have declared or created the variable, then we can assign a value to it. This is
called variable definition.. It is done using assignment operator (=).

Example 1:

// variable declaration

int marks;

// variable definition

marks = 10;

Example 2:

NOTE: We can do declaration and definition in a single step too, like this
(recommended).

int num = 3;

Accessing Variables
The data stored inside a C variable can be easily accessed by using the variable's
name.
Example:
#include <stdio.h>
int main()
{
// create integer variable declared
int num = 3;
// Access the value stored in memory
printf("%d", num);
return 0;
}
Changing Stored Values
We can also update the value of a variable with a new value whenever needed by
using the assignment operator =.
Example:
#include <stdio.h>
int main()
{
// Create integer variable
int n = 3;
// Change the stored data
n = 22;
// Access the value stored in memory
printf("%d", n);
return 0;
}

Scope of Variables in C
We have told that a variable can be accessed anywhere once it is declared, but it
is partially true. A variable can be accessed using its name anywhere in a specific
region of the program called its scope.
Example:
// num cannot be accessed here
int main()
{
// num cannot be accessed here
{
// Variable declaration
int num;
}
// Cannot be accessed here either
return 0;
}
Constant variables:
In C programming, const is a keyword used to declare a variable as constant, meaning
its value cannot be changed after it is initialized.
Syntax:

Name of the
variable
Example:

const float PI = 3.14159;

Types of Constants:

1. Integer Constants
An integer constant in C is a fixed whole number value without a decimal point that
cannot be changed during program execution.
Example:
const int age = 25; // age is an integer constant with value 25
const int year = 2025; // year is an integer constant with value 2025
2. Character Constants:
Character constants are single characters enclosed in single quotes. They represent
individual characters like letters, digits, or symbols.
Example:
const char char_const = 'A';
3. Floating Constants
Floating-point constants represent real numbers and always include a decimal point.
Example:
const float PI = 3.14;
4. String Constants
String constants are sequences of characters enclosed in double quotes.
Example:
const char* MESSAGE = "Hello, World!";
Variables
There are two ways to classify variables

[Link] Variables

• Declared inside a function or block ({ }).


• Only accessible within that function or block.

Example:

#include <stdio.h>
void display()
{
int x = 10; // Local variable
printf("x = %d\n", x);
}
int main()
{
display();
// printf("%d", x); // ERROR: x is not accessible here
return 0;
}
2. Global Variables
• Declared outside of all functions (usually at the top of the file).
• Accessible by all functions in the same file (and even in other files
using extern).

Example:

#include <stdio.h>
int g = 5; // Global variable

void func()
{
printf("g = %d\n", g); // Accessible here
}
int main()
{
printf("g = %d\n", g); // Accessible here
func();
return 0;
}
Constant variables:
In C programming, const is a keyword used to declare a variable as constant,
meaning its value cannot be changed after it is initialized.
Syntax:

Name of the
variable

Example:

const float PI = 3.14159;


Types of Constants:

1. Integer Constants
An integer constant in C is a fixed whole number value without a decimal point
that cannot be changed during program execution.
Example:
const int age = 25; // age is an integer constant with value 25
const int year = 2025; // year is an integer constant with value 2025
2. Character Constants:
Character constants are single characters enclosed in single quotes. They represent
individual characters like letters, digits, or symbols.
Example:
const char char_const = 'A';
3. Floating Constants
Floating-point constants represent real numbers and always include a decimal
point.
Example:
const float PI = 3.14;

4. String Constants
String constants are sequences of characters enclosed in double quotes.
Example:
const char* MESSAGE = "Hello, World!";
Operators

An operator is a symbol that tells the compiler to perform a specific


operation on one or more operands (such as variables, constants).

Example:

Int a = 10, b = 5;
Int sum = a + b; // here '+' is an operator

Types of operators:

1. Arithmetic Operators:
An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc…
Operator Description Example
+ Addition 5 + 3 = 8

- Subtraction 5 - 3 = 2

* Multiplication 5 * 3 = 15

/ Division 6 / 3 = 2

% Modulus (remainder) 5 % 3 = 2

Example:
#include <stdio.h>
int main()
{
int a = 10, b = 3;
printf("sum = %d\n", a + b);
printf("sub = %d\n", a - b);
printf("mul = %d\n", a * b);
printf("divi = %d\n", a / b);
printf("mod = %d\n", a % b);
return 0;
}
Output:
sum = 13
sub = 7
mul = 30
divi = 3
mod = 1

2. Relational (Comparison) Operators

Used to compare values. Result is either 1 (true) or 0 (false).

Operator Description Example


== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal a >= b
<= Less than or equal a <= b

Example:
#include <stdio.h>
int main()
{
int x = 5, y = 10;
printf("x == y: %d\n", x == y);
printf("x != y: %d\n", x != y);
printf("x > y: %d\n", x > y);
printf("x < y: %d\n", x < y);
printf("x < y: %d\n", x <= y);
printf("x < y: %d\n", x >=y);
return 0;
}
Output:
x == y :0
x != y :1
x>y :0
x<y :1
x<y :1
x<y :0
3. Logical Operators

Used to combine multiple conditions.

Operator Meaning Example


&& Logical AND. If c = 5 and d = 2 then, expression
True only if all operands ((c==5) && (d>5)) equals to 0.
are true
|| Logical OR. If c = 5 and d = 2 then, expression
True only if either one ((c==5) || (d>5)) equals to 1.
operand is true
! Logical NOT. If c = 5 then, expression !(c==5) equals
True only if the operand to 0.
is 0
Example:
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);
result = (a == b) || (c < b);
printf("(a == b) || (c < b) is %d \n", result);
result = !(a = b);
printf("!(a != b) is %d \n", result);
return 0;
}
Output:
(a == b) && (c > b) is 1
(a == b) || (c < b) is 1
!(a = b) is 0

4. Assignment Operators:
An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =
Syntax:
variable = value (or) variable (or) expression
1. variable = value;
example:
int a;
a = 10; // Assigns the value 10 to variable 'a'
2. variable = variable;
example:
int a = 5;
int b;
b = a; // Assigns the value of 'a' (which is 5) to 'b'
3. variable = expression;
example:
int a = 4, b = 6;
int result;
result = a + b; // result = 4 + 6 → 10
Operator Description Example
= Assign a = 10
+= Add and assign a += 5 → a = a + 5
-= Subtract and assign a -= 5 → a=a-5
*= Multiply and assign a *= 5 → a=a*5
/= Divide and assign a /= 5 → a=a/5
%= Modulus and assign a %= 5 → a=a%5

Example:
#include <stdio.h>
int main()
{
int a = 10;
printf("Initial value of a: %d\n", a);
a += 5;
printf("After a += 5: %d\n", a); // a = a + 5 → 15
a -= 5;
printf("After a -= 5: %d\n", a); // a = a - 5 → 10
a *= 5;
printf("After a *= 5: %d\n", a); // a = a * 5 → 50
a /= 5;
printf("After a /= 5: %d\n", a); // a = a / 5 → 10
a %= 5;
printf("After a %= 5: %d\n", a); // a = a % 5 → 0
return 0;
}
4. Bitwise Operators in C
 Bitwise operators perform manipulations of data at the bit level.
 These operators also perform the shifting of bits from right to left.
 Bitwise operators are not applied to float or double, long double, void,
etc.
Operator Description Ex: Explanation
& Bitwise AND 5&9 0101 & 1001 = 0001 → 1

| | Bitwise 13
OR
^ Bitwise Exclusive OR 5 ^ 9 0101 ^ 1001 = 1100 → 12
(XOR)
~ One's complement ~5 ~0101 = 0110 (in 4 bits) → -6
(NOT)
>> Shift right 9 >> 1 1001 >> 1 = 0100 → 4
<< Shift left 5 << 1 0101 << 1 = 1010 → 10
1. & Bitwise AND:

Compares each bit of two numbers and returns 1 only if both bits are 1.

Example:

5&9
= 0101 & 1001
= 0001 → 1
2. Bitwise OR: 5 | 9

Binary:
0101 (5)
| 1001 (9)
= 1101 → 13
3. Bitwise XOR: 5 ^ 9
Binary:

0101 (5)
^ 1001 (9)
= 1100 → 12
1. One's Complement (~)

The One's Complement of a number flips all the bits:

 1 becomes 0,
 0 becomes 1.

2. 2’s Complement

1. Invert all bits (change 0 to 1 and 1 to 0). ← This is the one's


complement.
2. Add 1 to the result of step 2.

1. Left Shift by 1 (a << 1) :

Example: 16 - 00010000
int a = 16;

int result = a << 1 Formula:


result=32 Number * 2n

[Link] Shift by 1 (a >> 1)

Example: 16 - 00010000

int a = 16;

int result = a >> 1 Formula:


result=8 Number / 2n
[Link] Operator (?) or Conditional Operator:

The ternary operator, also known as the conditional operator in the C language
can be used for statements of the form if-then-else.

Syntax :

(Expression1) ? Expression2 : Expression3;

Here is how it works:

 The question mark ? in the syntax represents the if part.


 If (expression 1) returns true then the (expression 2) is executed.
 If (expression 1) returns false then the expression on the right side
of: i.e. (expression 3) is executed.

Example:
int a = 10, b = 20;
int max = (a > b) ? a : b; // if a>b then max=a else max=b
printf("Maximum = %d\n", max);

6. Special Operator

Operator Name Description Example


sizeof Sizeof Returns the size (in bytes) of a sizeof(int)
operator variable or data type.
& Address-of Returns the address of a variable. &x
operator
* Pointer Access value at a given address *ptr
operator (pointer dereferencing).
, Comma Evaluates multiple expressions. x=(a=3, a+2);
operator
-> Arrow Used to access members of a ptr->member
operator structure through a pointer.
. Dot operator Access structure members directly. [Link]
7. Increment and Decrement Operators
In the C programming language, increment (++) and decrement (- -) operators
can be used to increase and decrease the numerical values by 1.
[Link]- increment
(e.g., ++x, --x) to change the value before it is used.
2. post- increment
(e.g., x++, x--) to change the value after it is used.

Example 1:
int x = 5, y = 5;
printf("Post-Increment = %d\n", x++); // Post-Increment : 6
Example 2:
int a = 5, b = 5;
printf("Prefix Increment: ++a = %d\n", ++a); // Post-Increment : 6
Precedence
When an expression has multiple operators, precedence determines the
order in which operators are evaluated.
Example:
int x = 10 + 5 * 2;
• Here * has higher precedence than +.
• So expression is evaluated as 10 + (5 * 2) = 10 + 10 = 20.
Associativity
When operators have the same precedence, associativity decides the
direction of evaluation (left-to-right or right-to-left).
Example – Left to Right Associativity
int x = (20 / 5) * 2;

You might also like