0% found this document useful (0 votes)
2 views28 pages

Programming C Module 1 Notes

The document provides a comprehensive overview of programming in C, covering fundamental concepts such as hardware and software, types of software, programming languages, algorithms, and flowcharts. It details the structure of a C program, the process of writing, compiling, and executing C programs, as well as preprocessor directives and the stages involved in program execution. Additionally, it highlights the characteristics and uses of the C programming language, emphasizing its significance in software development.

Uploaded by

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

Programming C Module 1 Notes

The document provides a comprehensive overview of programming in C, covering fundamental concepts such as hardware and software, types of software, programming languages, algorithms, and flowcharts. It details the structure of a C program, the process of writing, compiling, and executing C programs, as well as preprocessor directives and the stages involved in program execution. Additionally, it highlights the characteristics and uses of the C programming language, emphasizing its significance in software development.

Uploaded by

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

Programming in C

Detailed Study Notes with Simple Examples


Programming Fundamentals
1. Introduction to Computer Software
A computer is made up of two main parts: hardware and software. Hardware refers to the physical parts of a
computer that we can touch, such as the keyboard, monitor, mouse, and the CPU (Central Processing Unit).
Software, on the other hand, is a set of instructions, data, or programs that tell the hardware what to do and how to
do it. Software cannot be touched; it can only be seen and used through the hardware.

In simple words: Hardware is the "body" of the computer, and Software is the "mind" that tells the body what to
do.

Example: Think of a computer like a music player.


• The music player (device) is the hardware.
• The songs and the app that plays them are the software.
Without software, hardware is just a lifeless machine that cannot perform any useful task.

2. Classification of Computer Software


Computer software is broadly classified into two categories: System Software and Application Software.

2.1 System Software


System software manages and controls the computer hardware so that application software can perform its task. It
acts as an interface between the user, the application software, and the computer hardware. It runs in the
background and is essential for the computer to function at all.

• Operating System (OS): Manages hardware resources and provides services to application programs.
Example: Windows, Linux, macOS, Android.
• Device Drivers: Small programs that allow the OS to communicate with hardware devices like printers,
keyboards, and graphic cards.
• Utility Software: Helps maintain and optimize the computer, such as antivirus programs, disk cleanup
tools, and file compression tools.
• Language Translators/Processors: Convert programs written in high-level languages into machine
language (compilers, interpreters, assemblers).

2.2 Application Software


Application software is designed to help the user perform specific tasks. Unlike system software, it directly
interacts with the user to accomplish everyday jobs.

• Word Processors: Used to create and edit text documents. Example: Microsoft Word.
• Spreadsheet Software: Used for calculations and data analysis. Example: Microsoft Excel.
• Web Browsers: Used to access the internet. Example: Google Chrome, Mozilla Firefox.
• Media Players: Used to play audio and video files. Example: VLC Media Player.
• Games and Educational Software: Used for entertainment and learning.

Example: Everyday comparison


When you switch on a computer, the Operating System (system software) starts running first. Once it is ready,
you can open MS Word (application software) to type an assignment. Without the Operating System running in
the background, MS Word could not even open.

Basis System Software Application Software

Purpose Manages computer hardware and Helps user perform specific tasks
resources

Dependency Can run independently of application Cannot run without system software
software

Example Windows, Linux MS Word, Excel, Chrome

Interaction Works mostly in the background Directly used by the end user

3. Programming Languages
A programming language is a set of rules and symbols used to write instructions (programs) that a computer can
understand and execute. Just as humans use languages like English or Hindi to communicate, programmers use
programming languages to communicate with computers.

Programming languages are broadly classified into three categories based on their closeness to human language or
machine language:

3.1 Machine Language (Low-Level Language)


This is the most basic language, written using only 0s and 1s (binary code). It is directly understood by the
computer's hardware without any translation, but it is very difficult for humans to read or write.

Example: Machine language instruction

10110000 01100001
This binary code might instruct the processor to move a value into a register, but it is nearly impossible for a
human to understand at a glance.

3.2 Assembly Language (Low-Level Language)


Assembly language uses short English-like abbreviations called mnemonics (such as ADD, SUB, MOV) instead
of binary numbers. It is easier for humans to read than machine language, but it still needs to be translated into
machine language using a program called an Assembler.

Example: Assembly language instruction

