0% found this document useful (0 votes)
29 views23 pages

Unit 1 CPS

Uploaded by

mtmsr2001.1
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)
29 views23 pages

Unit 1 CPS

Uploaded by

mtmsr2001.1
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
You are on page 1/ 23

Flowchart with Examples

A flowchart is a visual representation of the sequence of steps and decisions needed to


perform a process. Each step in the process is represented by a symbol, and arrows
connect these symbols to show the flow of the process. Flowcharts are used to design
and document complex processes and programs in an easy-to-understand manner.
Common Flowchart Symbols
1. Oval (Terminator):
o Purpose: Represents the start and end points of a flowchart.
o Example Label: "Start" or "End"
2. Rectangle (Process):
o Purpose: Represents a process, action, or operation.
o Example Label: "Add two numbers", "Print report"
3. Diamond (Decision):
o Purpose: Represents a decision point where the flow can branch based
on a Yes/No or True/False condition.
o Example Label: "Is X > 0?", "Is the password correct?"
4. Parallelogram (Input/Output):
o Purpose: Represents input to or output from a process.
o Example Label: "Enter Name", "Display Result"
5. Arrow (Flowline):
o Purpose: Represents the direction of flow from one step to the next.
6. Circle (Connector):
o Purpose: Represents a connection point when the flowchart continues in
another section.
o Example Label: "A" (to connect with another "A")
Example 1: Flowchart for a Simple Calculator
Let's create a flowchart for a simple calculator program that adds two numbers.
Steps:
1. Start the program.
2. Input the first number.
3. Input the second number.
4. Add the two numbers.
5. Display the result.
6. End the program.
Flowchart:
Program Development Environments
Program development environments, often referred to as Integrated Development
Environments (IDEs), are software applications that provide comprehensive facilities to
computer programmers for software development. They typically combine multiple
tools and features in a single user interface, which simplifies and streamlines the process
of writing, testing, and debugging code.
Components of Program Development Environments
1. Editor:
o The core component where developers write and edit their code. Modern
editors often provide syntax highlighting, code completion, and error
detection.
o Examples: Sublime Text, Visual Studio Code, Atom.
2. Compiler/Interpreter:
o Converts the source code written in a high-level language into machine
code or bytecode that can be executed by a computer.
o Examples: GCC (GNU Compiler Collection), Clang, Python Interpreter.
3. Debugger:
o A tool that helps in testing and debugging code by allowing developers
to step through code execution, set breakpoints, inspect variables, and
analyze the call stack.
o Examples: GDB (GNU Debugger), LLDB, Visual Studio Debugger.
4. Build Automation Tools:
o Automates the process of compiling code, running tests, and packaging
software into deployable formats.
o Examples: Make, CMake, Gradle, Maven.
5. Version Control Integration:
o Integrates with version control systems to manage changes to the
codebase, track history, and collaborate with other developers.
o Examples: Git, Subversion, Mercurial.
6. Integrated Terminal/Command-Line Interface (CLI):
o Provides direct access to the command line within the development
environment, allowing developers to run commands, scripts, and tools
without leaving the IDE.
o Examples: Terminal in Visual Studio Code, Terminal in IntelliJ IDEA.
7. Project Management Features:
o Tools for managing and organizing the structure of a software project,
including file and folder hierarchies, build configurations, and
dependencies.
o Examples: Project Explorer in Eclipse, Solution Explorer in Visual Studio.
8. Package Manager Integration:
o Tools to manage libraries and dependencies, allowing developers to
easily install, update, and manage third-party packages.
o Examples: npm (Node Package Manager), pip (Python Package Installer),
NuGet.
9. Testing Frameworks:
o Integration with testing frameworks to write and run tests, ensuring code
correctness and reliability.
o Examples: JUnit (Java), pytest (Python), NUnit (.NET).
10. Refactoring Tools:
o Tools that assist in restructuring existing code without changing its external
behavior, improving code readability, and reducing complexity.
o Examples: Rename, Extract Method, Inline Variable.
11. Profiling and Performance Analysis:
o Tools to analyze the performance of the code, including memory usage,
CPU usage, and execution time, helping to identify bottlenecks.
o Examples: VisualVM, Valgrind, Perf.
12. Documentation and Help:
o Built-in access to language documentation, libraries, and APIs, as well as
tutorials and code snippets to assist developers.
o Examples: Quick Documentation in IntelliJ IDEA, IntelliSense in Visual
Studio.
Benefits of Using an IDE
 Increased Productivity: By providing a suite of tools in a single environment, IDEs
