0% found this document useful (0 votes)
4 views46 pages

Module 1 Final

The document provides an introduction to computing and programming in C, covering machine languages, symbolic languages, and high-level languages. It outlines the steps for creating and running C programs, including editing, compiling, linking, and executing, as well as the system development life cycle and different models like Waterfall and Agile. Additionally, it discusses the history of C, its evolution from BCPL and B, and its classification as a middle-level language that combines features of both high-level and low-level languages.

Uploaded by

pallavi
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)
4 views46 pages

Module 1 Final

The document provides an introduction to computing and programming in C, covering machine languages, symbolic languages, and high-level languages. It outlines the steps for creating and running C programs, including editing, compiling, linking, and executing, as well as the system development life cycle and different models like Waterfall and Agile. Additionally, it discusses the history of C, its evolution from BCPL and B, and its classification as a middle-level language that combines features of both high-level and low-level languages.

Uploaded by

pallavi
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 In C (1BEIT105)

MODULE – 01
Chapter-01
1. Introduction to Computing
1.1 Computer languages

Machine Languages

A machine language is a computer's native language, consisting of streams of 0s and 1s,


representing the "off" and "on" states of a computer's internal circuits (switches and transistors).
Every computer has its own unique machine language.

Machine language is the only language that a computer's hardware can directly understand and
execute. All other programming languages, no matter how advanced, must be translated into
machine language for a computer to run the program.

Example: Addition Program in machine language (binary form):

0001 01 ; LOAD number from address 01 (5)


0010 10 ; ADD number from address 10 (3)
0011 11 ; STORE result in address 11
1111 00 ; HALT

Symbolic Languages

 Symbolic languages are early programming languages that used symbols or


mnemonics (like short codes) to represent machine language instructions.
 They were created to make programming easier than using streams of 0s and 1s.
 Admiral Grace Hopper is credited with developing the concept of a program to
convert these symbolic instructions into machine code.
 A special program called an assembler translates symbolic code into machine
language.
 Because of this translation process, symbolic languages are also known as assembly
languages.
 The code is typically laid out in columns for labels, operators, and operands.
 Symbolic languages are hardware-specific, meaning they closely mirror the machine
language of a particular computer.

Example: Addition Program in Symbolic language

LOAD 01 ; Load value at address 01 (5)


ADD 10 ; Add value at address 10 (3)
STORE 11 ; Store result at address 11
HALT ; Stop execution

High-Level Languages

 High-level languages were developed to improve programmer efficiency and focus on


solving problems rather than a computer's hardware details.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -1


Programming In C (1BEIT105)

 They are portable, allowing the same code to run on different computers with minimal
changes.
 High-level languages are easier for humans to read and write, using syntax that is closer
to human language.
 They must be converted to machine language through a process called compilation,
which is done by a compiler.
 Early examples include FORTRAN (for scientific/engineering) and COBOL (for
business). C is another widely used high-level language.

Example: Addition Program in C

#include <stdio.h>
int main() {
int a = 5, b = 3, sum;
sum = a + b;
printf("Sum = %d\n", sum);
return 0;
}

1.2 Creating and Running Programs


Writing a program in C involves several steps, as C code needs to be translated into machine
language for the computer to understand. This process can be broken down into four key steps:

1. Editing: Writing the program in a text editor.


2. Compiling: Translating the program into machine-readable code.
3. Linking: Combining the program with the necessary library modules.
4. Executing: Running the program.

Writing and Editing Programs

To write a program, a text editor is used. This can be a simple text editor (like
Notepad), a word processor (saving as plain text), or more commonly, an integrated
development environment (IDE) that combines editing, compiling, and debugging tools. Text
editors allow you to write, modify, and save your source code files (e.g., program.c). Features
like search and replace, cut, copy, and paste commands, and tab settings are helpful for efficient
coding.

Compiling Programs

The compiler is responsible for translating the human-readable C source code into machine
language. This is typically a two-part process:

1. Pre-processor: This initial stage handles directives (like #include <stdio.h>) that modify
the source code before the main compilation.
2. Translator: The main compiler then takes the pre-processed code and translates it into
machine language instructions. The output of the compiler is an object module (e.g.,
[Link] or program.o), which contains the machine language code, but is not yet ready
to run.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -2


Programming In C (1BEIT105)

Linking Programs

Modern C programs often utilize many pre-written functions provided in libraries. The
linker is a program that takes the object module generated by the compiler and combines it
with these library functions and other object files to create a single, complete executable
program. This executable file contains all the machine code necessary to run the program.

Executing Programs

Once the executable program is created, it is ready for execution. This is handled by an
operating system utility known as the loader. The loader's job is to load the executable file
from secondary memory (like a hard drive) into the computer's main memory (RAM). Once in
RAM, the program takes control, and its instructions are carried out by the central processing
unit (CPU). Program execution often involves user input and display of output on the screen.

Figure 1-11: Building a C Program

The diagram illustrates the workflow:

 Programmer writes Source code using a Text editor.


 The Compiler processes the Source code to produce an Object module (machine code
instructions).
 The Linker takes the Object module and combines it with necessary functions from a
Library to create an Executable file.
 Finally, the Loader takes the Executable file and loads it into memory for execution,
producing Results.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -3


Programming In C (1BEIT105)

1.3 System Development

System development is a structured process used to create software applications. It


involves a series of steps to ensure the final product meets user requirements, is high-quality,
and is completed efficiently.

System Development Life Cycle (SDLC): The SDLC is a conceptual model that outlines all
the stages involved in the development of an information system. While specific models may
vary, they generally follow a sequence of interdependent phases.

Waterfall Model

The Waterfall model is a traditional, sequential approach where each phase must be completed
before the next begins. It is suitable for projects with clear, stable requirements.

Figure 1-12: Waterfall Model

Phases of the Waterfall Model:

1. Systems Requirements: Define what the system needs to do.


2. Analysis: Understand the system requirements in detail. This phase often results in a
functional specification.
3. Design: Develop the system's architecture, defining how it will work.
4. Code: Write the actual program code based on the design.
5. System Test: Test the complete system to ensure it meets requirements and is free of
errors.
6. Maintenance: Ongoing support, bug fixes, and enhancements after deployment.

Waterfall model is costly and time-consuming, making it less flexible for changing
requirements.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -4


Programming In C (1BEIT105)

Agile Model

The Agile model is an iterative and incremental approach that emphasizes flexibility,
collaboration, and rapid delivery of working software. It involves short development cycles
called "sprints" or "iterations."

Figure 1-13: Agile Model - An iterative, adaptive approach to software development

The Agile model consists of several iterative phases that ensure flexibility and continuous
improvement during software development.

1. Requirement Analysis: This is the initial stage where the development team works to
understand and gather the user’s needs and expectations.
2. Design: Based on the requirements, the architecture and design for the features in the
current iteration are created.
3. Development: The coding and implementation of the planned features are carried out
in this phase.
4. Testing: Quality assurance activities are performed, including bug detection and fixing,
to ensure the developed features work as intended.
5. Deployment: The working software increment is released to customers for use and
feedback.
6. Continued Iterations: The process repeats, with each cycle adding new features or
refining existing ones until the product reaches its final form.

Program Development

Program development involves a structured approach to creating individual software


programs. It typically begins with understanding the problem, devising a solution, writing the
program, and then testing it.

Understand the Problem

This is the most crucial step. Before writing any code, you must thoroughly understand
what the program needs to accomplish.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -5


Programming In C (1BEIT105)

This involves:

 Reading the requirements statement: Carefully review the problem description.


 Clarifying unknowns: Ask questions to ensure a complete understanding.
 Identifying Inputs: What data will the program receive?
 Identifying Outputs: What results should the program produce?
 Defining Constraints: Are there any limitations or specific conditions?

 Example: Calculating Square Footage


o What is the definition of square footage?
o How is the square footage going to be used?
o For calculating a quote for home insurance?
o For calculating the amount of paint required to carpet all or part of the house?
o Is the garage included?
o Are closets and hallways included?

Example: Addition of two numbers


o What is it? → Adding two numbers to get the sum.
o Why use it? → For simple calculations.
o Where do numbers come from? → User or given values.
o What to do with result? → Show the sum.

Develop the Solution


After understanding and clarifying the problem, the next step is to develop the solution.
Three tools help in this task:

1. Structure charts
2. Pseudocode
3. Flowcharts

Generally, you will use only two of them — a structure chart and either pseudocode or a
flowchart.

 Structure chart is used to design the whole program.


 Pseudocode and flowcharts are used to design the individual parts of the program.
 These parts are known as modules in pseudocode or functions in the C language.

Structure Chart

A structure chart, also called a hierarchy chart, is a tool used to show the functional flow of
a program. It breaks the program into logical steps, with each step represented as a separate
module. This design is similar to an architect’s blueprint for a house, as it provides a complete
picture of how the program will be built before coding begins. By carefully laying out the
modules and their interconnections, programmers gain a clear understanding of the system and
avoid mistakes caused by incomplete planning.

Large programs are often complex, consisting of many interrelated parts. The structure chart
helps organize these parts so they are easier to design, understand, and implement. It
distinguishes between the programmer’s product (software, existing inside the computer) and
an engineer’s product (a physical object).

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -6


Programming In C (1BEIT105)

 Example: A program to calculate square footage for linoleum and carpeting could be
broken down into modules for getting user info, calculating different areas (kitchen,
bathroom, bedroom, living areas), printing reports, etc.

Figure 1-14: Structure chart for calculating square footage

Structure chart for Addition of Two numbers

Pseudocode
Pseudocode is an informal, high-level description of a program's algorithm. It uses a
blend of natural language and programming constructs to outline the logic without adhering to
a specific programming language's syntax.

Algorithm 1-1: Pseudocode for Calculate BathRooms

1 prompt user to enter (input) linoleum price


2 prompt user and read number of bathrooms
3 set total bath area and baths processed to zero
4 while (baths processed < number of bathrooms)
4.1 prompt user and read bathLength and bathWidth

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -7


Programming In C (1BEIT105)

4.2 total bath area = total bath area + bath length * bath width
4.3 add 1 to baths processed
5 bath cost = total bath area * linoleum price
6 return bath cost
end algorithm Calculate Bathrooms

This pseudocode describes a function to calculate the total cost for linoleum in multiple
bathrooms. It iterates through each bathroom, takes its dimensions, calculates its area, and sums
it up, finally multiplying by the linoleum price.

Flowchart
A flowchart is a graphical representation of an algorithm, using standard symbols to
depict the logical flow of operations, decisions, and data.

Figure 1-15: Flowchart for calculating bathrooms

Flowchart for calculating Addition of two numbers

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -8


Programming In C (1BEIT105)

This visual diagram shows the same logic as the pseudocode: taking inputs, looping to
calculate area for each bathroom, and returning a final cost.

After designing the program using structure charts, pseudocode, or flowcharts, the next
step is to write the program. Coding should follow the design step by step, usually beginning
at the top of the structure chart and working downward. A well-prepared design makes
programming easier, reduces confusion, and ensures a clear logical flow in the implementation.

Once the program is written, it must be tested to ensure correctness and reliability.
Testing is one of the most important but time-consuming parts of software development. It
validates whether the program works as expected under all possible conditions. The two main
types of testing are blackbox testing, performed by test engineers without knowledge of the
internal code, and whitebox testing, performed by programmers with complete knowledge of
the internal logic.

Blackbox testing checks the system against requirements, treating the program as a
black box where only inputs and outputs are observed. Whitebox testing, on the other hand,
ensures that every line of code, condition, loop, and boundary value is tested at least once. It
also verifies error-handling logic. Together, these methods ensure the program is error-free,
reliable, and meets user requirements.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -9


Programming In C (1BEIT105)

Chapter-02
An Overview of C

2.1 A Brief History of C

1. Before C – BCPL and B


o BCPL (Basic Combined Programming Language) → Created by Martin
Richards.
o From BCPL came B, invented by Ken Thompson.
o B then evolved into C.
2. Invention of C
o Dennis Ritchie invented C in the 1970s.
o First used on a DEC PDP-11 computer running Unix.
o C became popular because it was simple, powerful, and portable.
3. First Standard – K&R C
o Early C was described in the famous book “The C Programming Language”
(1978) by Brian Kernighan and Dennis Ritchie.
o This version is often called K&R C.
4. ANSI Standard – C89 / ANSI C
o In 1983, a committee started working to standardize C.
o Standard approved in 1989 → called C89 (or ANSI C).
o Later also approved internationally → called ISO C.
5. Update – Amendment 1 (1995)
o Added new library functions.
o This version became the base for C++ (since C++ was built on C).
6. C99 Standard (1999)
o Introduced improvements like:
 Variable-length arrays
 restrict pointer (for optimization)
 New numeric libraries
o Still kept almost everything from C89.
o Ensured C remained modern and useful.
7. Today
o C89 → still the most widely supported (used for maximum compatibility).
o C99 → adds more features but not always supported by older compilers.
o C++ grew from C, but C is still used everywhere for system programming,
operating systems, and embedded systems.

2.2 C as a Middle-Level Language


o Combines features of high-level languages (easy, portable) and low-level
(assembly) (control, flexibility).
o Allows direct manipulation of bits, bytes, addresses (like assembly).
o Still portable → programs can run on different systems with little change.
 Position in Language Spectrum
o High-level: Ada, Pascal, COBOL, FORTRAN, BASIC
o Middle-level: Java, C++, C
o Low-level: Assembler
 Data Types in C
o Supports common types: int, char, float etc.
o Not strongly typed (unlike Pascal, Ada).

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -10


Programming In C (1BEIT105)

o Allows type conversions freely (e.g., char ↔ int).


 Error Checking
o Very little run-time error checking.
o Example: No automatic check for array bounds.
o Responsibility lies with programmer.
 Function Arguments
o C does not demand strict type matching.
o Allows conversions between parameter and argument types.
 Special Features of C
o Direct access to bits, bytes, words, pointers → useful for system
programming.
o Small set of keywords:
 C89 → 32 keywords
 C99 → +5 keywords (total 37)
 BASIC → 100+ keywords

2.3 C is a structured language


 C is called a structured language because it organizes a program into small,
manageable parts instead of writing everything in one long sequence. These parts are
mainly functions and blocks of code. A function is like a small machine that does one
specific job (e.g., calculating sum, printing a message). Each function works
independently without disturbing the rest of the program. This makes programs easier
to read, test, and reuse.
 Although C is similar to other structured languages like Pascal, Ada, or Java, it is not
fully block-structured because it does not allow one function to be written inside
another. Still, it supports the main features of structured programming.
 C also allows code blocks, which are groups of statements enclosed in curly braces { }.
For example:
 if (x < 10) {
 printf("Too low, try again.\n");
 scanf("%d", &x);
 }
 Here, both statements inside the braces run together as a single logical unit. Blocks like
this make the code neat and logical.
 Structured languages like C also provide looping constructs such as while, do-while, and
for for repeating tasks, instead of relying on the old goto command (which is
discouraged). This improves clarity and reduces errors.
 The most important feature of structured languages is compartmentalization of code
and data. This means information is kept only where it is needed. In C, this is done
using local variables, which exist only inside the function or block. This avoids
unwanted side effects caused by global variables (which affect the entire program).
 In short, C’s structured approach—through functions, blocks, loops, and local
variables—makes programs easier to design, understand, debug, and reuse.

2.4 C Is a Programmer’s Language

C is called a programmer’s language because it was designed by programmers for


programmers. Unlike COBOL and BASIC, which were made for nonprogrammers to
understand or write simple programs, C was created to give programmers freedom, control,

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -11


Programming In C (1BEIT105)

and efficiency. It provides few restrictions, uses block structure and stand-alone functions, and
has a small set of keywords that make coding fast and flexible.

C combines the speed of assembly language with the structured design of higher-level
languages like Pascal or Modula-2. Assembly language is powerful but hard to read, debug,
and maintain, and it is not portable between machines. C solved these problems by offering
structured programming and portability, allowing the same program to run on different
computers easily.

At first, C was mainly used for system programming, such as creating operating
systems, compilers, and utilities. Later, it became popular for all types of programs because it
is fast, efficient, and portable. Even after the invention of C++, C remains widely used—
especially in embedded systems and system-level software—because it is simple, powerful,
and dependable. Thus, C continues to be one of the most important and long-lasting
programming languages in the world.

2.5 Compilers vs. Interpreters

 Language vs Execution:
o A programming language defines what the program is, not how it is executed.
o Execution methods: Compilation or Interpretation.
 Interpreter
o Reads and executes code line by line.
o Slower because it processes instructions at run-time.
o Example: Early BASIC worked this way.
o Java: converts code to an intermediate form (bytecode), then interpreted by
JVM.
o Requires interpreter every time the program runs.
 Compiler
o Translates the entire program into object code (machine code/binary).
o Once compiled, source code is no longer needed at run-time.
o Compilation is a one-time cost → execution is fast.
o C is designed as a compiled language (though interpreters exist for special
cases).
 Speed Difference
o Compiled programs → faster.

o Interpreted programs → slower due to overhead each run.

Keywords in C

 C89 Keywords (32 total) include:


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
 C99 adds 5 more keywords:
_Bool, _Complex, _Imaginary, inline, restrict
 Rules:
o C is case-sensitive → else is valid, ELSE is not.
o Keywords cannot be used as variable or function names.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -12


Programming In C (1BEIT105)

 Extended Keywords (compiler-specific, nonstandard): e.g., asm, far, near, huge, pascal,
interrupt.

2.6 Form of a C Program

 A C program = one or more functions.


 main():
o Must be present in every program.
o First function executed.
o Acts as an outline of program → calls other functions.
o Not a keyword, but treat it as reserved.
 General Structure of C Program:

main() {
// outline of program
f1(); // call to user-defined function
f2();
...
fN();
}

f1() { ... } // user-defined function


f2() { ... }
...
fN() { ... }

Global declarations
int main(parameter list)
{
statement sequence
}
return-type f1(parameter list)
{
statement sequence
}
return-type f2(parameter list)
{
statement sequence
}...
return-type fN(parameter list)
{
statement sequence
}
Figure 1-1
The general form of a C program

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -13


Programming In C (1BEIT105)

2.7 Library and Linking

 C language provides only keywords → does not directly support I/O, math, graphics,
etc.
 Standard Library contains commonly used functions (e.g., printf(), scanf(), sqrt()).
 Functions in libraries are reusable building blocks.
 When you use a library function:
o Compiler remembers its name.
o Linker connects your code with object code of the library.
 Linking:
o Some compilers use their own linker.
o Others rely on the OS linker.
 Library functions are in relocatable format:
o Memory addresses are not fixed, only offsets are stored.
o Actual addresses are assigned during linking.
 You can also create your own custom libraries.

2.8 Separate Compilation

 Small programs → usually written in one file.


 Large programs → can be split into multiple files.
 Benefits:
o Saves time → only modified file needs recompilation.
o Helps in team projects (multiple programmers).
o Organizes large projects.
 After compiling all files → they are linked together with required libraries.

2.9 Compiling a C Program

1. Create program → write source code (.c file).


2. Compile program → convert source code into object code (.o / .obj).
3. Link program → combine object code with libraries to form executable.

 Note:
o Compiler requires plain text files (not word processor files).
o Compilation & linking process varies with compilers.
o Many compilers provide IDE (Integrated Development Environment) with
built-in editor + compiler.

2.10 C Program Memory Map

A compiled C program uses four distinct memory regions:

1. Program Code (Text Segment)


o Stores compiled machine code instructions.
2. Global Variables (Data Segment)
o Stores global and static variables.
3. Stack
o Stores:

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -14


Programming In C (1BEIT105)

 Return addresses of function calls.


 Function arguments.
 Local variables.
 Current CPU state during execution.
o Grows downward in memory.
4. Heap
o Stores dynamically allocated memory (malloc(), calloc(), free()).
o Grows upward in memory.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -15


Programming In C (1BEIT105)

Chapter-3
Expressions
3.1 The Basic Data types:

In C language, there are some basic data types which are the building blocks for all other
types. C89 defines five of them: char, int, float, double, and void. These are written using
their keywords.

 char is used to store characters like letters, numbers, and symbols (usually from the
ASCII set). It always takes 1 byte (8 bits).
 int is used to store whole numbers. Its size depends on the system. On old 16-bit
systems, it was 16 bits. On 32-bit systems, it is usually 32 bits. On modern 64-bit
systems, it is also commonly 32 bits. You should not assume its size, because it changes
with compiler and environment.
 float is used for decimal numbers with single precision (around 6 digits of accuracy).
 double is also for decimal numbers but with double precision (around 15 digits of
accuracy). The range of float and double is very large, at least from 1E–37 to 1E+37.
 void means “nothing.” It is used when a function does not return any value, or when
creating a generic pointer (void*) that can point to any type of data.

Later, in C99, three more types were added:

 _Bool → for Boolean values (true/false).


 _Complex → for complex numbers.
 _Imaginary → for imaginary numbers.

3.2 Modifying the Basic data types

In C, we can use modifiers with the basic data types (except void) to change their size
or how they handle values. The main modifiers are signed, unsigned, short, and long.
These modifiers help us store numbers more efficiently depending on whether we need
negative values or larger ranges.

The int type can be combined with signed, unsigned, short, and long. For example,
short int uses less memory than a normal int, while long int uses more. Similarly, char can be
either signed or unsigned, which decides whether it can store negative values or only
positive ones. The double type can also be modified with long to give long double (higher
precision). In C99, an extra type called long long int was introduced for very large integers.

By default, if you just write int, it is treated as signed int. So writing signed int is usually
not necessary unless you want to be clear. Also, if you use only a modifier without a type
(like just unsigned), C assumes int. For example, unsigned means unsigned int, and short means
short int.

The difference between signed and unsigned numbers is in how the highest (leftmost)
bit is interpreted. In signed numbers, that bit is the sign flag (0 = positive, 1 = negative).
In unsigned numbers, all bits are used to store the value, so they can hold larger positive
numbers but no negatives. Most systems use the two’s complement method to represent
negative numbers: invert the bits, add 1, and mark the sign bit as 1.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -16


Programming In C (1BEIT105)

For example, a 16-bit signed integer can hold values from –32,768 to 32,767, but an
unsigned 16-bit integer can hold 0 to 65,535. This means unsigned types give a bigger
positive range, while signed types allow both positive and negative values.

Table 2-1 shows all valid data type combinations supported by C, along with their
minimal ranges and typical bit widths

Type Typical Size (bits) Minimal Range / Precision


char 8 –127 to 127
unsigned char 8 0 to 255
signed char 8 –127 to 127
int 16 or 32 –32,767 to 32,767
unsigned int 16 or 32 0 to 65,535
signed int 16 or 32 Same as int
short int 16 –32,767 to 32,767
unsigned short int 16 0 to 65,535
signed short int 16 Same as short int
long int 32 –2,147,483,647 to 2,147,483,647
signed long int 32 Same as long int
unsigned long int 32 0 to 4,294,967,295
long long int (C99) 64 –(2⁶³–1) to 2⁶³–1
unsigned long long int (C99) 64 0 to 2⁶⁴–1
float 32 1E–37 to 1E+37 (≈6 digits precision)
double 64 1E–37 to 1E+37 (≈10 digits precision)
long double 80 1E–37 to 1E+37 (≈10 digits precision)

3.3 Identifiers Names:

In C, the names we give to variables, functions, and other items are called identifiers.

An identifier must start with a letter or an underscore (_). After that, you can use
letters, numbers, or underscores. Identifiers are case-sensitive, so count, Count, and COUNT
are all different. You cannot use C keywords (like int, for, while) as identifiers, and you should
avoid using names of library functions.

Examples of correct identifiers are: count, test23, high_balance.


Examples of incorrect identifiers are: 1count, hi!there, high..balance.

There are two kinds of identifiers: external (like function names and global variables
that can be used across files) and internal (like local variables inside a function).

The length of identifiers also has limits. In C89, only the first 6 characters of external
identifiers and the first 31 characters of internal identifiers are important. In C99, this increased
to 31 characters for external and 63 for internal identifiers. In C++, up to 1,024 characters are
important.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -17


Programming In C (1BEIT105)

3.4 Variables:

A variable in C is a named memory location used to store a value that can change while the
program runs. Before using a variable, it must be declared with a data type and optional
modifiers. The general form of declaration is

type variable_list;,

where type is a valid data type and variable_list contains one or more variable names separated
by commas.

For example: int i, j, l;, short int si;, unsigned int ui;, or double balance, profit, loss;. The variable name
does not affect its type.

Where variables are declared

Variables can be declared in three places: inside a function (local variables), in function
parameters (formal parameters), or outside all functions (global variables).

Local variables:

In C, local variables are variables declared inside a function or a specific block of code, and
they can only be used within that block. These variables are sometimes called automatic
variables because they are created when the block is entered and destroyed when it is
exited. For example, in the two functions below:

void func1(void)
{
int x;
x = 10;
}
void func2(void)
{
int x;
x = -199;
}

The variable x in func1() is completely separate from the x in func2(). Each exists only while
its function is running and cannot affect the other. Local variables are automatically stored on
the stack, and their values are lost once the block ends. To keep a value between function
calls, you can use the static keyword.

Local variables can also be declared inside smaller blocks within a function. For example:
void f(void)
{
int t;
scanf("%d%*c", &t);
if(t == 1) {
char s[80]; // created only when 'if' block executes
printf("Enter name: ");

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -18


Programming In C (1BEIT105)

gets(s);
}
// s is not accessible here
}

Here, s exists only while the if block is running and disappears afterward. Declaring variables
inside the block that uses them helps prevent accidental changes from other parts of the code.

If a variable in an inner block has the same name as one in an outer block, the inner variable
hides the outer one temporarily. For example:

#include <stdio.h>
int main(void) {
int x;
x = 10;
if(x == 10) {
int x; // inner x hides outer x
x = 99;
printf("Inner x: %d\n", x);
}
printf("Outer x: %d\n", x);
return 0;
}

This prints:

Inner x: 99
Outer x: 10

The inner x is a separate variable, and once the block ends, the outer x becomes visible again.

In C89, all local variables must be declared at the start of a block. For example, the following
code causes an error in C89:

void f(void) {
int i;
i = 10;
int j; // error in C89
j = 20;
}

However, in C99 (and C++), you can declare local variables anywhere in a block before their
first use.

Local variables can also be initialized when declared. The value is assigned every time the
block is entered. For example:

#include <stdio.h>
void f(void);
int main(void) {

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -19


Programming In C (1BEIT105)

int i;
for(i = 0; i < 10; i++) f();
return 0;
}
void f(void) {
int j = 10;
printf("%d ", j);
j++; // this change is lost when function exits
}

This prints 10 ten times because j is re-created with the value 10 each time f() is called, and the
increment does not persist outside the function.

In C, when a function needs to use values passed to it, it declares formal parameters to receive
those values. Formal parameters are like local variables inside the function—they exist only
while the function runs and are destroyed when it exits. They are declared inside the
parentheses following the function name. For example:

int is_in(char *s, char c) {


while(*s)
if(*s == c) return 1;
else s++;
return 0;
}

Here, the function is_in() has two formal parameters: s (a string) and c (a character). The
function returns 1 if c is found in s and 0 otherwise. Although these parameters receive values
from the arguments passed to the function, they behave like normal local variables—you can
assign values to them or use them in expressions. Like all local variables, their content is lost
once the function finishes execution.

Global variables:

In C, global variables are declared outside all functions and can be used anywhere in the
program. They retain their values throughout the program’s execution. For example:

#include <stdio.h>
int count; /* global variable */

void func1(void);
void func2(void);

int main(void) {
count = 100;
func1();
return 0;
}

void func1(void) {
int temp;

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -20


Programming In C (1BEIT105)

temp = count;
func2();
printf("count is %d", count); /* prints 100 */
}

void func2(void) {
int count; /* local variable hides global */
for(count = 1; count < 10; count++)
putchar('.');
}

In this program, the variable count is global and can be used by main() and func1() even though
it is not declared inside them. However, func2() declares a local variable also named count.
Inside func2(), any reference to count refers only to the local variable, leaving the global
variable unchanged. Global variables are stored in a fixed memory area and are useful when
multiple functions need access to the same data. However, overusing global variables can lead
to memory waste and program errors, because changes in one part of the program can affect
other parts unexpectedly. It is generally better to use local variables unless a variable truly
needs to be shared across functions.

3.5 The four C Scopes:

1. File Scope – Identifiers declared outside all functions; visible throughout the entire
file (global variables).
2. Block Scope – Identifiers declared inside { } blocks; also includes function
parameters; local to the block.
3. Function Prototype Scope – Identifiers declared in a function prototype; visible only
within that prototype.
4. Function Scope – Labels used with goto; must be within the same function as the goto.

3.6 Type Qualifiers:

In C, type qualifiers control how variables can be accessed or modified. The two main
qualifiers in C89 are const and volatile (C99 adds restrict).

Const:

A variable declared as const cannot be changed by the program, although it can be initialized
with a value. For example:

const int a = 10;

Here, a cannot be modified in the program. The const qualifier is also useful in function
parameters to prevent the function from modifying data pointed to by a pointer.

For instance:

#include <stdio.h>
void sp_to_dash(const char *str);
int main(void) {

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -21


Programming In C (1BEIT105)

sp_to_dash("this is a test");
return 0;
}
void sp_to_dash(const char *str) {
while(*str) {
if(*str == ' ') printf("%c", '-');
else printf("%c", *str);
str++;
}
}

In this program, the const ensures that the string cannot be modified inside the function. If you
try to assign to *str, the compiler will produce an error, as shown in the incorrect example:

/* Incorrect version */
void sp_to_dash(const char *str) {
while(*str) {
if(*str == ' ') *str = '-'; // Error: cannot modify const
printf("%c", *str);
str++;
}
}

Many standard library functions, such as strlen(const char *str), also use const to prevent
modification of the input.

The volatile qualifier indicates that a variable’s value may change due to external events (like
hardware or system routines) not visible in the program. This prevents the compiler from
optimizing code in a way that assumes the variable is unchanged. For example:

const volatile char *port = (const volatile char *) 0x30;

This declaration ensures that the program cannot modify port (because of const), and the
compiler knows its value may change unexpectedly (because of volatile), preventing unwanted
optimizations or side effects.

3.7 Storage Class Specifiers

Storage class specifiers tell the compiler:

1. Where to store a variable (memory location)


2. How long it should exist (lifetime)
3. Where it can be accessed (scope)

C has 4 storage class specifiers:

auto

 Default for local variables inside a function.


 Stored in: Stack (temporary memory)

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -22


Programming In C (1BEIT105)

 Scope: Only inside the function/block


 Lifetime: Exists only while the function/block runs
 Example:

void func() {
auto int x = 10; // 'auto' is optional
printf("%d", x);
}

Register

 Suggests the compiler to store variable in CPU register for fast access.
 Stored in: CPU register (if available)
 Scope: Local to the block/function
 Lifetime: Only during function execution
 Example:

void func() {
register int speed = 100;
printf("%d", speed);
}

Static

 Extends the lifetime of a variable to the entire program, but the scope can still be
local.
 Stored in: Data segment
 Scope: Local to block (if declared inside a function) or global (if outside)
 Lifetime: Entire program execution
 Example (inside function):

void func() {
static int count = 0; // remembers value between function calls
count++;
printf("%d\n", count);
}

 Calling func() multiple times will increment count, instead of resetting to 0.

Extern

extern is used to tell the compiler:


“This variable exists somewhere else in the program, don’t allocate memory for it here.”

Declaration → tells the compiler the type & name of a variable.


Definition → allocates memory for the variable.
You can have many declarations but only one definition.
extern allows you to declare a variable without defining it.

Why do we need extern?

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -23


Programming In C (1BEIT105)

If you use a global variable before it’s defined in the same file.
If you want to share a global variable between multiple files.

#include <stdio.h>

int main(void) {
extern int first, last; // Declare variables defined later
printf("%d %d\n", first, last);
return 0;
}
// Define global variables
int first = 10, last = 20;

Example of Multiple Files

File1.c
// Define global variables
int x, y;
char ch;

int main(void) {
// Use variables
x = 5;
y = 10;
ch = 'A';
}

File2.c

// Declare the same variables using extern


extern int x, y;
extern char ch;

void func1(void) {
x = 123;
}
void func22(void) {
x = y / 10;
}
void func23(void) {
y = 10;
}

3.8 Variable Initialization:

 You can assign a value when declaring a variable.


👉 Example:
int a = 10;
char ch = 'a';
double balance = 123.23;

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -24


Programming In C (1BEIT105)

 Global and static variables → initialized only once, at program start.


o If not given a value → set to 0 automatically.
 Local variables → initialized each time the block (like a function) runs.
o If not initialized → contain garbage (unknown) values.

Example:

int x; // global → automatically 0


void main() {
int y; // local → garbage value
static int z; // static local → automatically 0
}

3.9 Constants in C

In C, constants are fixed values that do not change during program execution. They
represent literal values used directly in the code and can belong to any basic data type such
as int, char, float, or double. Constants are also called literals.

Character Constants

A character constant is a single character enclosed within single quotes (' '), such as 'a', '%',
or '5'. C also supports multibyte characters (for example 'xy') and wide characters, used for
large language character sets. Wide characters are defined using a prefix L, for example:

#include <stddef.h>
wchar_t wc;
wc = L'A'; // Wide character constant

Here, wchar_t is defined in <stddef.h> and is used for wide characters.

Integer and Floating-Point Constants

Integer constants are numbers without a decimal point, such as 10, -100, or 35000L.
Floating-point constants include a decimal point or are written in scientific notation, like
11.123, 4.34e–3, or 1.0.
By default:

 Integers are of type int


 Real numbers (with a decimal) are of type double

You can control the type using suffixes:

 U or u → unsigned integer
 L or l → long integer
 F or f → float
 L or l (after a decimal number) → long double

Examples:

int x = 123;

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -25


Programming In C (1BEIT105)

long int y = 35000L;


unsigned int z = 987u;
float f = 123.23F;
double d = 1.0;
long double ld = 1001.2L;

In C99, you can also use LL or ll for long long integers, e.g., 12345LL.

Hexadecimal and Octal Constants

C supports other number systems like:

 Octal (base 8) → starts with 0


 Hexadecimal (base 16) → starts with 0x or 0X

Examples:

int oct = 012; // 10 in decimal


int hex = 0x80; // 128 in decimal

Octal uses digits 0–7, and hexadecimal uses 0–9 and A–F (or a–f) to represent 10–15.

String Constants

A string constant is a sequence of characters enclosed in double quotes (" ").


Example:

printf("This is a test");

Strings are different from characters:

 'a' → character constant


 "a" → string constant (a string of one character)

In C, there is no separate string data type — strings are handled as arrays of characters
ending with \0 (null character).

Backslash (Escape) Character Constants

Some characters like newline or tab cannot be typed directly.


C provides escape sequences, which are special codes beginning with a backslash (\).

Example Program:

#include <stdio.h>
int main(void)
{
printf("\n\tThis is a test.");
return 0;
}

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -26


Programming In C (1BEIT105)

Output:

This is a test.

Explanation: \n moves to a new line, and \t adds a tab space before printing the text.

Code Meaning

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\" Double quote

\' Single quote

\\ Backslash

\v Vertical tab

\a Alert (beep)

\? Question mark

\N Octal constant (where N is octal)

\xN Hexadecimal constant (where N is hexadecimal)

3.10 Operators

C language has many built-in operators.


Operators are symbols that tell the compiler to perform some operation (like +, =, >, etc.).

There are 4 main types of operators:

Type Example Use


Arithmetic Operators +, -, *, /, % For mathematical operations
Relational Operators <, >, <=, >=, ==, != To compare values
Logical Operators &&, `
Bitwise Operators &, ` , ^, <<, >>, ~`

Other special ones include:

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -27


Programming In C (1BEIT105)

 Assignment operator (=) – assigns a value


 Increment/decrement (++, --)
 Conditional (?:), comma (,), etc.

Assignment Operator (=)

This operator assigns a value to a variable.

Syntax:

variable_name = expression;

✅ The left side must be a variable (something that can store a value).
✅ The right side can be:

 a constant (5)
 another variable (x)
 or an expression (a + b * 2)

lvalue and rvalue

You’ll often see these two words:

Term Meaning Example


"Left value" — something that can appear on left side of = (a x = 10; → x is an
lvalue
variable). lvalue
x = 10; → 10 is an
rvalue "Right value" — the value or expression on the right side.
rvalue

Type Conversion in Assignments


Sometimes the data types on both sides of = are different.

In that case:

C automatically converts the right side (expression) to the type of the left side (variable).

Example:
int x;
float f;
char ch;
ch = x; // int → char
x = f; // float → int
f = ch; // char → float
f = x; // int → float

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -28


Programming In C (1BEIT105)

What Happens in Each Line

Line 1 → ch = x;

 If x has more bits than ch (example: int → char),


only the lower 8 bits of x are stored in ch.
 If x value > 255 or < 0, the value “wraps around”.

Example:
If x = 260, then ch = 260 % 256 = 4.

Line 2 → x = f;

 Float → Int conversion.


 Fractional part is removed (truncated).
Example: if f = 3.14, then x = 3.

Line 3 → f = ch;

 Char → Float conversion.


 The ASCII or numeric value of ch is converted to a float.
Example: if ch = 'A', ASCII value is 65, so f = 65.0.

Line 4 → f = x;

 Int → Float conversion.


 The integer value is converted to floating-point format (no data loss unless the
number is huge).

Bit Loss during Conversions

When we convert between different sizes of variables, bits can be lost.

Example:

 int → char: only lower 8 bits kept, higher bits lost.


 long → int: may lose 16 or 32 bits depending on your system.

#include <stdio.h>
void main() {
int x = 300;
char ch;
float f;

ch = x; // Line 1: int → char


printf("ch = %d\n", ch); // prints 44 (because 300 % 256 = 44)

x = f = 3.14; // Line 2: float → int


printf("x = %d\n", x); // prints 3

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -29


Programming In C (1BEIT105)

f = ch; // Line 3: char → float


printf("f = %.2f\n", f); // prints 44.00

f = x; // Line 4: int → float


printf("f = %.2f\n", f); // prints 3.00
}

In C, you can assign values to multiple variables in a single line using multiple
assignments. This makes programs shorter and cleaner.

For example, the statement x = y = z = 0; assigns the value 0 to all three variables x, y,
and z.

Here, the assignment is done from right to left — first z gets 0, then y gets the value of
z (which is 0), and finally x gets the value of y (also 0). This method is commonly used in
professional programs when several variables need the same initial value.

C also provides a shorthand method called compound assignment (or shorthand assignment)
to simplify operations that modify a variable’s value. For example, instead of writing x = x +
10;, you can write x += 10;.

The operator += tells the compiler to add 10 to the current value of x and then store the result
back into x. Similarly, x = x - 100; can be written as x -= 100;.

Compound assignment operators exist for all arithmetic and bitwise binary operators, such as
-=, *=, /=, %=, &=, |=, ^=, <<=, and >>=. In general, any expression of the form var = var operator
expression can be rewritten as var operator = expression. These compound assignments make the
code shorter, easier to read, and are widely used in professionally written C programs.

Arithmetic Operators in C

C provides several arithmetic operators that perform mathematical calculations.


They work just like in normal mathematics and can be used with integers, characters, or
floating-point numbers.

List of Arithmetic Operators

Operator Action Example Result


+ Addition x+y Adds two numbers
- Subtraction or Unary minus x - y, -x Subtracts or changes sign
* Multiplication x*y Multiplies two numbers
/ Division x/y Divides one number by another
% Modulus x%y Gives the remainder after integer division
++ Increment x++ or ++x Increases value by 1
-- Decrement x-- or --x Decreases value by 1

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -30


Programming In C (1BEIT105)

How Division Works

When both operands are integers, division truncates the remainder (cuts off the decimal
part).

Example:

int x = 5, y = 2;
printf("%d", x / y);

Output → 2
(5 divided by 2 is 2.5, but integer division keeps only 2)

Modulus Operator (%)

The % operator gives the remainder after integer division.

Example:

int x = 5, y = 2;
printf("%d", x % y);

Output → 1
(5 divided by 2 leaves remainder 1)

#include <stdio.h>

int main() {
int x, y;
x = 5;
y = 2;

printf("%d ", x / y); // prints 2


printf("%d\n", x % y); // prints 1

x = 1;
y = 2;
printf("%d %d", x / y, x % y); // prints 0 1
return 0;
}

Unary Minus

The unary minus (-) changes the sign of a number.

Example:

int x = 5;
printf("%d", -x);

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -31


Programming In C (1BEIT105)

Output → -5

It simply multiplies the number by -1.

In C, the increment (++) and decrement (--) operators are special operators used to increase
or decrease the value of a variable by 1. They make programs shorter and more efficient.

For example, writing x = x + 1; can be simply written as ++x;, and x = x - 1; can be written as --x;.
T

hese operators can be used in two ways — as prefix (before the variable) or postfix (after the
variable).

When used as a prefix, like ++x, the variable is incremented first, and then its updated value is
used in the expression.

When used as a postfix, like x++, the current value of the variable is used first, and then it is
incremented. For example, if x = 10; y = ++x; then both x and y become 11. But if x = 10; y = x++;,
then y becomes 10 while x becomes 11 after the statement. The same logic applies to the
decrement operator (--x and x--).

C compilers handle increment and decrement operations very efficiently, often producing faster
code than equivalent assignment statements. Therefore, it is good practice to use ++ and --
whenever you need to increase or decrease a variable by one.

The precedence of arithmetic operators determines the order in which operations are
performed. The highest precedence is given to ++ and --, followed by the unary minus (-), then
the operators *, /, and %, and finally the lowest precedence goes to + and - (for addition and
subtraction). Operators that are on the same level of precedence are evaluated from left to
right. You can, however, use parentheses ( ) to change the order of evaluation. Parentheses
work in C just as they do in mathematics — the expressions inside them are evaluated first.

In summary, increment (++) and decrement (--) operators are powerful shorthand tools for
increasing or decreasing variable values efficiently, and understanding their prefix/postfix
behavior and precedence rules helps in writing correct and optimized C programs.

Relational and Logical Operators in C

In C, relational operators are used to compare two values and define the relationship between
them, while logical operators are used to combine or invert those relationships. These
operators form the basis of decision-making in C programs (such as in if, while, and for
statements).
In C, the concept of true and false is very important: any nonzero value is true, and zero is
false. The result of a relational or logical expression is either 1 (true) or 0 (false).

🔹 Relational Operators

The relational operators are:


> (greater than),

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -32


Programming In C (1BEIT105)

>= (greater than or equal to),


< (less than),
<= (less than or equal to),
== (equal to), and
!= (not equal to).
These operators compare two values and return true or false. For example, if a = 10 and b = 5,
then a > b is true and a == b is false.

🔹 Logical Operators

The logical operators in C are:


&& (logical AND),
|| (logical OR), and
! (logical NOT).
These connect multiple conditions. The AND operator && returns true only if both
conditions are true. The OR operator || returns true if any one of the conditions is true. The
NOT operator ! reverses the result of a condition — if a condition is true, ! makes it false, and
vice versa.

Example truth table:

| p | q | p && q | p || q | !p |
|---|---|--------|--------|----|
|0|0|0|0|1|
|0|1|0|1|1|
|1|0|0|1|0|
|1|1|1|1|0|

Example Expression:
10 > 5 && !(10 < 9) || 3 <= 4 → evaluates to true (1).

Both relational and logical operators have lower precedence than arithmetic operators. So, in
an expression like 10 > 1 + 12, the addition is done first (1 + 12 = 13), then the comparison (10 >
13), which results in false (0). Parentheses can be used to change the order of evaluation, e.g.,
(10 > 1) + 12 changes the result.

Example Program for Logical XOR

Although C doesn’t have a direct XOR logical operator, it can be created using existing
operators.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -33


Programming In C (1BEIT105)

#include <stdio.h>
int xor(int a, int b);

int main(void) {
printf("%d", xor(1, 0)); // Output: 1
printf("%d", xor(1, 1)); // Output: 0
printf("%d", xor(0, 1)); // Output: 1
printf("%d", xor(0, 0)); // Output: 0
return 0;
}
int xor(int a, int b) {
return (a || b) && !(a && b);
}

Explanation:
This function performs an exclusive OR (XOR) operation, which returns true only when
exactly one of the operands is true.

Bitwise Operators in C

C also supports bitwise operators, which operate on individual bits of integer data. They are
used in low-level programming, such as hardware control, encryption, and device drivers.
Bitwise operators cannot be used on float or double types.

Operator Action
& Bitwise AND
` `
^ Bitwise Exclusive OR (XOR)
~ One’s Complement (NOT)
<< Shift Left
>> Shift Right

Each operator works on each bit of the operands.


For example:

p q p ^ q (XOR)
000
101
011
110

Bitwise AND (&)

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -34


Programming In C (1BEIT105)

Used to clear bits. A bit is 1 only if both bits are 1.


Example:

char ch;
ch = read_modem(); // get a character
return (ch & 127); // clears the 8th bit

Here, ch & 127 forces the highest (8th) bit to 0.

Bitwise OR (|)

Used to set bits. If either bit is 1, the result bit is 1.


Example:
128 | 3 → sets high bits to 1.

🔸 Bitwise XOR (^)

Used to toggle bits — it sets a bit to 1 only when the bits are different.
Example:
127 ^ 120 results in a value where only differing bits are 1.

🔸 Bitwise Shift Operators (<< and >>)

Used to shift bits left or right.

 << shifts bits left, filling zeros on the right (multiplies by 2).
 >> shifts bits right, filling zeros on the left (divides by 2).
Bits shifted out are lost.

#include <stdio.h>
int main(void) {
unsigned int i = 1;
int j;

// Left shifts
for(j = 0; j < 4; j++) {
i = i << 1;
printf("Left shift %d: %d\n", j, i);
}

// Right shifts
for(j = 0; j < 4; j++) {
i = i >> 1;
printf("Right shift %d: %d\n", j, i);
}
return 0;
}

Explanation:
Each left shift multiplies i by 2, and each right shift divides it by 2.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -35


Programming In C (1BEIT105)

🔸 One’s Complement (~)

Reverses all bits — 1s become 0s and 0s become 1s.

Example:

char encode(char ch) {


return (~ch); // complements the bits
}

If you apply ~ twice, the value returns to its original form. This is sometimes used for simple
encryption.

Bit Shift Example Table

Statement Binary Value Decimal


x = 7; 00000111 7
x = x << 1; 00001110 14
x = x << 3; 01110000 112
x = x << 2; 11000000 192
x = x >> 1; 01100000 96
x = x >> 2; 00011000 24

Ternary operator ?

The ternary operator ? : is a conditional operator in C. It is used as a short form of the if–
else statement. It helps make code shorter and cleaner.

🔹 Syntax

condition ? expression_if_true : expression_if_false;

🔹 Working

1. The condition is first evaluated.


2. If the condition is true, the expression after ? is executed.
3. If the condition is false, the expression after : is executed.

🔹 Example 1

int x = 10;
int y;

y = x > 9 ? 100 : 200;

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -36


Programming In C (1BEIT105)

🔹 Equivalent if–else form

if (x > 9)
y = 100;
else
y = 200;

🔹 Example 2: Finding Maximum

int a = 20, b = 30;


int max;

max = (a > b) ? a : b;

Result:
max = 30 (since a > b is false)

🔹 Example 3

int num = 5;
printf("%s", (num % 2 == 0) ? "Even" : "Odd");

Output: Odd

Pointer?

 A pointer is a variable that stores the memory address of another variable.


 Instead of holding a value directly, a pointer holds where the value is stored in
memory.
 Example:
If variable x is stored at address 2000, then a pointer can store 2000 (the address of x).

Why Pointers are Useful

Pointers are very powerful in C because they:

 Allow functions to modify variables directly (by passing addresses).


 Make it easier to work with arrays and strings.
 Help in building dynamic data structures like linked lists, trees, etc.
 Increase efficiency of programs.

Pointer Operators in C

There are two main pointer operators:

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -37


Programming In C (1BEIT105)

Operator Name Meaning Example


Gives the address of a p = &x; → p gets
& Address-of operator
variable address of x
Value-at-address operator (or Gives the value stored y = *p; → y gets value
*
dereference operator) at the address at address p

Understanding & (Address-of Operator)

 & gives the memory address of a variable.


 Syntax:
 pointer_variable = &normal_variable;
 Example:
 int count = 100;
 int *m;
 m = &count; // m stores the address of count

Think of & as "address of"


If count is at location 2000, then m = 2000.

Understanding * (Value-at-address Operator)

 * is used to access the value stored at a memory address.


 It is called the dereference operator.
 Syntax:
 value_variable = *pointer_variable;
 Example:
 int q;
 q = *m; // q gets the value stored at address inside m

Think of * as "value at address"


If m = 2000 and location 2000 has value 100,
then *m = 100.

Declaring Pointer Variables

To declare a pointer, use * before the variable name:

int *ptr; // pointer to integer


char *ch; // pointer to character
float *fptr; // pointer to float

 Example:
 char *ch; // ch is not a character, but a pointer to a character

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -38


Programming In C (1BEIT105)

� The data type (like int, char, float) is called the base type of the pointer.
It tells the compiler what kind of data the pointer will point to.

Mixing Pointer and Non-Pointer Declarations

You can declare both in the same line:

int x, *y, count;

 x and count → normal integers


 y → pointer to integer

Example Program Using & and * Operators

#include <stdio.h>
int main(void)
{
int target, source; // normal integer variables
int *m; // pointer to integer

source = 10; // assign 10 to source

m = &source; // m now holds the address of source

target = *m; // *m means value stored at address m (i.e., value of source)

printf("%d", target); // prints 10

return 0;
}

Compile-Time Operator sizeof in C

 sizeof isa unary compile-time operator.


 It returns the size (in bytes) of:
o A variable, or
o A data type (written inside parentheses).

 Used to find how many bytes a variable or data type occupies in memory.
 Helps to make portable programs that can run correctly on different computer
systems.

🔹Syntax
sizeof variable_name
sizeof(type_name)

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -39


Programming In C (1BEIT105)

✅ Parentheses are required only when using a type name,


but optional when using a variable name.

Example
double f;
printf("%d ", sizeof f);
printf("%d", sizeof(int));

� Explanation:

 Suppose:
o sizeof(double) = 8 bytes
o sizeof(int) = 4 bytes
 Output:

84

Type Returned: size_t

 sizeof returns a value of type size_t.


 It is defined (using typedef) as an unsigned integer type.
 You can treat it like an unsigned int in most cases.

Example:

size_t s;
s = sizeof(int);
printf("%u", s);

#include <stdio.h>
int main(void)
{
int a;
double b;
char c;

printf("Size of int: %lu bytes\n", sizeof(a));


printf("Size of double: %lu bytes\n", sizeof(b));
printf("Size of char: %lu bytes\n", sizeof(c));
printf("Size of float: %lu bytes\n", sizeof(float));

return 0;
}

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -40


Programming In C (1BEIT105)

Comma Operator in C

The comma operator (,) allows you to combine multiple expressions into a single
statement. It evaluates each expression from left to [Link] value of the entire
expression is the value of the last expression in the sequence.

🔹Syntax
(expression1, expression2, expression3, ...);

✅ Each expression is separated by a comma.


✅ The last expression decides the final value.

🔹 Example
x = (y = 3, y + 1);

� Step-by-step:

1. y=3 → assigns 3 to y
2. y+1 → evaluates to 4
3. The last expression (y + 1) becomes the value of the whole expression
4. So, x = 4

✅ Final Values:

y=3
x=4

#include <stdio.h>
int main() {
int x, y;

x = (y = 3, y + 1); // y = 3 first, then x = y + 1


printf("x = %d, y = %d", x, y);

return 0;
}
✅ Output:

ini
Copy code
x = 4, y = 3

Another Example
#include <stdio.h>
int main() {
int a, b, c;

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -41


Programming In C (1BEIT105)

a = (b = 2, c = 5, b + c); // sequence: b=2 → c=5 → b+c


printf("a = %d", a);
return 0;
}

� Step-by-step:

 b=2
 c=5
 b+c=7 → this is the final value assigned to a.

✅ Output:

a=7

Structure is a collection of different data items (like int, float, char) all grouped together under one
name.

Dot (.) and Arrow (→) Operators in C

 Both . (dot) and -> (arrow) are structure member access operators.
 They are used to access individual members (fields) of a structure or union.

Operator Used With Meaning

. (Dot) Structure variable Access member directly

-> (Arrow) Pointer to a structure Access member through pointer

Example Structure
struct employee {
char name[80];
int age;
float wage;
};

Using the Dot (.) Operator

 Used when you have a structure variable.

struct employee emp;


[Link] = 123.23; // Accessing directly using dot

Using the Arrow (→) Operator

 Used when you have a pointer to a structure.

struct employee *p = &emp; // p points to emp

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -42


Programming In C (1BEIT105)

p->wage = 123.23; // Accessing using pointer

Shortcut Meaning

👉 p->wage is the same as (*p).wage


(but easier to read and write)

[ ] and ( ) Operators in C

Parentheses Operator

 Used to group expressions.


 It increases precedence, meaning the operations inside parentheses are done first.
 Also used in function calls and function declarations.

Example 1 — for precedence:

int a = (2 + 3) * 4; // (2 + 3) done first → result 20

Example 2 — for function call:

printf("Hello"); // ( ) used to pass arguments to a function

Square Bracket Operator

 Used for array indexing.


 Lets you access individual elements of an array.
 The value inside [ ] is called the index (it shows the position).
 Remember: Array index starts from 0.

Example:

char s[80]; // array of 80 characters

s[3] = 'X'; // puts 'X' into 4th element (index 3)


printf("%c", s[3]); // prints 'X'

s[3] means “the 4th element of array s”.

Example Program Explained


#include <stdio.h>
char s[80]; // array with 80 elements
int main(void)
{
s[3] = 'X'; // store 'X' in 4th element
printf("%c", s[3]); // print that element
return 0;
}

✅ Output → X

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -43


Programming In C (1BEIT105)

3.11 Expressions in C

An expression is any valid mix of variables, constants, operators, and functions


that produces a value.
Example:
x = a + b * c;

Here a + b * c is an expression.

Order of Evaluation

 In C, the compiler decides the order in which subexpressions are calculated.


 So, don’t depend on which part happens first.

Example:

x = f1() + f2();

It’s not guaranteed that f1() runs before f2().

Operator Precedence (Which Runs First)

| Highest → Lowest | Operator | Meaning |


|---------------------------|---------------|
| 1 | ( ), [ ], ->, . | Parentheses, array, structure access |
| 2 | !, ~, ++, --, (type), *, &, sizeof | Unary operators |
| 3 | *, /, % | Multiplication, division, remainder |
| 4 | +, - | Addition, subtraction |
| 5 | <<, >> | Shift left/right |
| 6 | <, <=, >, >= | Relational operators |
| 7 | ==, != | Equality operators |
| 8 | &, ^, |, &&, || | Bitwise/logical operators |
| 9 | ?: | Conditional |
| 10 | =, +=, -=, etc. | Assignment |
| 11 | , | Comma (lowest) |

Type Conversion (Type Promotion)

When you mix different data types in one expression, C automatically converts smaller
types to larger ones. This process is called Type Promotion.

Simple Example (as shown in your image)


char ch;
int i;
float f;
double d;

result = (ch / i) + (f * d) - (f + i);

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -44


Programming In C (1BEIT105)

Step-by-Step Conversion
1. ch / i →
o ch (char) becomes int
o result = int
2. f*d →
o float × double → result = double
3. f+i→
o int becomes float → result = float
4. Finally:
o int + double → result = double
o double - float → result = double

✅ Final result = double

Order of promotion:
char → int → float → double → long double

Cast Operator (type)


 Used to force a value into a specific data type.

Syntax:

(type) expression
� Example:
(float) x / 2 // forces x to be float before division
Without (float), division between integers would cut off fractions.
Program Example
#include <stdio.h>
int main(void) {
int i;
for(i = 1; i <= 5; i++)
printf("%d / 2 = %f\n", i, (float)i / 2);
return 0;
}

✅ Output:
1 / 2 = 0.500000
2 / 2 = 1.000000
3 / 2 = 1.500000

Parentheses and Spacing

 Parentheses make expressions clear and easier to read.


 Adding extra spaces doesn’t change meaning.

� Example:

x = (y / 3) - (34 * temp) + 127;

✔� Easier to understand than → x = y/3-34*temp+127;

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -45


Programming In C (1BEIT105)

Module 1 Question Bank


1. Explain the different types of computer languages
2. Describe the steps involved in creating and running a C program.
3. Explain the phases of system development and the role of a programmer in each
phase.
4. Explain the program development process using structure chart, pseudocode, and
flowchart
5. Explain the structure of a C program with an example program.
6. Write a brief history of the C language. Explain its evolution from BCPL and B
language.
7. Why is C called a middle-level and structured programming language? Give reasons
with examples.
8. “C is a programmer’s language.” Justify this statement.
9. List and explain the basic data types and type modifiers in C.
10. Define variables and explain the difference between local, global, and static
variables.
11. Explain the four scopes and storage classes (auto, register, static, extern) with
examples.
12. What are type qualifiers? Explain const, volatile, and restrict.
13. Define variable initialization. Differentiate between initialization of global, static,
and local variables.
14. What are constants in C? Explain integer, floating-point, character, string, and
escape sequence constants.
15. Explain type conversion in assignments with examples.
16. List and explain arithmetic, relational, and logical operators with examples.
17. Explain bitwise, conditional (?:), and comma ( , ) operators with suitable examples.
18. Discuss operator precedence and associativity in C with an example.

Mrs Pallavi CS Dept. of Data Science AIT, Chikkamagaluru. Page -46

You might also like