MOV A, 5
ADD A, 3
This means: move the value 5 into register A, then add 3 to it.

3.3 High-Level Language


High-level languages are written in a manner very close to human (English-like) language, making them easy to
learn, write, and understand. They must be translated into machine language using a Compiler or Interpreter
before the computer can run them. C, C++, Java, and Python are all examples of high-level languages.

Example: High-level language instruction (C language)

printf("Hello, World!");
This single line simply tells the computer to display the message "Hello, World!" on the screen. It reads almost
like a plain English instruction.

Feature Machine Language Assembly Language High-Level Language

Readability Very hard (binary) Moderate (mnemonics) Easy (English-like)

Speed of execution Fastest Fast Slower (needs translation)

Translator needed None Assembler Compiler/Interpreter

Example 01001010 MOV A, B C, Python, Java

4. Algorithms and Flowcharts


4.1 Algorithm
An algorithm is a step-by-step set of instructions written in plain language to solve a specific problem. It is like a
recipe: it lists every step needed to reach the final result, in the correct order. A good algorithm should be clear,
finite (it must end after a limited number of steps), and should produce the correct output.

Example: Algorithm to add two numbers


1. Start
2. Take two numbers as input, say A and B
3. Add A and B, and store the result in SUM
4. Display SUM
5. Stop

Example: Algorithm to find the largest of two numbers


6. Start
7. Read two numbers A and B
8. If A is greater than B, then display A as the largest
9. Otherwise, display B as the largest
10. Stop

4.2 Flowchart
A flowchart is the pictorial (diagrammatic) representation of an algorithm. It uses standard symbols/shapes to
represent different types of steps, and arrows to show the flow of control from one step to the next. Flowcharts
make it easier to visualize the logic of a program before actually writing the code.
Common Flowchart Symbols
Symbol Shape Name Purpose

Oval/Ellipse Terminator Represents the Start or End of the


flowchart

Parallelogram Input/Output Represents input taken from user or


output displayed

Rectangle Process Represents a processing step, e.g., a


calculation

Diamond Decision Represents a yes/no or true/false


decision point

Arrow Flow line Shows the direction/order of execution

Example: Flowchart to add two numbers (described in words, since a flowchart is drawn using shapes)
• Start (Oval)
• Input A, B (Parallelogram)
• Compute SUM = A + B (Rectangle)
• Display SUM (Parallelogram)
• End (Oval)
Each of these steps would be connected by arrows in a real flowchart, showing that the program moves from
Start, to taking input, to processing, to showing output, and finally to End.
Basics of C Programming
1. Introduction to C
C is a general-purpose, high-level programming language that was developed by Dennis Ritchie at AT & TBell
Laboratories in 1972. It was originally created to develop the UNIX operating system. C is often called the
"mother of all programming languages" because many later languages such as C++, Java, and Python borrowed
heavily from its syntax and concepts.

1.1 Characteristics of C
• Simple and Efficient: C has a small set of keywords and a simple syntax, making it easy to learn and fast
to execute.
• Structured Language: A C program can be broken down into smaller parts called functions, making the
code organized and easy to manage.
• Portable: A C program written on one type of computer can be run on another type of computer with little
or no modification.
• Rich Library Support: C provides a large number of built-in functions (like printf, scanf) to perform
common tasks.
• Middle-Level Language: C combines the features of both high-level languages (easy to understand) and
low-level languages (direct hardware access), which is why it is often called a middle-level language.
• Case-Sensitive: In C, "Sum" and "sum" are treated as two completely different names.

1.2 Uses of C
Mainly C Language is used to Develop Desktop application and system software. Some
applications of C language are given below.
• C programming language can be used to design the system software like operating system
and Compiler.
• To develop application software like database and spread sheets.
• For Develop Graphical related application like computer and mobile games.
• To evaluate any kind of mathematical equation, use c language.
• C programming language can be used to design the compilers.
• UNIX Kernel is completely developed in C Language.
• For Creating Compilers of different Languages which can take input from other language
and convert it into lower-level machine dependent language.
• C programming language can be used to design Operating System.
• C programming language can be used to design Network Devices.
• To design GUI Applications. Adobe Photoshop, one of the most popularly used photo editors since
olden times, was created with the help of C.

2. Structure of a C Program
Every C program follows a fixed general structure. Understanding this structure helps beginners know exactly
where to write each part of their code.
Section Purpose