streamline development tasks, reducing context-switching and setup time.
 Error Reduction: Features like syntax highlighting, real-time error detection, and
debugging tools help catch errors early in the development process.
 Better Code Management: Version control integration, project management
features, and refactoring tools help maintain code quality and organization.
 Collaboration: IDEs often integrate with collaboration tools and platforms,
making it easier to work on projects with others.
Summary
Program development environments, or IDEs, are essential tools for modern software
development, providing everything a developer needs to write, test, and debug code
efficiently. With a range of features that cater to different programming languages and
development needs, IDEs are critical in enhancing productivity and ensuring code
quality.
Introduction to Programming: Programming Languages and Generations

Programming languages are formal languages used to communicate instructions to a


computer. These languages allow developers to write programs that perform specific
tasks, solve problems, or control the behavior of a computer. Over time, programming
languages have evolved through various generations, each offering different levels of
abstraction and capabilities.
1. What is a Programming Language?
A programming language is a set of syntax rules and semantic guidelines that dictate
how to write code to perform tasks on a computer. The code written in a programming
language is often referred to as source code. This source code is typically translated
into machine code, which the computer's processor can execute directly.
2. Characteristics of Programming Languages
 Syntax: The rules that define the structure and form of valid statements in the
language.
 Semantics: The meaning of the statements within the language.
 Abstraction: The level at which the language abstracts the underlying hardware,
making it easier or more complex to use.
 Type System: The way a language handles and categorizes data types, such as
integers, strings, and objects.
3. Generations of Programming Languages
Programming languages are generally categorized into five generations, each
representing a significant step in the evolution of how humans interact with computers.
First Generation (1GL): Machine Language
 Description: The lowest-level programming language, consisting of binary code
(0s and 1s) that the computer's central processing unit (CPU) can execute
directly.
 Features:
o Directly controls hardware.
o Extremely fast execution but difficult for humans to read, write, and
debug.
 Example: 10110100 00000001 (binary instructions specific to a CPU architecture).
Second Generation (2GL): Assembly Language
 Description: A low-level programming language that uses mnemonic codes to
represent machine-level instructions. It provides a small level of abstraction over
machine code.
 Features:
o Each assembly language instruction corresponds to a specific machine
code instruction.
o Easier to write than machine language but still closely tied to the
hardware.
 Example: MOV AL, 1 (an assembly instruction to move the value 1 into a register).
 Tools: Assembler, which converts assembly code into machine code.
Third Generation (3GL): High-Level Languages
 Description: These languages provide a higher level of abstraction from the
hardware, making them easier to learn and use than assembly or machine
languages.
 Features:
o More human-readable and closer to natural language.
o Portable across different types of hardware.
o Requires a compiler or interpreter to convert into machine code.
 Examples:
o C: A general-purpose language widely used for system and application
software.
o Java: A high-level, object-oriented language known for its portability
("write once, run anywhere").
o Python: A high-level, interpreted language known for its simplicity and
readability.
Fourth Generation (4GL): Very High-Level Languages
 Description: These languages are designed to be closer to human language,
focusing on reducing the complexity of programming and improving
productivity.
 Features:
o Often used for database querying, report generation, and other high-level
tasks.
o Require less coding and are more declarative in nature.
 Examples:
o SQL: A language used for managing and querying databases.
o MATLAB: A language and environment for numerical computing and
algorithm development.
o RPG: A language used in business applications for generating reports.
Fifth Generation (5GL): Natural Languages and AI-Based Languages
 Description: These languages are designed to solve problems by using
constraints given to the program, rather than through explicit instructions. They
often involve natural language processing or artificial intelligence.
 Features:
o Aim to make the computer understand and respond to natural human
languages.
o Often used in expert systems, neural networks, and other AI applications.
 Examples:
o Prolog: A language used in artificial intelligence and computational
linguistics.
o LISP: A language used for AI research, known for its powerful symbolic
expression capabilities.
4. Choosing a Programming Language
The choice of programming language depends on several factors, including:
 Project Requirements: The specific tasks and goals of the project.
 Performance: The need for speed and efficiency.
 Platform: The operating system or hardware for which the software is being
developed.
 Developer Skill: The experience and familiarity of the developer with the
