INTRODUCTION
TO
PROGRAMMING
[BTECH-JNTUGV-R23]
BY
CH. RAMACHANDRA REDDY
CEC@CSE-DEPARTMENT
BLOCK DIAGRAM OF COMPUTER AND ITS FUNCTIONAL UNITS EXPLAINATION
COMPUTER: A computer is a electronic device which accepts the input and
produces the desired output, it consists of so ware [set of programs] &
hardware [physical components] pro-ac vely work each other to perform any
frui ul task or complex task.
A computer system can be broadly divided into the following functional units:
1. Input Unit
2. Central Processing Unit (CPU)
o Arithmetic and Logic Unit (ALU)
o Control Unit (CU)
o Memory Unit (MU)
3. Output Unit
INTRODUCTION TO PROGRAMMING RCR@CEC
1. Input Unit:
The input unit is responsible for taking input from the user or environment.
Input devices like a keyboard, mouse, scanner, and microphone convert
user inputs into a form that the computer can process (typically binary
code).
Examples: Keyboard, Mouse, Scanner, Microphone.
2. Central Processing Unit (CPU):
The CPU is the brain of the computer where most calculations take place.
It performs all the instructions from the software and hardware.
Arithmetic and Logic Unit (ALU):
The ALU handles all arithmetic operations (like addition, subtraction,
multiplication, division) and logic operations (like AND, OR, NOT). It is
where actual data processing occurs.
Control Unit (CU):
The Control Unit directs all the operations of the computer by sending
control signals to other components. It interprets the instructions from the
software and directs the ALU and memory on how to respond.
Memory Unit:
The memory unit stores data and instructions that the CPU needs to execute
programs. It includes both volatile memory (RAM) and non-volatile
memory (ROM).
Types:
Primary Memory (RAM and ROM): Fast and directly
accessible by the CPU. RAM is volatile, meaning it loses its
data when the power is off, while ROM retains data
permanently.
Secondary Memory (Hard Drives, SSDs): Slower than
primary memory, used for long-term storage[secondary
storage devices].
INTRODUCTION TO PROGRAMMING RCR@CEC
3. Output Unit:
The output unit is responsible for presenting the processed data
(information) to the user or environment. Output devices convert binary
data from the computer into a human-readable form.
Examples: Monitor, Printer, Speakers.
INTRODUCTION TO PROGRAMMING RCR@CEC
INTRODUCTION TO PROGRAMMING RCR@CEC
INTRODUCTION TO PROGRAMMING RCR@CEC
INTRODUCTION TO PROGRAMMING RCR@CEC
INTRODUCTION TO PROGRAMMING RCR@CEC
INTRODUCTION TO PROGRAMMING RCR@CEC
UNIT-2
INTRODUCTION TO C -PROGRAMMING
Introduction,
Structure of a C Program
Comments
Keywords
Identifiers
Data Types
Variables
Constants
Input/output Statement.
Operators
Type Conversion
Control Flow, Relational Expressions:
Conditional Branching Statements: if, if-else, if-else—if, switch. Basic
Loop Structures: while, do-while loops, for loop, nested loops.
Break and Continue Statements, goto statements.
INTRODUCTION TO PROGRAMMING RCR@CEC
Introduction to C Programming
What is C Programming?
C is a general-purpose, procedural programming language that was initially
developed by Dennis Ritchie between 1969 and 1973 at Bell Labs at
AT&T[American Telephone & Telegraph]. It is one of the most widely used
programming languages, particularly known for its efficiency, portability, and the
control it offers over hardware.
C as a mother language
C language is considered as the mother language of all the modern programming
languages because most of the compilers, JVMs, Kernels, etc. are written in C
language, and most of the programming languages follow C syntax, for example,
C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc.
that are being used in many languages like C++, Java, C#, etc.
C as a system programming language
A system programming language is used to create system software. C language
is a system programming language because it can be used to do low-level
programming (for example driver and kernel). It is generally used to create
hardware devices, OS, drivers, kernels, etc. For example, Linux kernel is written
in C.
It can't be used for internet programming like Java, .Net, PHP, etc.
C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A
procedural language specifies a series of steps for the program to solve the
problem.
A procedural language breaks the program into functions, data structures, etc.
C is a procedural language. In C, variables and function prototypes must be
declared before being used.
INTRODUCTION TO PROGRAMMING RCR@CEC
C as a structured programming language
A structured programming language is a subset of the procedural
language. Structure means to break a program into parts or blocks so that it may
be easy to understand.
In the C language, we break the program into parts using functions. It makes the
program easier to understand and modify.
C as a mid-level programming language
C is considered as a middle-level language because it supports the feature of both
low-level and high-level languages. C language program is converted into
assembly code, it supports pointer arithmetic (low-level), but it is machine
independent (a feature of high-level).
A Low-level language is specific to one machine, i.e., machine dependent. It is
machine dependent, fast to run. But it is not easy to understand.
A High-Level language is not specific to one machine, i.e., machine independent.
It is easy to understand.
INTRODUCTION TO PROGRAMMING RCR@CEC
Key Features of C Programming
1. Simple and Easy to Learn
Simple Syntax: C has a straightforward and clean syntax, making it easier
for beginners to read and write code. It uses common English words and
symbols, so once you learn the basics, writing C programs becomes more
intuitive.
Foundation Language: C is often considered a foundation language.
Learning C makes it easier to understand and learn other programming
languages, as many concepts in modern languages like Java, C++, and
Python are based on C.
2. Efficient and Fast
High Performance: C is known for its speed. Programs written in C run
quickly because C code is close to the machine's language, meaning it
translates efficiently into instructions that the computer's hardware can
execute.
Minimal Overhead: C programs are lean, meaning they don’t require a
lot of extra resources or memory, which is why C is often used in situations
where performance is critical, like in game development or operating
systems.
INTRODUCTION TO PROGRAMMING RCR@CEC
3. Portable
Write Once, Run Anywhere: C is a portable language, which means you
can write a program on one type of computer and run it on another with
little or no modification. This portability is useful if you’re working on
projects that need to be used on different types of computers.
4. Structured Language
Organized Code: C supports structured programming, which helps you
organize your code into small, manageable sections. This makes your
programs easier to understand, debug, and modify. For example, you can
break a complex task into simpler parts by creating functions, each
performing a specific job.
5. Low-Level Access
Direct Hardware Control: C allows you to interact directly with the
computer’s memory and hardware. This level of control is beneficial for
tasks that need to manage resources precisely, such as developing operating
systems or embedded systems.
Use of Pointers: Pointers are a powerful feature in C that allows you to
manipulate memory directly, giving you fine-grained control over how
your program uses system resources.
6. Rich Set of Built-in Functions
Standard Library: C comes with a large number of built-in functions that
you can use to perform common tasks, like input/output operations, string
manipulation, mathematical calculations, and more. This library makes it
easier to perform complex operations without having to write everything
from scratch.
INTRODUCTION TO PROGRAMMING RCR@CEC
Advantages & Disadvantages
Pros And Cons // Merits & De-Merits
Advantages of C Programming:
1. Portability: C programs can be executed on various machines with
minimal changes. This makes C highly portable and a preferred choice for
developing system software.
2. Efficient and Fast: C is a low-level language, which allows developers to
write programs that are highly efficient and close to hardware, leading to
fast execution speeds.
3. Rich Library Support: C provides a wide range of built-in functions and
libraries that simplify the development process.
4. Structured Language: C follows a structured approach, allowing for
better organization of code through functions, making it easier to
understand, debug, and maintain.
5. Memory Management: C allows dynamic memory allocation, providing
more control over system memory, unlike many higher-level languages.
6. Low-Level Access: With C, you can directly manipulate bits, bytes, and
addresses, giving more control over hardware components, which is
essential in system programming.
7. Extensibility: C code can be easily extended and integrated with other
programming languages like C++ or Java.
INTRODUCTION TO PROGRAMMING RCR@CEC
Disadvantages of C Programming:
1. Lack of Object-Oriented Features: C is a procedural language and does
not support object-oriented programming concepts like inheritance,
polymorphism, or encapsulation.
2. Manual Memory Management: Developers are responsible for memory
management in C. Improper memory allocation or deallocation can lead to
memory leaks or crashes.
3. No Runtime Error Checking: C lacks features for runtime error detection,
like checking for array bounds or uninitialized variables, leading to
potential undefined behaviour.
4. Limited Standard Library: Although C has a standard library, its
collection of functions is less extensive compared to higher-level languages
like Python or Java.
5. No Built-in String Handling: C lacks built-in support for string
manipulation. Developers must use character arrays and functions from
libraries to manage strings.
6. Complex Syntax: For beginners, C’s syntax may seem complicated,
especially when dealing with pointers, memory management, or low-level
data manipulation.
7. Platform Dependency: While C is portable, some platform-specific code
or dependencies might be required, making certain programs less portable
across systems.
INTRODUCTION TO PROGRAMMING RCR@CEC
History of C
C programming language was developed in 1972 by Dennis Ritchie at bell
laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B,
BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It
inherits many features of previous languages such as B and BCPL.
INTRODUCTION TO PROGRAMMING RCR@CEC
Structure Of a C Program
The program written in C language follows this basic structure. The
sequence of sections should be as they are in the basic structure. A C
program should have one or more sections but the sequence of sections
is to be followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program or function section
1. DOCUMENTATION SECTION :
This is where you describe the program using comments. These
comments are ignored by the compiler but provide important information
for developers.
Comments in C can be:
o Single-line: //
o Multi-line: /* ... */
o It comes first and is used to document the use of logic or reasons in
your program.
o It can be used to write the program's objective, developer and logic
details.
o Whatever is written between will be non-printable & non
executable & non-readable.
INTRODUCTION TO PROGRAMMING RCR@CEC
2. LINKER SECTION / PREPROCESSOR SECTION
The preprocessor section contains all the header files used in a program. It
informs the system to link the header files to the system libraries.
They usually begin with #, and common examples include #include for
including header files and #define for defining constants.
Eg: #include<> #include<stdio.h>
Here, the # is a preprocessor-directive , stdio[standard input output] is header
file name & moreover it is a default header file of c programming, .h is the
extension of header file
3. DEFINITION SECTION : It is used to declare some constants and assign
them some value.
e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is
found in the
program replace it with 25.
4. GLOBAL DECLARATION SECTION : Here the variables which are used
through out the program
(including main and other functions) are declared so as to make them global(i.e
accessible to all
parts of program)
e.g. int i; (before main())
5. MAIN FUNCTION SECTION :
It tells the compiler where to start the execution from
The main() function is the entry point of any C program. Execution starts from
the main() function.
It typically returns an integer (int) and may accept arguments (int argc, char
*argv[]) in certain cases.
main()
INTRODUCTION TO PROGRAMMING RCR@CEC
{
point from execution starts
}
main function has two sections
1. declaration section : In this the variables and their data types are declared.
2. Executable section : This has the part of program which actually performs the
task we need.
6. SUB PROGRAM OR FUNCTION SECTION :
This has all the sub programs or the functions which our program needs.
7. Return Statement
The main() function typically ends with a return 0; statement, which
signifies successful completion of the program.
In other functions, return is used to return values.
SIMPLE ‘C’ PROGRAM:
/* simple program in c */
#include<stdio.h>
int main()
{
printf(“welcome to c programming”);
return 0;
} // End of main
INTRODUCTION TO PROGRAMMING RCR@CEC
CREATING AND RUNNING PROGRAMS:-
Generally, the programs created using programming languages like C,
C++, Java, etc., are written using a high-level language like English. But,
the computer cannot understand the high-level language.
It can understand only low-level language. So, the program written in high-
level language needs to be converted into the low-level language to make
it understandable for the computer.
This conversion is performed using either Interpreter or Compiler.
Popular programming languages like C, C++, Java, etc., use the compiler
to convert high-level language instructions into low level language
instructions.
sTo create and execute C programs in Windows Operating System, we need
to install Turbo C software. We use the following steps to create and
execute C programs in Windows-OS.
Execution Process of a C Program
INTRODUCTION TO PROGRAMMING RCR@CEC
C-TOKEN:
A C-TOKEN is smallest unit of a C-program.
A C-TOKEN is known as “building blocks” for constructing a program.
It represents various elements present in the program that may of variable,
constant, datatype, etc,,.
C-TOKENS:
Comments, Keywords, Identifiers, Data Types, Variables, Constants, Input/output
Statement, Operators
Comments in C
Definition: Comments are non-executable statements i.e., non printable in a
program that are used to explain code or describe about the program and make it
more readable & understandable for programmers. The compiler ignores these
lines during execution.
Types of Comments:
Single-line comments: Begin with // and continue until the end of the line.
o Example: // This is a single-line comment
Multi-line comments: Enclosed between /* and */. Can span multiple
lines.
Example: /* This is
a multi-line
comment */
Importance:
Makes code easier to understand.
Helps in debugging by explaining logic.
Can be used to disable parts of code temporarily.
INTRODUCTION TO PROGRAMMING RCR@CEC
Purpose of Comments:
Documentation: Explaining what certain sections of code are doing,
especially complex logic.
Code Review: Helping other programmers or collaborators to understand
the code more efficiently.
Debugging: Allowing specific parts of the code to be commented out for
testing without deleting the lines.
Keywords in C
Definition:
Keywords in C are reserved words that have specific meanings in the C language.
They are predefined in the C language syntax, which means that they cannot be
used for any other purpose, such as naming variables or functions. Keywords
serve as building blocks of C's syntax and control the flow of a program, data
types, operations, and more.
Characteristics of Keywords:
They are written in lowercase (e.g., int, float, if, else).
Keywords are the foundation of C syntax, as they define operations, control
structures, data types, and more.
Each keyword has a specific, well-defined meaning that the compiler
understands.
Reserved: The C language reserves keywords are those keywords that
cannot be used as identifiers in programs. Using a keyword as a variable
name or other identifier will cause a compilation error.
Predefined Meaning: Each keyword has a specific meaning that is
assigned by the C language. These meanings are built into the C language's
grammar and syntax and the compiler interprets them accordingly.
Specific Use: Keywords are designed for specific purposes and contexts
within the C language. They define control structures, data types, flow
control, and other language constructs. Attempting to use a keyword
outside of its intended purpose will result in a compilation error.
INTRODUCTION TO PROGRAMMING RCR@CEC
Standardized: C language keywords are standardized across different
compilers and implementations. It ensures the consistency and portability
of C programs across different platforms and environments.
Examples:
Control flow: if, else, switch, for, while, do
Data types: int, char, float, double
Miscellaneous: return, void, sizeof
NOTE:
There are 32 keywords in the c language is given below:
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
Identifiers in C
Definition:
Identifiers are names given to various elements in a C program, such as variables,
functions, arrays, and structures. An identifier allows the programmer to refer to
these elements in the code. Unlike keywords, identifiers can be chosen by the
programmer, following certain rules, to name data and functions.
Key Points:
Identifiers are case-sensitive, meaning count, Count, and COUNT are
treated as three different identifiers.
They must begin with a letter (A-Z, a-z) or an underscore (_), followed by
letters, digits (0-9), or underscores.
Identifiers should be descriptive to make the code more readable and
maintainable (e.g., totalMarks rather than tm).
INTRODUCTION TO PROGRAMMING RCR@CEC
Variables
A variable is the name of the memory location. It is used to store
information. Its value can be altered and reused several times. It is a way
to represent memory location through symbols so that it can be easily
identified.
Variables used to store and modify data in computer programs. A variable
is a designated memory region that stores a specified data type value. Each
variable has a unique identifier, its name, and a data type describing the
type of data.
Declaring the data type.
Specifying the data that the variable may carry.
Giving the variable a unique name.
SYNTAX: data_type variable_name;
RULES for IDENTIFIERS & VARIABLES to follow:
The first character of an identifier should be either an alphabet or an
underscore, and then it can be followed by any of the character(a to z,
A TO Z ), digit(1,2,3), or underscore( _ ).
It should not begin with any numerical digit.
In identifiers, both uppercase and lowercase letters are distinct.
Therefore, we can say that identifiers are case sensitive.
Commas or blank spaces cannot be specified within an identifier.
Keywords cannot be represented as an identifier.
The length of the identifiers should not be more than 31 characters.
Identifiers should be written in such a way that it is meaningful, short,
and easy to read.
Types of Variables: There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
INTRODUCTION TO PROGRAMMING RCR@CEC
Local Variable
A variable that is declared inside the function or block is called a local variable.
It must be declared at the start of the block.
Global Variable
A variable that is declared outside the function or block is called a global variable.
Any function can change the value of the global variable. It is available to all the
functions.
It must be declared at the start of the block.
Static Variable
A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls.
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by
default. We can explicitly declare an automatic variable using auto keyword.
External Variable
We can share a variable in multiple C source files by using an external variable.
To declare an external variable, you need to use extern keyword.
INTRODUCTION TO PROGRAMMING RCR@CEC
Data Types in C
Definition:
Data types in C specify the type of data a variable can hold and the size of the
memory it will occupy.
They are a crucial aspect of defining variables because they determine how much
memory will be allocated for a variable
To represent different types of data in C program we need different data types.
A data type is essential to identify the storage representation and the type of
operations that can be performed on that data.
Classification/ Categories/ data types supported by C/ types of data types:
Primitive Data Types:
These are the basic built-in types of data used to store integers, floating-
point numbers, characters, etc.
Integer Types: Stores whole numbers (e.g., int, short, long).
Floating-point Types: Stores real numbers with fractional parts (e.g., float,
double).
Character Types: Stores single characters (char).
Notes:
The size of int, long, and float can vary depending on the system
architecture (32-bit vs 64-bit).
unsigned data types do not allow negative values but allow for a
larger positive range.
INTRODUCTION TO PROGRAMMING RCR@CEC
A format specifier in C is a special sequence of specification used within input
and output functions like printf() and scanf() to specify the type of data that is
being passed. Format specifiers inform the compiler how to interpret the
corresponding variable or value during input/output operations.
Format specifiers are used to handle various data types and ensure the correct
format of data when printing it on the screen or accepting it from the user.
How Format Specifiers Work:
When using printf(), format specifiers define how data is displayed.
When using scanf(), they indicate how the program should read and store
user input.
INTRODUCTION TO PROGRAMMING RCR@CEC
Derived Data Types:
These are types that are derived from the primitive data types.
Examples include arrays, pointers, and functions.
User-defined Data Types:
C Provides a facility called typedef for creating new data type
namesdefined by the user.
For Example , typedef int Integer;
Integer num1,num2;
the declaration , typedef int Integer; It makes the name Integer a synonym
of int. Now the type Integer can be used in declarations , casts, etc, like,
Integer num1,num2; Which will be treated by the C compiler as the
declaration of num1,num2as int variables.
“typedef” ia more useful with structures and pointers.
NOTE: [another type of datatypes used at rare cases]
Enumeration Data Types:
Enumerations define a set of named integer constants using the enum
keyword.
Void:
Represents no value. Commonly used for functions that don’t return any
data.
INTRODUCTION TO PROGRAMMING RCR@CEC
Constants in C
Definition:
Constants in C are fixed values that, once defined, cannot be altered by the
program during its execution. Constants are essential when values need to remain
unchanged throughout the program.
Types of Constants:
1. Integer Constants: Whole numbers without any fractional part (e.g., 10, -
50).
2. Floating-point Constants: Numbers with a decimal point (e.g., 3.14, -
0.001).
3. Character Constants: A single character enclosed in single quotes (e.g.,
'A', '9').
4. String Constants: A sequence of characters enclosed in double quotes
(e.g., "Hello World").
Declared using the #define directive or const keyword.
o #define: Creates a macro that the compiler replaces with a value
before the program is compiled.
o const: Defines a variable whose value cannot change after
initialization.
Example:
#define PI 3.1415 // Symbolic constant
const int MAX = 100; // Constant variable
advantages of using constants in C:
1. Improves Readability: Constants make the code easier to understand
with descriptive names.
2. Easier Maintenance: Changing a constant's value in one place updates it
everywhere in the code.
3. Prevents Modification: Constants cannot be altered during execution,
avoiding accidental changes.
INTRODUCTION TO PROGRAMMING RCR@CEC
4. Optimizes Memory: The compiler can efficiently manage memory by
storing constants in read-only memory.
5. Increases Security: Critical values remain unchanged, reducing bugs and
vulnerabilities.
6. Reusable: Constants can be used across functions or files, promoting
modular and reusable code.
7. Simplifies Debugging: Constants make debugging easier by avoiding
"magic numbers."
8. Ensures Consistency: Guarantees that common values are consistently
used throughout the program.
Input/Output Statements in C
Definition:
Input/Output (I/O) statements allow a C program to interact with the user by
receiving input and displaying output. The standard I/O functions are part of the
stdio.h library/header file and are essential for communicating data between the
user and the program.
Common Input/Output Functions:
1. printf():
o Used to output data to the console.
o Takes a format string and optional variables.
o Example: printf("The value is %d", number);
2. scanf():
o Used to take input from the user.
o Requires the address of the variable to store the input using the &
operator.
o Example: scanf("%d", &number);
*few functions: puts(); , get(); , putchar(); , getchar(); also comes under i/o
statements.
INTRODUCTION TO PROGRAMMING RCR@CEC
Expression in C
An expression in C is a combination of operands (variables, constants, or values)
and operators that evaluates to a value. Expressions are fundamental to any C
program, as they perform calculations, assign values, and control the flow of
logic.
Components of an Expression:
1. Operands: These are the values or variables that the operator works on.
o Examples: x, 5, 3.14, etc.
2. Operators: Symbols that perform operations on operands.
o Examples: +, -, *, /, =, etc.
Operators in C
Definition:
Operators in C are special symbols that perform operations on operands (variables
and values). They are essential for performing calculations, comparisons, and
logical operations. Operators are divided into different categories based on the
type of operation of particular operator they perform.
Classifications of Operators
Unary operator: Only one operand is required to perform calculation.
Binary Operator: Two operands are required to perform calculation.
Ternary Operator: Three operands are required to perform calculation.
INTRODUCTION TO PROGRAMMING RCR@CEC
INTRODUCTION TO PROGRAMMING RCR@CEC
Types of Operators:
1. Arithmetic Operators: Used for basic mathematical operations like
addition (+), subtraction (-), multiplication (*), division (/), and modulus
(%)
2. Relational Operators: Used to compare two values. Common operators
include greater than (>), less than (<), equal to (==), not equal to (!=).
3. Logical Operators:
Used to combine multiple conditions. Includes AND (&&), OR (||), and
NOT (!).
4. Assignment Operators:
Used to assign values to variables. The basic assignment operator is =, but
there are also compound assignment operators like +=, -=, *=.
5. Increment/Decrement Operators: Used to increase (++) or decrease (--)
a variable's value by one.
Types:
PRE-increment/decrement: increase or decrease the variables value
by 1 first then assign to it.
POST-increment/decrement: first assign the value to variable later
increase or decrease the variables value by 1.
6. Bitwise Operators:
Perform operations at the bit level, such as AND (&), OR (|), XOR (^),
NOT (~), shift left (<<), and shift right (>>).
INTRODUCTION TO PROGRAMMING RCR@CEC
7. Conditional (Ternary) Operator
The conditional operator, also known as the ternary operator (?:), is a
compact form of the if-else statement in C. It allows you to execute one of
two expressions based on a condition, and it is the only operator in C that
takes three operands.
Syntax: condition ? expression1 : expression2;
condition: A boolean expression (evaluated as either true or false).
expression1: Executed if the condition is true.
expression2: Executed if the condition is false.
If the condition is true, the operator returns the value of expression1.
If the condition is false, it returns the value of expression2.
Advantages:
1. Concise: The conditional operator can replace an if-else block in a single
line.
2. Readable: Improves readability when used for simple conditions.
3. Inline Use: Can be used directly in expressions and assignments.
Example:
int num = 5;
char *result = (num % 2 == 0) ? "Even" : "Odd";
// Output: result will point to "Odd" since 5 is not divisible by 2.
INTRODUCTION TO PROGRAMMING RCR@CEC
Precedence & Associativity in C
Operator precedence defines the order in which different operators are
evaluated in an expression. When an expression contains multiple operators,
precedence determines which operations are performed first. Operators with
higher precedence are evaluated before those with lower precedence.
Example: In the expression 5 + 3 * 2, multiplication (*) has higher
precedence than addition (+), so the multiplication is done first, resulting
in 5 + 6 = 11.
Associativity defines the direction in which operators of the same precedence
level are evaluated when they appear together in an expression. Associativity can
be either left-to-right or right-to-left:
Left-to-right: Most operators (like +, -, *, /, etc.) are evaluated from left
to right.
Right-to-left: Some operators (like assignment = and unary operators) are
evaluated from right to left.
Example: In the expression 5 - 3 - 2, both - operators have the same
precedence and left-to-right associativity, so the expression is evaluated as
(5 - 3) - 2 = 0.
INTRODUCTION TO PROGRAMMING RCR@CEC
Type Conversion in C
Type conversion, also known as type casting, refers to the process of converting
a variable from one data type to another. In C, there are two types of type
conversion:
1. Implicit Type Conversion (Automatic Type Conversion)
2. Explicit Type Conversion (Type Casting)
1. Implicit Type Conversion (Automatic Type Conversion)
Implicit type conversion occurs automatically when a variable of one type is
assigned to another type, without the need for explicit instructions from the
programmer. The C compiler handles this automatically, and it typically occurs
when performing operations involving two different types.
How It Works:
When the two operands in an expression have different data types, the
compiler converts the lower data type to the higher data type before
performing the operation.
The hierarchy of data types (from lower to higher) is as follows: char →
int → float → double
Example:
int a = 10;
float b = 5.5;
float result = a + b; // 'a' is implicitly converted to float
Here, a is automatically converted from int to float before the addition.
Promotion of Data Types:
Integer promotion: Smaller integer types like char and short are promoted
to int when used in an expression.
Floating-point promotion: If an operation involves float and double, the
float is promoted to double.
INTRODUCTION TO PROGRAMMING RCR@CEC
2. Explicit Type Conversion (Type Casting)
Explicit type conversion (type casting) is when a programmer explicitly converts
a variable from one type to another using the cast operator.
Syntax:
(type) expression;
Example:
int a = 10;
float b = 3.14;
int result = (int)b; // 'b' is explicitly converted from float to int
Main key Differences:
INTRODUCTION TO PROGRAMMING RCR@CEC