Documentation/Comments Describes what the program does (optional but good


practice)

Preprocessor Directives Instructions to the preprocessor, e.g. #include, #define

Global Declarations Variables or functions declared outside main(), usable


anywhere in the program

main() Function The starting point of every C program; execution always


begins here

Local Declarations & Statements Variables and instructions inside main() or other functions

return Statement Ends the function and optionally sends a value back

Example: A simple C program showing the complete structure

#include <stdio.h> // Preprocessor directive

int main() // main function: entry point


{
printf("Hello, World!"); // Statement: prints text
return 0; // Ends the program successfully
}

Output:
Hello, World!
Here, #include <stdio.h> tells the compiler to include the Standard Input Output library so that functions like
printf() can be used. The main() function is where the program execution starts and ends. Everything inside the
curly braces { } is the body of the function.

Comment line

It indicates the purpose of the program. It is represented as /*……………………………..*/ Comment line is used
for increasing the readability of the program. It is useful in explaining the program and generally used for
documentation. It is enclosed within the decimeters. Comment line can be single or multiple line but should not
be nested. It can be anywhere in the program except inside string constant & character constant.

Preprocessor Directive:

#include tells the compiler to include information about the standard input/output library. It is also used in
symbolic constant such as #define PI 3.14(value). The stdio.h (standard input output header file) contains
definition &declaration of system defined function such as printf( ), scanf( ), pow( ) etc. Generally printf()
function used to display and scanf() function used to read value.

Global Declaration:

This is the section where variables are declared globally so that it can be access by all the functions used in the
program. And it is generally declared outside the function.

main() It is the user defined function and every function has one main() function from where actually program is
started and it is encloses within the pair of curly braces. The main( ) function can be anywhere in the program but
in general practice it is placed in the first position. Syntax : main() { …….. …….. …….. } The main( ) function
return value when it declared by data type as int main( ) { return 0

} The main function does not return any value when void (means null/empty) as void main(void ) or void main() {
printf (“C language”); } Output: C language

The program execution starts with opening braces and end with closing brace.

/*First c program with return statement*/ #include int main (void) { printf ("welcome to c Programming
language.\n"); return 0; } Output: welcome to c programming language.

3. Writing, Compiling and Executing a C Program


Creating a working C program involves three main stages:

3.1 Writing the Program


The programmer writes the source code using a text editor or an Integrated Development Environment (IDE) such
as Turbo C, Code::Blocks, or VS Code. This file is saved with a .c extension, for example, hello.c.

3.2 Compiling the Program


A compiler is a software program that analyzes a program developed in a particular computer language and then translates it
into a form that is suitable for execution on a particular computer system. Figure below shows the steps that are involved in
entering, compiling, and executing a computer program developed in the C programming language and the typical Unix
commands that would be entered from the command line.
The compiler checks the source code for errors (such as spelling mistakes in keywords or missing semicolons)
and translates it into machine language, producing an object file. If there are errors, the compiler lists them, and
the programmer must fix them before proceeding.

3.3 Executing the Program


Once compiled successfully, the machine code is linked with any required libraries to create an executable file
(e.g., [Link]). Running this file executes the program, and the output is displayed to the user.