language.
 Community and Ecosystem: The availability of libraries, frameworks, and
community support.
Summary
Programming languages have evolved significantly over time, moving from machine-
level code (1GL) to high-level, human-readable languages (3GL) and beyond. The
development of programming languages reflects the ongoing effort to make computer
programming more accessible, efficient, and powerful. Today, programmers have a
wide variety of languages to choose from, each suited to different types of tasks and
levels of abstraction.
Introduction to C Programming Language
C is a general-purpose, procedural programming language developed in the early
1970s by Dennis Ritchie at Bell Labs. It is one of the most widely used programming
languages and has had a significant influence on many other languages, including
C++, Java, and Python.
Key Features of C:
1. Low-Level Access:
o C provides direct access to memory through the use of pointers, which
makes it suitable for system programming (like operating system or
embedded system development).
2. Rich Library Support:
o C has a rich set of built-in functions and libraries that can be used for
various tasks, from mathematical computations to input/output
operations.
3. Efficiency:
o Programs written in C are typically fast and efficient. This is why C is often
used in situations where performance is critical, such as in game
development or real-time systems.
4. Portability:
o C programs can be easily transferred from one machine to another,
making it a highly portable language.
5. Structured Language:
o C supports structured programming, which allows developers to write
clear, understandable, and maintainable code by dividing programs into
smaller functions.
Structure of C Program
The structure of a C program consists of several key components, each serving a
specific purpose in the development and execution of the code. Here's a breakdown
of the typical structure:
1. Documentation Section
 Comments: This section includes comments that describe the program's purpose,
author, date, and other relevant information. Comments are ignored by the
compiler.
 Single-line comment: // This is a single-line comment
 Multi-line comment:
/*
This is a multi-line comment
spanning multiple lines
*/
2. Preprocessor Directives
 Purpose: Instructions to the preprocessor, which is a program that processes the
source code before compilation.
 Common Directives:
o #include: Includes header files containing standard library functions (e.g.,
#include <stdio.h>).
o #define: Defines constants or macros (e.g., #define PI 3.14).
#include <stdio.h>
#define MAX 100
3. Global Declarations
 Purpose: Declarations of global variables and function prototypes that can be
used throughout the program.
 Example:
int globalVar = 10; // Global variable declaration

void someFunction(); // Function prototype


4. main() Function
 Purpose: Every C program must have a main() function, which is the entry point
of the program. The execution starts here.
 Structure:
int main() {
// Local variable declarations
// Statements
return 0; // Return value to the operating system
}
 Components:
o Return Type: Typically int, indicating the function returns an integer value.
o Function Name: main.
o Body: Enclosed within {}, containing the program's logic.
o Return Statement: Usually return 0;, indicating successful execution.
5. Local Declarations
 Purpose: Variables declared within the main() function or any other functions are
local to that function.
 Example:
int main() {
int localVar = 5; // Local variable declaration
}
6. Executable Statements
 Purpose: The actual instructions that the program executes, such as calculations,
function calls, and input/output operations.
 Example:
printf("Hello, World!\n");
7. User-defined Functions
 Purpose: Additional functions created by the programmer to perform specific
tasks, making the program more modular and easier to manage.
 Structure:
void someFunction() {
// Function body
}
8. Return Statement
 Purpose: Ends the main() function and returns control to the operating system.
The value returned is typically an integer, with 0 representing successful
execution.
 Example:
return 0;
Example of a Complete C Program:
#include <stdio.h> // Preprocessor directive
// Global declaration
int globalVar = 10;
int main() { // Main function
int localVar = 5; // Local variable declaration

void greet(); // Function declaration

greet(); // Executable statement - function call


printf("The value of localVar is: %d\n", localVar); // Output statement
return 0; // Return statement
}
void greet() { // User-defined function or other functions
printf("Hello, World!\n");
}
Breakdown of the Example:
 Preprocessor Directive: Includes the standard I/O header file.
 Global Declaration: Declares a global variable globalVar.
 User-defined Function: greet() function prints "Hello, World!".
 main() Function: Declares a local variable, calls the greet() function, prints the
value of localVar, and returns 0.
This structure provides a clear, organized approach to writing C programs, making them
easier to understand, debug, and maintain.
Keywords in C Language