4. Preprocessor Directives
Preprocessor directives are special instructions that are processed by the preprocessor before the actual
compilation of the program begins. They always start with a hash symbol (#) and do not end with a semicolon.

• #include: Used to include the contents of a header file (a file containing predefined functions) into the
program. Example: #include <stdio.h>
• #define: Used to define a constant or a macro. Example: #define PI 3.14

Example: Using #define

#include <stdio.h>
#define PI 3.14 // PI is now a constant value

int main()
{
float radius = 5;
float area = PI * radius * radius;
printf("Area = %f", area);
return 0;
}

Output:
Area = 78.500000
Wherever PI appears in the program, the preprocessor simply replaces it with 3.14 before compilation starts.

5. Processes Involved in Program Execution


Before a C program written in human-readable code can actually run on a computer, it passes through several
stages. These are: Compilation, Interpretation, Loading, and Linking.

5.1 Compilation
Compilation is the process of converting the entire high-level source code (written by the programmer) into
machine code (object code) all at once, before execution begins. A special program called the Compiler performs
this task. If there is even one error in the code, the compiler will not produce the final output until it is fixed. C
programs are typically compiled languages.

5.2 Interpretation
Interpretation is an alternative method where the source code is translated and executed line-by-line, rather than
all at once. A program called an Interpreter reads one instruction, executes it immediately, then moves to the next.
This makes debugging easier but generally makes execution slower compared to compiled programs. (Languages
like Python typically use interpretation, while C mainly uses compilation.)

5.3 Loading
Loading is the process of copying the executable program from secondary storage (like a hard disk) into the
computer's main memory (RAM) so that the CPU can access and execute its instructions. A system program
called the Loader performs this job.

5.4 Linking
Linking is the process of combining the object code of the program with the object code of any library functions it
uses (such as printf or scanf), to create a single executable file. A program called the Linker performs this task.
For example, when a program uses printf(), the linker connects the program's object code with the pre-compiled
code of the printf() function from the C standard library.

Stage Performed By What Happens

Compilation Compiler Converts source code to


object/machine code, checking for
errors

Interpretation Interpreter Translates and executes code line by


line (alternative to compiling)
Stage Performed By What Happens

Linking Linker Combines object code with library


functions to form an executable

Loading Loader Loads the executable file into main


memory (RAM) for execution

6. Comments, Keywords and Identifiers


6.1 Comments
Comments are notes written by the programmer to explain the code. They are completely ignored by the compiler
and are meant only for humans reading the program. C supports two types of comments:

• Single-line comment: starts with // and continues till the end of the line.
• Multi-line comment: starts with /* and ends with */, and can span multiple lines.

Example: Using comments

// This program adds two numbers

/* This is a multi-line comment


explaining that the program
simply displays a message */

#include <stdio.h>
int main()
{
printf("Learning C is fun!");
return 0;
}

6.2 Keywords
Keywords are reserved words that have a special, fixed meaning in the C language. They cannot be used as
variable names because the compiler already understands them as part of the language's syntax. C has 32
keywords in total. Some commonly used ones are:

Keyword Meaning

int Declares an integer variable

float Declares a floating-point (decimal) variable

char Declares a character variable

if / else Used for decision making

for, while Used for loops (repeating instructions)

return Returns a value from a function

6.3 Identifiers
Identifiers are the names given by the programmer to variables, functions, arrays, and other user-defined items.
They must follow certain rules:

• Can contain letters, digits, and underscore (_), but must start with a letter or underscore, not a digit.
• Cannot be a keyword (e.g., you cannot name a variable int).
• Cannot contain spaces or special symbols like @, #, %.
• C is case-sensitive, so Total and total are different identifiers.
• first characters should be alphabet or underscore
Identifiers are generally given in some meaningful name such as value, net_salary, age, data etc. An identifier name
may be long, some implementation recognizes only first eight characters, most recognize 31 characters. ANSI
standard compiler recognize 31 characters. Some invalid identifiers are 5cb, int, res#, avg no etc.

Example: Valid and invalid identifiers


Identifier Valid? Reason

studentAge Valid Starts with a letter, no special symbols

_count Valid Starts with an underscore

2ndValue Invalid Starts with a digit

total marks Invalid Contains a space

float Invalid It is a reserved keyword

7. Basic Data Types


A data type tells the compiler what kind of value a variable will hold, and how much memory space to allocate for
it.

 Data types in the C programming language are used to specify what kind of value can be stored in a variable.
 The memory size and type of the value of a variable are determined by the variable data type.
 In the c programming language, data types are classified as
follows...
 Primary Data Types: The primary/primitive data types in the C programming language are the basic data
types. All the primary data types are already defined in the system. Primary data types are also called as Built-
In data types.
Integer: We use the keyword "int" to represent integer data type in c.
• We use the keyword int to declare the variables and to specify the return type of a function.
• The integer data type is used with different type modifiers like Short (2bytes), long (4 bytes), signed (2bytes)
and unsigned (2bytes).
The access specifier for integer data type is %d.
Float: Floating-point data types are a set of numbers with the decimal value. Every floating-point value must
contain the decimal value. The floating-point data type has two variants: Float and double
 We use the keyword "float" to represent floating-point (4 bytes) datatype and "double" to represent double (8
bytes) data type in c.
 The float value contains 6 decimal places whereas double value contains 15 or 19 decimal places.
 The access specifier for float is %f and double is %ld

Character data type


 The character (1 byte) data type is a set of characters enclosed in single
quotations. We use the keyword char.
 The access specifier for character type is %c.
Example: Declaring variables of different data types

int age = 20; // whole number


float price = 99.5; // decimal number
char grade = 'A'; // single character
Note: Character values are always written inside single quotes, like 'A', while whole numbers and decimals are
written without any quotes.

void data type


The void data type means nothing or no value. Generally, the void is used to specify a function which does not
return any value. We also use the void data type to specify empty parameters of a function.
Enumerated data type
An enumerated data type is a user-defined data type that consists of integer constants and each integer constant is
given a name. The keyword "enum" is used to define the enumerated data type.
Derived data types
Derived data types are user-defined data types. The derived data types are also called as user-defined data types or
secondary data types. In the c programming language, the derived data types are created using the following
concepts...
 Arrays
 Structures
 Unions

8. Variables
A variable is an object whose value can change while a programme is running. A variable is a name given to a
memory location that is used to store a value which can change (vary) during program execution. Before using a
variable, it must be declared with a data type, telling the compiler what kind of value it will hold.

Each variable has a memory location or address assigned to it, and the value of that variable is stored there. Each
variable has its own name, data type, size, and value. All variables must have a type so that the compiler can
record all necessary information about them, generate the appropriate code during translation, and allocate the
necessary memory space.
Rules for Constructing Variable Name in C language are listed below:

1. Variable name may be a combination of alphabets, digits or underscores. Sometimes, an additional constraint
on the number of characters in the name is imposed by compilers in which case its length should not exceed 8
characters.
2. First character must be an alphabet or an underscore (_).
3. No commas or blank spaces are allowed in a variable name.
4. Among the special symbols, only underscore can be used in a variable name. E.g.: emp_age, item_4, etc.
5. No word, having a reserved meaning in C can be used for variable name

Syntax:
data_type variable_name;
Example
int marks, total;
float salary;
char ch;
Example: Declaring and using variables

#include <stdio.h>
int main()
{
int marks; // declaration
marks = 85; // assigning a value
printf("Marks = %d", marks);
return 0;
}

Output:
Marks = 85
Here, marks is a variable of type int. It first holds no meaningful value (declaration), and then we store 85 into it
(assignment). Later in the program, this value can even be changed, for example, marks = 90;

9. Constants
A constant is a value that does not change during the execution of the program. Unlike a variable, once a constant
is set, it cannot be modified later. Constants can be created in two common ways:

• Using #define (a preprocessor directive):


• Syntax: #define CONSTANT_NAME value
Example: #define PI 3.14159
#define MAX_USERS 100
• Using the const keyword:
The declaration for a constant in C language takes the following form:
Syntax: const data_type constant_name = value;
Example: const double PI = 3.14159;
const int MAX_USERS = 100;

Example: Using a constant with the const keyword

#include <stdio.h>
int main()
{
const int daysInWeek = 7;
printf("Days in a week = %d", daysInWeek);
// daysInWeek = 10; // This line would cause an ERROR
return 0;
}

Output:
Days in a week = 7

10. Input/Output Statements in C


Input/output statements allow a C program to interact with the user by taking data in (input) and displaying results
(output). The two most commonly used functions are scanf() for input and printf() for output, both provided
through the stdio.h header file.

Formatted Input/Formatted Output In this category, we have functions that allow input and output operations to be
performed in a fixed format.

Printf() and scanf() are the two most commonly used functions for formatted I/O. (). The printf() function is used
to view formatted data items on a standard output device, such as a monitor, while the scanf() function is used to
read formatted data input from a standard input device, such as a keyboard.

10.1 printf() - for Output


The printf() in one of the most important and useful functions to display data on monitor. It is used to display text,
numbers, or the values of variables on the screen. It uses special format specifiers to indicate the type of data
being printed, such as %d for integers, %f for floating-point numbers, and %c for characters.

Syntax: printf(“Format string”, arg1, arg2,...., argn);

Example: printf(“\n the sum of %d and %d is %d.”, a, b, c);

Where format string refers to a string in enclosed in double quotes that contain formatting information and arg1,
arg2, ...., argn are arguments (may be constants, variable, or other complex expressions) whose values are
formatted and printed according to the specification of the format string.
10.2 scanf() - for Input
scanf() is used to take input from the user through the keyboard and store it in a variable. It requires an ampersand
(&) before the variable name, which tells the compiler the memory address where the entered value should be
stored.

Syntax: scanf(“ format string”, arg1, arg2,.......argn);`

Example: scanf(“ %d %d”, &a, &b);

Example: A program that takes input and displays output

#include <stdio.h>
int main()
{
int age;
printf("Enter your age: "); // output: asking for input
scanf("%d", &age); // input: storing entered value
printf("You are %d years old.", age); // output: showing result
return 0;
}

Output:
Enter your age: 19
You are 19 years old.

Format Specifier Used For

%d Integer (int)

%f Floating-point number (float)

%c Single character (char)

%s String (a sequence of characters)

%lf Double (double)

Reading and Writing a Character


Unformatted console I/O functions don’t allow input and output to be formatted as per the user
requirements. In this category, we have:
1. Character I/O functions
2. String I/O functions
Character I/O functions are functions that programme input/output of one character at a time.
Since they deal with individual character values, these are the most basic I/O functions. To enter a
character from the keyboard, use the following functions:
1. getchar()
2. getch()
3. getche()
Whereas the output of a character as the monitor, the following functions can be used:
1. putchar()
2. putch()

#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
c = getchar();
putchar(c);
}
Character I/O functions have a drawback in that they can only handle one character at a time.
Strings, on the other hand, are commonly used in real-world programmes. A string is nothing more
than a set of characters. String I/O functions are functions that make it easier to move strings
between a computer and regular I/O devices. Following function can be used for handling strings
I/O:
1. gets()
2. puts()
Program for gets ()
#include<stdio.h>
void main ()
{
char s[25];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}

#include <stdio.h>
void main( )
{
char name[10];
printf(“Enter Name”);
gets(name);
printf("Entered name is");
puts(name);
return 0;
}

Difference between Formatted and Unformatted Functions


• Formatted input and output functions contain format specifier in their syntax.
• Unformatted input and output functions do not contain format specifier in their syntax.
• printf() and scanf() are examples for formatted input and output functions.
• getchar(), gets(), puts(), putchar() etc. are examples of unformatted input output functions.

11. Operators in C
An operator is a symbol that tells the compiler to perform a specific mathematical, relational, logical, or other
operation between operands (values or variables). C provides several categories of operators. Each type is
explained below with its own table and a complete, runnable example program.

C operators can be classified into a number of categories.


• Unary operator
• Binary operator
• Arithmetic operators
• Relational operators
• Logical operators
• Conditional operators
• Assignment operators
• Bitwise operators
• Increment and decrement operators
• Special operators

Unary operator
Unary operators are operators that act upon a single operand to produce a new value.

There are following types unary operators in C

Binary operators
Binary operators are those that operate on two operands. For example, a + b—the addition operator
(+) surrounded by two operands—is a popular binary expression. Arithmetic, relational, logical,
and assignment operators are all subsets of binary operators.
11.1 Arithmetic Operators
Used to perform basic mathematical calculations between two operands.

Operator Meaning Example (a=10, b=3) Result

+ Addition a+b 13

- Subtraction a-b 7

* Multiplication a*b 30

/ Division a/b 3 (integer division)

% Modulus (remainder) a%b 1

Example: Program using arithmetic operators

#include <stdio.h>
int main()
{
int a = 10, b = 3;
printf("Sum = %d\n", a + b);
printf("Difference = %d\n", a - b);
printf("Product = %d\n", a * b);
printf("Quotient = %d\n", a / b);
printf("Remainder = %d\n", a % b);
return 0;
}

Output:
Sum = 13
Difference = 7
Product = 30
Quotient = 3
Remainder = 1

11.2 Relational (Comparison) Operators


Used to compare two values. The result of a relational expression is always either 1 (true) or 0 (false).

Operator Meaning Example (a=10, b=3) Result

== Equal to a == b 0 (false)

!= Not equal to a != b 1 (true)

> Greater than a>b 1 (true)

< Less than a<b 0 (false)

>= Greater than or equal to a >= b 1 (true)

<= Less than or equal to a <= b 0 (false)

Example: Program using relational operators

#include <stdio.h>
int main()
{
int a = 10, b = 3;
printf("a == b : %d\n", a == b);
printf("a != b : %d\n", a != b);
printf("a > b : %d\n", a > b);
printf("a < b : %d\n", a < b);
printf("a >= b : %d\n", a >= b);
printf("a <= b : %d\n", a <= b);
return 0;
}

Output:
a == b : 0
a != b : 1
a>b :1
a<b :0
a >= b : 1
a <= b : 0
Note: relational operators are most often used inside if statements and loops to make decisions, e.g., if (a > b)
{ ... }

11.3 Logical Operators


Used to combine two or more conditions into a single true/false result. Commonly used inside if statements when
more than one condition must be checked together.

Operator Meaning Example

&& Logical AND — true only if both (a>5 && b>1)


conditions are true

|| Logical OR — true if at least one (a>5 || b>10)


condition is true

! Logical NOT — reverses true to false !(a>5)


and false to true

Example: Program using logical operators

#include <stdio.h>
int main()
{
int age = 20;
int hasID = 1; // 1 means true, 0 means false

printf("AND : %d\n", (age >= 18 && hasID == 1));


printf("OR : %d\n", (age >= 18 || hasID == 0));
printf("NOT : %d\n", !(age >= 18));
return 0;
}

Output:
AND : 1
OR : 1
NOT : 0
Here, age >= 18 is true (1) and hasID == 1 is true (1), so AND gives 1. Since at least one side of OR is true, OR
also gives 1. NOT simply flips the true result of (age >= 18) to 0.

11.4 Assignment Operators


The basic assignment operator (=) stores a value into a variable. C also provides shorthand compound assignment
operators that combine an arithmetic operation with assignment in one step.

Operator Meaning Example Same As

= Assign a=5 a=5

+= Add and assign a += 3 a=a+3

-= Subtract and assign a -= 3 a=a-3

*= Multiply and assign a *= 3 a=a*3

/= Divide and assign a /= 3 a=a/3


Operator Meaning Example Same As

%= Modulus and assign a %= 3 a=a%3

Example: Program using assignment operators

#include <stdio.h>
int main()
{
int a = 10;
a += 5; printf("After += : %d\n", a); // 15
a -= 3; printf("After -= : %d\n", a); // 12
a *= 2; printf("After *= : %d\n", a); // 24
a /= 4; printf("After /= : %d\n", a); // 6
a %= 4; printf("After %%= : %d\n", a); // 2
return 0;
}

Output:
After += : 15
After -= : 12
After *= : 24
After /= : 6
After %= : 2

11.5 Increment and Decrement Operators


These special unary operators increase (++) or decrease (--) the value of a variable by 1. They can be used in two
forms:

• Pre-increment/decrement (++a or --a): the value is changed first, then used in the expression.
• Post-increment/decrement (a++ or a--): the value is used in the expression first, then changed.

Example: Program showing the difference between pre and post increment

#include <stdio.h>
int main()
{
int a = 5, b = 5;
printf("Post-increment: %d\n", a++); // prints 5, then a becomes 6
printf("a after post-increment: %d\n", a);

printf("Pre-increment: %d\n", ++b); // b becomes 6 first, then prints 6


printf("b after pre-increment: %d\n", b);
return 0;
}

Output:
Post-increment: 5
a after post-increment: 6
Pre-increment: 6
b after pre-increment: 6

11.6 Bitwise Operators


Bitwise operators work directly on the individual bits (0s and 1s) of integer values. These are used in low-level
programming tasks such as embedded systems, encryption, and performance-critical code.

Operator Meaning Example (a=6, b=3) Binary Working

& Bitwise AND a&b=2 0110 & 0011 = 0010

| Bitwise OR a|b=7 0110 | 0011 = 0111

^ Bitwise XOR a^b=5 0110 ^ 0011 = 0101

~ Bitwise NOT (complement) ~a = -7 Flips every bit of a

<< Left shift a << 1 = 12 0110 shifted left = 1100

>> Right shift a >> 1 = 3 0110 shifted right = 0011

Example: Program using bitwise operators

#include <stdio.h>
int main()
{
int a = 6, b = 3; // a = 0110, b = 0011 in binary
printf("a & b = %d\n", a & b);
printf("a | b = %d\n", a | b);
printf("a ^ b = %d\n", a ^ b);
printf("~a = %d\n", ~a);
printf("a << 1 = %d\n", a << 1);
printf("a >> 1 = %d\n", a >> 1);
return 0;
}

Output:
a&b =2
a|b =7
a^b =5
~a = -7
a << 1 = 12
a >> 1 = 3

11.7 Conditional (Ternary) Operator


The ternary operator ?: is a shorthand way of writing a simple if-else statement in a single line. It is the only
operator in C that takes three operands, hence the name "ternary". Its general form is:

condition ? valueIfTrue : valueIfFalse;

Example: Program using the ternary operator to find the largest of two numbers

#include <stdio.h>
int main()
{
int a = 10, b = 20, largest;
largest = (a > b) ? a : b; // if a>b is true, largest=a, else largest=b
printf("Largest = %d", largest);
return 0;
}

Output:
Largest = 20

11.8 Special Operators


C also provides a few special-purpose operators for specific tasks:

Operator Name Purpose

sizeof() Size-of operator Returns the size (in bytes) occupied by


a data type or variable

, Comma operator Allows multiple expressions to be


evaluated where only one is expected

& Address-of operator Returns the memory address of a


variable

* Pointer/Dereference operator Declares a pointer, or accesses the


value stored at an address

Example: Program using sizeof and the address-of operator

#include <stdio.h>
int main()
{
int a = 10;
printf("Size of int = %lu bytes\n", sizeof(a));
printf("Value of a = %d\n", a);
printf("Address of a = %p\n", &a);
return 0;
}

Output:
Size of int = 4 bytes
Value of a = 10
Address of a = 0x7ffe4a3c9b1c (this will vary each time you run it)
sizeof() is very useful when writing code that needs to work correctly regardless of how much memory a data type
occupies on a particular machine. The address-of operator (&) is essential when using scanf() and pointers, since
it tells the compiler exactly where in memory a value should be stored.

11.9 Operator Precedence (Quick Reference)


When an expression contains more than one operator, C follows a fixed order called operator precedence to
decide which operation to perform first — similar to the "BODMAS" rule in mathematics. Operators with higher
precedence are evaluated before operators with lower precedence.

Precedence (High to Low) Operators

1. Unary ++, --, +, -, !, ~, sizeof

2. Multiplicative *, /, %
Precedence (High to Low) Operators

3. Additive +, -

4. Shift <<, >>

5. Relational <, <=, >, >=

6. Equality ==, !=

7. Bitwise AND/XOR/OR &, ^, |

8. Logical AND/OR &&, ||

9. Conditional ?:

10. Assignment =, +=, -=, *=, /=, %=

Example: How precedence affects a result

#include <stdio.h>
int main()
{
int result = 10 + 5 * 2; // * has higher precedence than +
printf("Result = %d", result); // 5*2 is done first, then +10
return 0;
}

Output:
Result = 20

12. Type Conversion and Type Casting


Sometimes a program needs to convert a value from one data type to another. In C, this can happen in two ways:
automatically (type conversion) or manually (type casting).

12.1 Type Conversion (Implicit)


Type conversion happens automatically, done by the compiler itself, when values of different data types are used
together in an expression. The compiler usually converts the "smaller" data type into the "larger" one to avoid loss
of data. This is also called implicit conversion.

Example: Automatic type conversion

#include <stdio.h>
int main()
{
int a = 5;
float b = 2.5;
float result = a + b; // int 'a' is automatically converted to float
printf("Result = %f", result);
return 0;
}

Output:
Result = 7.500000
Here, the compiler automatically converts the integer value of a into a floating-point value before adding it to b,
since the result is being stored in a float variable.

12.2 Type Casting (Explicit)


Type casting is when the programmer manually and deliberately converts a value from one data type into another,
by writing the desired data type in parentheses before the value. This is also called explicit conversion.

Example: Manual type casting

#include <stdio.h>
int main()
{
int a = 7, b = 2;
float result;
result = (float) a / b; // manually converting 'a' to float
printf("Result = %f", result);
return 0;
}

Output:
Result = 3.500000
Without the (float) cast, both a and b would be treated as integers, and the division 7 / 2 would give 3 (losing the
decimal part). By casting a to float first, the division correctly produces 3.5.

Aspect Type Conversion (Implicit) Type Casting (Explicit)

Who performs it? Compiler, automatically Programmer, manually

Syntax No special syntax needed (dataType) value

Control Less control for the programmer Full control for the programmer

Example int + float done automatically (float) a / b

You might also like