In C programming, keywords are reserved words that have a special meaning and
purpose in the language. These keywords cannot be used as identifiers (like variable
names, function names, etc.). Here's a list of commonly used keywords in C:
1. auto - Declares automatic variables.
2. break - Exits from a loop or a switch statement.
3. case - Used in switch statements to define individual cases.
4. char - Declares a character variable.
5. const - Declares a constant value that cannot be changed.
6. continue - Skips the remaining code in the current iteration of a loop and jumps
to the next iteration.
7. default - Specifies the default case in a switch statement.
8. do - Used in do-while loops, which execute at least once.
9. double - Declares a double-precision floating-point variable.
10. else - Used with if to execute a block of code when the condition is false.
11. enum - Defines an enumeration, a set of named integer constants.
12. extern - Declares a variable or function as external.
13. float - Declares a floating-point variable.
14. for - Used for loop iteration.
15. goto - Jumps to a labeled statement within a function.
16. if - Used for conditional execution of code.
17. int - Declares an integer variable.
18. long - Declares a long integer variable.
19. register - Suggests that the variable be stored in a CPU register.
20. return - Exits from a function and optionally returns a value.
21. short - Declares a short integer variable.
22. signed - Specifies a signed modifier for integer types.
23. sizeof - Returns the size of a data type or variable.
24. static - Declares a static variable or function with internal linkage.
25. struct - Defines a structure, a user-defined data type.
26. switch - Allows a variable to be tested against a list of values.
27. typedef - Defines a new name (alias) for an existing data type.
28. union - Defines a union, a data structure that can hold different data types in the
same memory location.
29. unsigned - Specifies an unsigned modifier for integer types.
30. void - Specifies that a function returns no value or declares a pointer to an
unknown data type.
31. volatile - Indicates that a variable may be changed unexpectedly.
32. while - Used for loop iteration as long as a condition is true.
These keywords form the foundation of C programming and are integral to writing C
code.
Identifiers in C Language
In C programming, identifiers are names used to identify variables, functions, arrays,
and other user-defined items. Identifiers allow you to name and refer to these elements
in your code. Here are the key points regarding identifiers in C:
Rules for Naming Identifiers:
1. Character Set:
o Identifiers must begin with a letter (uppercase or lowercase) or an
underscore (_).
o The subsequent characters can be letters, digits, or underscores.
o Example: sum, _counter, var1.
2. Case Sensitivity:
o C is case-sensitive, meaning that variable, Variable, and VARIABLE are all
different identifiers.
3. Length:
o Identifiers can be of any length, but only the first 31 characters are
typically considered significant by most compilers.
4. No Reserved Words:
o Identifiers cannot be the same as C keywords (like int, return, while, etc.)
because keywords are reserved for specific purposes in the language.
5. No Special Characters:
o Identifiers cannot contain special characters like @, #, !, -, etc. The only
special character allowed is the underscore (_).
Examples of Valid Identifiers:
 totalSum
 _index
 counter1
 average_value
Examples of Invalid Identifiers:
 2ndVariable (starts with a digit)
 total-sum (contains a hyphen)
 float (a reserved keyword)
Best Practices:
 Meaningful Names: Choose identifiers that describe the purpose of the variable
or function (e.g., totalSum for a variable holding the sum).
 Use of Underscores: When using multiple words, you can separate them with
underscores for readability (e.g., total_sum, max_value).
 Avoid Starting with Underscore: Although allowed, starting identifiers with an
underscore is generally discouraged because identifiers that begin with an
underscore followed by a capital letter, or identifiers that start with two
underscores, are reserved for the implementation (e.g., in libraries or system
headers).
By following these rules and best practices, you can write clear and maintainable C
code.
Data Types in C Language
In C programming, data types define the type of data that can be stored in a variable,
as well as the operations that can be performed on that data. C has a rich set of data
types that can be categorized into several groups:
1. Basic Data Types
 int:
o Used to store integers (whole numbers).
o Size: Typically 4 bytes.
o Example: int count = 10;
 float:
o Used to store floating-point numbers (numbers with a decimal point).
o Size: Typically 4 bytes.
o Example: float temperature = 36.5;
 double:
o Used to store double-precision floating-point numbers (more precision
than float).
o Size: Typically 8 bytes.
o Example: double area = 9.6789234;
 char:
o Used to store a single character.
o Size: 1 byte.
o Example: char grade = 'A';
 void:
o Represents the absence of type. Commonly used for functions that do not
return a value.
o Example: void function_name() { }
2. Derived Data Types
 Arrays:
o A collection of elements of the same type.
o Example: int numbers[10]; (an array of 10 integers)
 Pointers:
o Variables that store the address of another variable.
o Example: int *ptr; (pointer to an integer)
 Functions:
In C, functions are blocks of code that perform a specific task, which can be
called from other parts of the program. Functions help organize code, improve
readability, and promote reusability.
o Functions help in breaking down complex problems into simpler pieces.
o They make the code more modular and easier to understand.
o Functions in C can be recursive, calling themselves to solve problems.
 Strings:
In C, strings are arrays of characters terminated by a null character ('\0'). Since C
does not have a dedicated string data type, strings are handled as arrays of
char.
o Strings in C are null-terminated character arrays.
o Use functions from <string.h> for string manipulation.
o Handle strings carefully to avoid common pitfalls like buffer overflows.
3. User Defined Data Types

 Structures (struct):
o A collection of variables of different data types under a single name.
o Example:
struct Person {
char name[50];
int age;
float height;
};
 Unions (union):
o Similar to structures, but all members share the same memory location.
o Example:
union Data {
int i;
float f;
char str[20];
};
 Enumerations (enum):
o A user-defined type that consists of named integer constants.
o Example:
enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
 Typedef (typedef):
The typedef keyword in C is used to create new type names (aliases) for existing
data types. This can make complex data types easier to work with, improve
code readability, and provide a more meaningful way to use certain types in a
program.
o ‘typedef’ does not create new data types; it only creates aliases.
o It can greatly improve code clarity and maintainability, especially when
working with complex or frequently used types.
o It's a common practice in C programming, especially when defining
structures, unions, and function pointers.
o Syntax: The general syntax for using typedef is:
typedef existing_type new_type_name;
Examples:
typedef unsigned long ulong

4. Modifiers
Modifiers are used with basic data types to alter the size or range of the data type.
 short:
o Used to declare short integers.
o Example: short int x;
 long:
o Used to declare long integers.
o Example: long int x;
 signed:
o Default modifier for int, char, and other types (can store both positive and
negative values).
o Example: signed int x;
 unsigned:
o Used to declare unsigned integers (can only store positive values).
o Example: unsigned int y;
Summary of Basic Data Types with Size (Typical):
 char - 1 byte
 int - 4 bytes
 float - 4 bytes
 double - 8 bytes
 void - No storage
Choosing the Right Data Type:
 Efficiency: Choose the smallest data type that can hold the value to save
memory.
 Precision: Use double for high precision floating-point operations.
 Boolean: Use _Bool or int (with 0 and 1) for true/false values.
 Complexity: Use structures for complex data that involves multiple variables of
different types.
By understanding these data types and their modifiers, you can write more efficient
and effective C programs.
Constants
In C, a constant refers to a value that does not change during the execution of a
program. Constants are used to represent fixed values, such as numbers, characters, or
strings. There are several types of constants in C:
1. Integer Constants
These are whole numbers without any fractional or decimal part. They can be positive
or negative.
 Decimal Constants: Base 10 (e.g., 123, -456)
 Octal Constants: Base 8, prefixed by 0 (e.g., 012, 077)
 Hexadecimal Constants: Base 16, prefixed by 0x or 0X (e.g., 0x1A, 0XFF)
2. Floating-point Constants
These represent real numbers with a fractional part. They can be expressed in either
standard decimal or scientific notation.
 Decimal Notation: (e.g., 3.14, -0.001)
 Exponential Notation: (e.g., 1.23e4 for 1.23 × 10^4)
3. Character Constants
A single character enclosed in single quotes (e.g., 'A', '9', '\n').
 Character constants have a type of int in C, and their value is the ASCII value of
the character.
4. String Constants (String Literals)
A sequence of characters enclosed in double quotes (e.g., "Hello, World!", "C
programming").
 Strings are stored as arrays of characters terminated by a null character '\0'.
5. Enumeration Constants
Defined using the enum keyword, they assign names to integral constants, making the
code more readable.
enum Color { RED, GREEN, BLUE };
6. Defined Constants
These are constants defined using the #define preprocessor directive. These are also
called macro constants.
#define PI 3.14159
#define MAX_SIZE 100
Using const Keyword
You can also declare a variable as constant using the const keyword, which prevents its
value from being modified after initialization.
const int max_attempts = 5;
const float gravity = 9.81;
I/O Statements
In C, Input/Output (I/O) statements are used to handle data input from the user
(keyboard) and output to the console (screen). The standard library <stdio.h> provides
functions for performing input and output operations.
Common I/O Functions in C
1. printf: Outputs formatted text to the console.
2. scanf: Reads formatted input from the keyboard.
3. gets/fgets: Reads a string from the input.
4. puts: Outputs a string to the console.
5. putchar/getchar: Reads or writes a single character.
Details of Common I/O Functions
1. printf Function
 Usage: Outputs formatted data to the console.
 Syntax:
printf("format_string", argument_list);
 Example:
printf("Hello, %s! You are %d years old.\n", "Alice", 25);
 Format Specifiers:
o %d or %i: Integer
o %f: Floating-point
o %c: Character
o %s: String
o %x/%X: Hexadecimal representation of an integer
o %o: Octal representation of an integer
2. scanf Function
 Usage: Reads formatted input from the console.
 Syntax:
scanf("format_string", &variable);
 Example:
int age;
printf("Enter your age: ");
scanf("%d", &age);
 Important: Use the & (address-of) operator before variables except when
reading a string.
3. gets and fgets Functions
 Usage: Read an entire line of text input.
 Syntax:
o gets:
gets(string_variable);
Note: gets is unsafe and has been deprecated due to potential buffer
overflow vulnerabilities. Use fgets instead.
o fgets:
fgets(string_variable, size, stdin);
 Example:
char name[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
4. puts Function
 Usage: Outputs a string to the console, followed by a newline character.
 Syntax:
puts(string_variable);
 Example:
char message[] = "Hello, World!";
puts(message);
5. putchar and getchar Functions
 putchar:
o Usage: Writes a single character to the console.
o Syntax:
putchar(character);
o Example:
putchar('A');
 getchar:
o Usage: Reads a single character from the console.
o Syntax:
char ch = getchar();
o Example:
printf("Enter a character: ");
char c = getchar();
printf("You entered: %c\n", c);
Example Program Using I/O Functions
Here is a simple example demonstrating the usage of printf, scanf, puts, and fgets:

#include <stdio.h>
int main() {
char name[50];
int age;

printf("Enter your name: ");


fgets(name, sizeof(name), stdin); // Reading string input safely

printf("Enter your age: ");


scanf("%d", &age); // Reading integer input

printf("Hello, %s", name);


printf("You are %d years old.\n", age);

return 0;
}
Operators
In C, operators are special symbols or keywords that perform operations on one or more
operands (variables, constants, or expressions). Operators in C can be categorized into
several types based on their functionality.
Types of Operators in C
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Increment and Decrement Operators
7. Conditional (Ternary) Operator
8. Comma Operator
9. Sizeof Operator
10. Type Cast Operator
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a % b
 Example:
int a = 10, b = 3;
int sum = a + b; // 13
int remainder = a % b; // 1
2. Relational Operators
Relational operators are used to compare two values. They return either true (non-zero)
or false (zero).
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
 Example:
int a = 5, b = 8;
if (a < b) {
printf("a is less than b");
}
3. Logical Operators
Logical operators are used to combine two or more conditions or expressions.
Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a
 Example:
int a = 1, b = 0;
if (a && !b) {
printf("Condition is true");
}
4. Bitwise Operators
Bitwise operators perform operations on the binary representation of data.
Operator Description Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR (exclusive OR) a^b
~ Bitwise NOT (one's complement) ~a
<< Left shift a << 2
>> Right shift a >> 2
 Example:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int c = a & b; // Binary AND: 0001 (Decimal: 1)
int d = a << 1; // Left shift: 1010 (Decimal: 10)
5. Assignment Operators
Assignment operators assign values to variables.
Operator Description Example
= Simple assignment a=b
+= Add and assign a += b
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
&= Bitwise AND and assign a &= b
` =` Bitwise OR and assign
^= Bitwise XOR and assign a ^= b
<<= Left shift and assign a <<= 2
>>= Right shift and assign a >>= 2
 Example:
int a = 10;
a += 5; // Equivalent to a = a + 5

6. Increment and Decrement Operators


These operators are used to increase or decrease the value of a variable by 1.
Operator Description Example
++ Increment ++a or a++
-- Decrement --a or a--
 Example:
int a = 5;
a++; // Post-increment: a becomes 6
++a; // Pre-increment: a becomes 7
7. Conditional (Ternary) Operator
The ternary operator (? :) is a shorthand for an if-else statement.
 Syntax: condition ? expression_if_true : expression_if_false;
 Example:
int a = 5, b = 10;
int max = (a > b) ? a : b; // max is assigned the value of b
8. Comma Operator
The comma operator (,) allows multiple expressions to be evaluated in a single
statement, with only the rightmost expression's value being used.
 Example:
int a, b;
a = (b = 3, b + 2); // b is assigned 3, and a is assigned 5
9. sizeof Operator
The sizeof operator returns the size, in bytes, of its operand (a variable or data type).
 Syntax: sizeof(variable or data_type);
 Example:
int a = 5;
printf("Size of a: %zu bytes\n", sizeof(a));
10. Type Cast Operator
Type casting is used to convert a variable from one data type to another.
 Syntax: (type) expression
 Example:
double num = 5.8;
int n = (int) num; // n becomes 5, the integer part of num
Operator Precedence and Associativity
In C, operator precedence and associativity determine the order in which operators
are evaluated in expressions. Understanding these rules is crucial to ensure that
expressions are evaluated as intended.
Operator Precedence
Operator precedence defines the order in which operators are evaluated in an
expression. Operators with higher precedence are evaluated before operators with
lower precedence.
Associativity
Associativity defines the order in which operators of the same precedence level are
evaluated. It can be either left-to-right or right-to-left.
Table of Operator Precedence and Associativity in C
Below is a table showing the operators, their precedence (from highest to lowest), and
their associativity:
Precedence
Operators Description Associativity
Level
Parentheses, Array subscript, Member
1 () [] -> . Left-to-right
access
++ -- Post-increment, Post-decrement
Unary plus, Unary minus, Logical NOT,
2 +-!~ Right-to-left
Bitwise NOT
++ -- Pre-increment, Pre-decrement
*& Dereference, Address of
sizeof Size of
(type) Type cast
3 */% Multiplication, Division, Modulus Left-to-right
4 +- Addition, Subtraction Left-to-right
5 << >> Bitwise Shift Left, Bitwise Shift Right Left-to-right
Relational Less than, Less than or
6 < <= > >= equal to, Greater than, Greater than Left-to-right
or equal to
7 == != Equality, Inequality Left-to-right
8 & Bitwise AND Left-to-right
9 ^ Bitwise XOR Left-to-right
10 ` ` Bitwise OR
11 && Logical AND Left-to-right
12 ` `
13 ?: Ternary Conditional Right-to-left
= += -= *= /= %= Assignment
14 =`
<<= >>= &= ^= ` operators
15 , Comma (sequential evaluation) Left-to-right
Examples
1. Operator Precedence
Consider the following expression:
int x = 5 + 3 * 2;
 Multiplication (*) has higher precedence than addition (+), so it is evaluated first.
 This means the expression is equivalent to 5 + (3 * 2), resulting in 11.
2. Operator Associativity
Consider another example with operators of the same precedence:
int y = 10 - 2 - 3;
 Both subtraction operators (-) have the same precedence and are left-
associative.
 Therefore, the expression is evaluated from left to right: (10 - 2) - 3, resulting in 5.
3. Right-to-Left Associativity Example
For assignment operators, which have right-to-left associativity:
int a, b, c;
a = b = c = 10;
 The assignment happens from right to left: c = 10, then b = c, and finally a = b.
 All variables end up with the value 10.
4. Using Parentheses to Override Precedence
You can use parentheses to change the default precedence and associativity:
int z = (5 + 3) * 2; // Parentheses change the evaluation order
 Here, addition is performed first because of the parentheses, so the result is 16.
Key Points
 Higher precedence operators are evaluated before lower precedence
operators.
 Associativity determines the order for operators with the same precedence.
 Use parentheses to explicitly define the order of evaluation in complex
expressions.
Example Code Illustrating Precedence and Associativity
#include <stdio.h>
int main() {
int a = 5, b = 10, c = 15;
int result;
result = a + b * c; // Multiplication has higher precedence
printf("Result of a + b * c: %d\n", result);
result = (a + b) * c; // Parentheses change the order of evaluation
printf("Result of (a + b) * c: %d\n", result);
result = a - b - c; // Left-associative: (a - b) - c
printf("Result of a - b - c: %d\n", result);
result = a = b = c; // Right-associative: a = (b = c)
printf("Result of a = b = c: %d\n", result);
return 0;
}

You might also like