C Programming
C Programming
Introduction to C Programming
C is one of the most widely used and influential programming languages in the world.
Developed in the early 1970s by Dennis Ritchie at Bell Laboratories, C was originally created
to develop the UNIX operating system. Over time, it became a foundation for many modern
programming languages such as C++, Java, Python, and C#. Because of its efficiency,
flexibility, and close relationship with computer hardware, C remains an essential language for
students and professionals in computer science and engineering.
One of the main reasons C is so important is its speed and performance. Programs written in
C are compiled directly into machine code, allowing them to run very fast. Unlike interpreted
languages, C gives programmers direct control over system resources such as memory and
processor usage. This makes it ideal for developing operating systems, embedded systems,
device drivers, and performance-critical applications like game engines and real-time systems.
SK THOTTARATH 1
Introduction to C Programming
Another important feature of C is its simplicity and small set of keywords. C has a relatively
limited number of built-in keywords compared to many modern languages, making it easier to
learn the fundamentals of programming. However, this simplicity does not mean C is weak.
Instead, it provides powerful constructs such as loops, conditionals, pointers, arrays, and
structures that allow developers to build complex and efficient programs.
One of the most distinctive aspects of C programming is the use of pointers. Pointers store
memory addresses and allow direct access to memory locations. While pointers can be
challenging for beginners, they are extremely powerful. They enable dynamic memory
allocation, efficient array handling, and low-level system programming. Understanding
pointers helps programmers gain deeper knowledge of how computers work internally,
including memory management and data representation.
C is also known for its portability. Programs written in C can be compiled and run on different
platforms with minimal changes. This is because C code is largely independent of hardware
and operating systems, provided that a suitable compiler is available. As a result, C has been
used on a wide range of systems, from small microcontrollers to supercomputers.
The language relies heavily on standard libraries, such as stdio.h for input and output
operations, stdlib.h for memory allocation and utilities, and math.h for mathematical functions.
These libraries provide pre-defined functions that simplify programming and reduce the need
to write code from scratch. By using these libraries, programmers can focus more on problem-
solving rather than low-level implementation details.
Learning C programming also helps develop strong problem-solving and logical thinking
skills. Since C does not hide many details from the programmer, it encourages careful planning,
precise coding, and a clear understanding of how programs execute. Errors such as memory
leaks or segmentation faults teach programmers the importance of writing safe and efficient
code. These skills are valuable not only in C but also when learning other programming
languages.
Despite the rise of newer programming languages, C continues to be highly relevant today. It
is widely used in embedded systems, robotics, operating systems, compilers, and network
programming. Many modern technologies, including Linux, Windows components, and
database systems, are written partially or entirely in C. Because of this, C remains a core subject
in computer science education worldwide.
In conclusion, C programming is a fundamental and powerful language that has shaped the
world of software development. Its efficiency, portability, and low-level capabilities make it
an excellent choice for understanding the core principles of programming and computer
systems. For beginners, learning C provides a strong foundation that makes it easier to learn
advanced languages and technologies in the future. Even decades after its creation, C continues
to be a vital tool in modern computing.
SK THOTTARATH 2
Introduction to C Programming
Character Set in C
The character set in C refers to the collection of valid characters that can be used to write C
programs. These characters are used to form keywords, identifiers, constants, operators, and
other elements of a C program. C uses the ASCII (American Standard Code for
Information Interchange) character set, which assigns numeric values to characters so they
can be stored and processed by computers.
1. Alphabets
Uppercase letters: A to Z
Lowercase letters: a to z
C is a case-sensitive language, which means uppercase and lowercase letters are treated as
different characters. For example, sum, Sum, and SUM are considered different identifiers.
2. Digits
0 1 2 3 4 5 6 7 8 9
These digits are used to form numeric constants and variable names (except that identifiers
cannot start with a digit).
White space characters are used to separate words and improve readability of programs.
They are generally ignored by the compiler except where they separate tokens.
SK THOTTARATH 3
Introduction to C Programming
Space ( )
Horizontal tab (\t)
New line (\n)
Vertical tab (\v)
Form feed (\f)
Carriage return (\r)
4. Special Symbols
Special symbols are characters that have special meanings in C and are used for operators,
punctuation, and program structure.
+ - * / %
= < > !
& | ^
~ ?
: ;
, .
# '
" \ ( ) [ ] { }
These symbols are used in expressions, function calls, control statements, preprocessing
directives, and string or character constants.
5. Escape Sequences
Escape sequences are special character combinations that begin with a backslash (\) and are
used to represent non-printable or special characters.
\n – New line
\t – Horizontal tab
SK THOTTARATH 4
Introduction to C Programming
\b – Backspace
\r – Carriage return
\f – Form feed
\\ – Backslash
\' – Single quote
\" – Double quote
\0 – Null character
Constants in C
In C programming, a constant is a fixed value that does not change during the execution of a
program. Unlike variables, constants remain the same throughout the program once they are
defined. Constants are used to make programs more readable, reliable, and easier to maintain.
Constants in C can be classified into different types based on their data and usage.
Types of Constants in C
1. Numeric Constants
Numeric constants represent numbers and are further divided into integer constants and
floating-point constants.
a) Integer Constants
Examples:
10
-25
0
b) Floating-Point Constants
SK THOTTARATH 5
Introduction to C Programming
Examples:
3.14
-0.5
2.5e3
2. Character Constants
Examples:
'A'
'9'
'$'
String constants are a sequence of characters enclosed in double quotes. In C, strings are
stored as arrays of characters ending with a null character (\0).
Examples:
"Hello"
"Welcome to C"
4. Enumeration Constants
Enumeration constants are user-defined constants declared using the enum keyword. They
assign meaningful names to integer values.
Example:
SK THOTTARATH 6
Introduction to C Programming
5. Symbolic Constants
Symbolic constants are created using the #define preprocessor directive. They are used
to define constant values with meaningful names.
Example:
#define PI 3.14
#define MAX 100
Symbolic constants improve readability and make it easy to change values in one place.
C also allows variables to be declared as constants using the const keyword. Once assigned,
their value cannot be changed.
Example:
Identifiers in C
In C programming, an identifier is the name given to a program element such as a variable,
function, array, or any other user-defined item. Identifiers are used to identify these
elements uniquely so that they can be referenced throughout the program.
For example:
int total;
float average;
SK THOTTARATH 7
Introduction to C Programming
count
_total
marks1
student_name
Sum
Types of Identifiers in C
SK THOTTARATH 8
Introduction to C Programming
Key words in C
In the C programming language, keywords are predefined, reserved words that have special
meanings to the compiler. These words form the core vocabulary of C and are used to define
the structure, data types, control flow, and behavior of a program. Because keywords are
reserved, they cannot be used as identifiers such as variable names, function names, or array
names.
Keywords are an essential part of C syntax. Understanding them is necessary to read, write,
and debug C programs effectively.
Characteristics of C Keywords
SK THOTTARATH 9
Introduction to C Programming
Understanding basic data types is essential for writing efficient, correct, and readable C
programs.
Basic data types are the predefined data types provided by the C language. They are used to
store simple values such as integers, characters, and decimal numbers. These data types form
the foundation for more complex data structures.
int
char
float
double
void
The int data type is used to store whole numbers (both positive and negative) without any
decimal part.
Features:
Example:
SK THOTTARATH 10
Introduction to C Programming
Variations of int:
short int
long int
signed int
unsigned int
Example:
The char data type is used to store single characters such as letters, digits, or symbols.
Features:
Example:
The float data type is used to store real numbers with decimal points.
Features:
SK THOTTARATH 11
Introduction to C Programming
Example:
Note:
The double data type is used to store decimal numbers with higher precision than float.
Features:
Example:
double pi = 3.14159265359;
double distance = 12345.6789;
Variations:
The void data type represents no value or no type. It is mainly used in functions and
pointers.
SK THOTTARATH 12
Introduction to C Programming
Uses of void:
Example:
void display() {
printf("Hello World");
}
void *ptr;
char 1 byte
int 4 bytes
float 4 bytes
double 8 bytes
void No storage
SK THOTTARATH 13
Introduction to C Programming
Variables in C Programming
In C programming, a variable is a named memory location used to store data that can change
during the execution of a program. Variables are fundamental elements of any programming
language because they allow programmers to store, modify, and retrieve data efficiently. Every
variable in C has a data type, a name, a value, and a scope, all of which determine how the
variable behaves within a program.
Definition of a Variable
A variable can be defined as a container for storing data values in memory. The value stored
in a variable may change as the program runs, which is why it is called a variable.
In C, a variable must be declared before it is used. Variable declaration tells the compiler the
type of data the variable will hold and how much memory should be allocated for it.
data_type variable_name;
Example:
int number;
float price;
char grade;
Variable names must begin with a letter (a–z or A–Z) or an underscore (_).
SK THOTTARATH 14
Introduction to C Programming
Types of Variables in C
Variables in C can be classified based on their scope, lifetime, and storage class.
1. Local Variables
Local variables are declared inside a function or block and are accessible only within that
block.
Characteristics:
Example:
void display() {
int x = 10; // local variable
}
2. Global Variables
Global variables are declared outside all functions and are accessible throughout the
program.
SK THOTTARATH 15
Introduction to C Programming
Characteristics:
Example:
3. Static Variables
Static variables are declared using the static keyword. They retain their value even after
the function exits.
Characteristics:
Example:
void counter() {
static int c = 0;
c++;
}
4. Register Variables
Register variables are declared using the register keyword and request the compiler to
store the variable in a CPU register for faster access.
Characteristics:
SK THOTTARATH 16
Introduction to C Programming
Example:
register int i;
Variable Initialization
Example:
int x = 5;
float rate = 2.5;
Uninitialized variables may contain garbage values, which can cause unexpected results in a
program.
Scope refers to the area of the program where a variable can be accessed.
Lifetime refers to the duration for which a variable exists in memory.
Different types of variables have different scopes and lifetimes, which affect program
behavior.
A clear understanding of operators and their precedence is essential to write correct, efficient,
and readable C programs.
SK THOTTARATH 17
Introduction to C Programming
An operator is a symbol that instructs the compiler to perform a particular operation. For
example, the + operator adds two values, while the = operator assigns a value to a variable.
Example:
int sum = a + b;
Types of Operators in C
1. Arithmetic Operators
Operator Operation
+ Addition
- Subtraction
Multiplication
/ Division
% Modulus (remainder)
‘Example:
int a = 10, b = 3;
int c = a + b;
SK THOTTARATH 18
Introduction to C Programming
2. Relational Operators
Relational operators compare two values and return either true (1) or false (0).
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Example:
if (a > b)
printf("a is greater");
3. Logical Operators
Operator Meaning
&& LogicalAND
|| Logical OR
! Logical NOT
Example:
4. Assignment Operators
SK THOTTARATH 19
Introduction to C Programming
Operator Description
= Assign
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
Example:
x += 5; // x = x + 5
Operator Meaning
++ Increment
-- Decrement
Example:
i++;
--j;
6. Bitwise Operators
Operator Operation
& BitwiseAND
| Bitwise OR
^ Bitwise XOR
~ Bitwise NOT
SK THOTTARATH 20
Introduction to C Programming
7. Conditional Operator
Syntax:
Example:
max = (a > b) ? a : b;
8. Special Operators
Operator Precedence in C
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated first. If two operators have the same
precedence, associativity determines the order of evaluation.
Example:
int result = 10 + 5 * 2;
Here, multiplication has higher precedence than addition, so the result is 20, not 30.
Precedence Operators
(), [], ->,
Highest
.
++, --
*, /, %
SK THOTTARATH 21
Introduction to C Programming
+, -
<, <=, >, >=
==, !=
&&
` `
?:
Lowest = , +=, -=
When in doubt, parentheses () should be used to ensure the desired order of evaluation.
Understanding bitwise operators helps programmers gain deeper insight into how data is stored
and processed inside the computer.
Bitwise operators operate on operands at the bit level. Before performing bitwise operations,
integer values are converted into binary form. The operation is then carried out bit by bit, and
the result is converted back into decimal form.
Bitwise operators are mainly used with integer data types such as int, char, and long.
SK THOTTARATH 22
Introduction to C Programming
Operator Name
| Bitwise OR
^ Bitwise XOR
The bitwise AND operator compares each bit of two operands. If both corresponding bits
are 1, the result is 1; otherwise, the result is 0.
Example:
int a = 5; // 0101
int b = 3; // 0011
int c = a & b; // 0001 (1)
Uses:
2. Bitwise OR (|)
The bitwise OR operator compares each bit of two operands. If at least one bit is 1, the result
is 1.
SK THOTTARATH 23
Introduction to C Programming
Example:
int a = 5; // 0101
int b = 3; // 0011
int c = a | b; // 0111 (7)
Uses:
The bitwise XOR (exclusive OR) operator compares each bit of two operands. If the bits are
different, the result is 1; if they are the same, the result is 0.
Example:
int a = 5; // 0101
int b = 3; // 0011
int c = a ^ b; // 0110 (6)
Uses:
The bitwise NOT operator inverts all the bits of its operand. It changes 1 to 0 and 0 to 1. This
operation is also known as one's complement.
Example:
int a = 5; // 00000101
int b = ~a; // 11111010
SK THOTTARATH 24
Introduction to C Programming
Note:
The result depends on the number of bits used to store the integer and the system's
representation of signed numbers.
The left shift operator shifts all bits of a number to the left by a specified number of
positions. Zeros are added from the right.
Example:
int a = 5; // 00000101
int b = a << 1; // 00001010 (10)
Uses:
The right shift operator shifts all bits of a number to the right by a specified number of
positions.
Example:
Uses:
SK THOTTARATH 25
Introduction to C Programming
Expressions in C Programming
In C programming, an expression is a combination of variables, constants, operators, and
function calls that are evaluated to produce a single value. Expressions are fundamental to C
programs because they are used to perform calculations, make decisions, and manipulate data.
Almost every statement in a C program involves an expression in some form.
A clear understanding of expressions helps programmers write correct, efficient, and readable
code. Expressions, together with operators and operands, form the backbone of logical and
computational processing in C.
Definition of an Expression
Example:
int result = a + b * c;
In this expression, a, b, and c are operands, while + and * are operators. The expression
evaluates to a single value that is assigned to result.
Components of an Expression
Example:
SK THOTTARATH 26
Introduction to C Programming
x = 10 + y;
Here, 10 and y are operands, + is an operator, and the entire statement contains an expression.
Types of Expressions in C
Expressions in C can be classified into several types based on the kind of operators used.
1. Arithmetic Expressions
Arithmetic expressions involve arithmetic operators such as +, -, *, /, and %. They are used to
perform mathematical calculations.
Example:
int sum = a + b;
int area = length * width;
2. Relational Expressions
Relational expressions use relational operators to compare two values. The result of a
relational expression is either true (1) or false (0).
Example:
if (a > b)
Common relational operators include <, >, <=, >=, ==, and !=.
3. Logical Expressions
Logical expressions combine one or more relational expressions using logical operators such
as &&, ||, and !.
SK THOTTARATH 27
Introduction to C Programming
Example:
4. Assignment Expressions
Assignment expressions use the assignment operator (=) to assign values to variables. The
assignment itself is treated as an expression in C.
Example:
x = y + 5;
Compound assignment operators such as +=, -=, *=, and /= also form assignment
expressions.
5. Conditional Expressions
The conditional (ternary) expression uses the ?: operator and is a compact form of the if-else
statement.
Syntax:
Example:
max = (a > b) ? a : b;
6. Bitwise Expressions
Bitwise expressions use bitwise operators to manipulate data at the bit level.
Example:
result = a & b;
SK THOTTARATH 28
Introduction to C Programming
Increment (++) and decrement (--) operators are used to increase or decrease the value of a
variable by one.
Example:
i++;
--count;
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated first. If operators have the same precedence,
associativity rules are applied.
Example:
int value = 10 + 5 * 2;
Using parentheses can help control the order of evaluation and improve code clarity.
C provides a set of standard input and output functions through the standard library
<stdio.h>. Understanding input and output statements is fundamental for writing effective
and interactive C programs.
SK THOTTARATH 29
Introduction to C Programming
Input refers to the process of receiving data from the user or another source.
Output refers to the process of displaying or sending data to the user.
In C, most input and output operations are performed using functions, not keywords or
operators.
Input Statements in C
Input statements are used to read data entered by the user through the keyboard. The most
commonly used input function in C is scanf().
1. scanf() Function
The scanf() function is used to read formatted input from the standard input device
(keyboard).
Syntax:
scanf("format_specifier", &variable);
Example:
int age;
scanf("%d", &age);
%d – integer
%f – float
%c – character
%s – string
int a, b;
scanf("%d %d", &a, &b);
SK THOTTARATH 30
Introduction to C Programming
Output Statements in C
Output statements are used to display data on the screen. The most commonly used output
function is printf().
1. printf() Function
Syntax:
printf("format_string", variables);
Example:
%d – integer
%f – float
%c – character
%s – string
Structure of a C Program
The structure of a C program refers to the organized way in which different parts of a C
program are arranged and written. A well-structured C program is easy to read, understand,
debug, and maintain. C follows a specific program structure that guides the compiler on how
the program should be executed.
Understanding the structure of a C program is the first and most important step for beginners
learning C programming, as it forms the foundation for writing correct and efficient programs.
SK THOTTARATH 31
Introduction to C Programming
1. Documentation Section
2. Link Section
3. Definition Section
4. Global Declaration Section
5. main() Function
6. User-Defined Functions
Each section has a specific purpose and role in the execution of the program.
1. Documentation Section
The documentation section consists of comments that describe the program. It includes
information such as the program name, author, date, and purpose of the program.
Comments are ignored by the compiler and are meant only for program readability.
Example:
2. Link Section
The link section includes header files using the #include directive. Header files contain
declarations of functions and macros that are used in the program.
Example:
#include <stdio.h>
Here, stdio.h provides input and output functions like printf() and scanf().
SK THOTTARATH 32
Introduction to C Programming
3. Definition Section
The definition section defines macros and symbolic constants using the #define
directive. These constants make programs more readable and easier to modify.
Example:
#define PI 3.14
#define MAX 100
The global declaration section contains global variables, function prototypes, and structure
declarations that are accessible throughout the program.
Example:
int count;
float total;
Global variables retain their values throughout the execution of the program.
5. main() Function
The main() function is the entry point of every C program. Program execution always
starts from the main() function.
Syntax:
int main() {
// statements
return 0;
}
SK THOTTARATH 33
Introduction to C Programming
6. User-Defined Functions
User-defined functions are written by the programmer to perform specific tasks. They help in
modular programming, making the program easier to manage and reuse.
Example:
void display() {
printf("Hello World");
}
int main() {
printf(MSG);
return 0;
}
SK THOTTARATH 34
Introduction to C Programming
#include <stdio.h>
int main() {
printf("Hello World");
return 0;
}
#include <stdio.h>
int main() {
int a, b, sum;
a = 10;
b = 20;
sum = a + b;
printf("Sum = %d", sum);
return 0;
}
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Sum = %d", a + b);
return 0;
}
SK THOTTARATH 35
Introduction to C Programming
#include <stdio.h>
int main() {
int length = 5, breadth = 4;
int area = length * breadth;
printf("Area of rectangle = %d", area);
return 0;
}
#include <stdio.h>
int main() {
float radius = 3.5;
float area = 3.14 * radius * radius;
printf("Area of circle = %.2f", area);
return 0;
}
Formula:
Simple Interest = (P × T × R) / 100
#include <stdio.h>
int main() {
float p = 1000, t = 2, r = 5;
float si = (p * t * r) / 100;
printf("Simple Interest = %.2f", si);
return 0;
}
SK THOTTARATH 36
Introduction to C Programming
#include <stdio.h>
int main() {
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
printf("a = %d, b = %d", a, b);
return 0;
}
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
float avg = (a + b + c) / 3.0;
printf("Average = %.2f", avg);
return 0;
}
SK THOTTARATH 37
Introduction to C Programming
Among various control statements, the if, if-else, and nested if statements are the most basic
and commonly used decision-making statements in C programming.
1. if Statement
The if statement is the simplest form of decision-making statement. It executes a block of
code only when a given condition is true.
Syntax:
if (condition) {
// statements
}
Working:
SK THOTTARATH 38
Introduction to C Programming
Example:
In this example, the message "Pass" is displayed only if the value of marks is 40 or more.
2. if-else Statement
The if-else statement is an extension of the if statement. It provides an alternative
block of code that is executed when the condition is false.
Syntax:
if (condition) {
// statements if condition is true
} else {
// statements if condition is false
}
Working:
Example:
if (num % 2 == 0) {
printf("Even number");
} else {
printf("Odd number");
}
SK THOTTARATH 39
Introduction to C Programming
This program checks whether a number is even or odd and displays the appropriate message.
3. Nested if Statement
A nested if statement is an if statement placed inside another if or else block. It is used
when multiple conditions need to be checked in a hierarchical manner.
Syntax:
if (condition1) {
if (condition2) {
// statements
}
}
Working:
Example:
In this example, the program first checks whether the student has passed. If true, it then
checks whether the student has scored distinction marks.
SK THOTTARATH 40
Introduction to C Programming
Statement Description
The switch statement allows a program to execute different blocks of code based on the value
of an expression. It improves program clarity and readability when dealing with multiple
choices.
The switch statement is a control statement that selects one block of code to execute from
multiple options. The selection depends on the value of an expression, usually an integer or
character type.
SK THOTTARATH 41
Introduction to C Programming
The expression is compared with several constant values called case labels. When a match is
found, the corresponding block of statements is executed.
switch (expression) {
case constant1:
// statements
break;
case constant2:
// statements
break;
default:
// statements
}
int choice = 2;
SK THOTTARATH 42
Introduction to C Programming
switch (choice) {
case 1:
printf("Option One");
break;
case 2:
printf("Option Two");
break;
case 3:
printf("Option Three");
break;
default:
printf("Invalid Choice");
}
In this example, the program prints "Option Two" because the value of choice is 2.
The break statement is used to exit from the switch block. If break is not used, execution
continues to the next case. This behavior is known as fall-through.
Example (Fall-through):
switch (x) {
case 1:
printf("One");
case 2:
printf("Two");
}
SK THOTTARATH 43
Introduction to C Programming
default Statement
The default case is optional and is executed when none of the case values match the switch
expression. It helps handle unexpected or invalid values.
SK THOTTARATH 44
Introduction to C Programming
The while and do-while statements are especially useful when the number of iterations is not
known in advance and depends on a condition.
Looping Statements in C
1. while loop
2. do-while loop
3. for loop
While Statement
The while statement is an entry-controlled loop, meaning the condition is checked before
the loop body is executed. If the condition is false initially, the loop body will not execute
even once.
while (condition) {
// statements
}
SK THOTTARATH 45
Introduction to C Programming
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}
Do-While Statement
The do-while statement is an exit-controlled loop, meaning the condition is checked after
the loop body is executed. Therefore, the loop body executes at least once, even if the
condition is false initially.
do {
// statements
} while (condition);
SK THOTTARATH 46
Introduction to C Programming
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
Loop body may not execute Loop body executes at least once
SK THOTTARATH 47
Introduction to C Programming
In C programming, a for loop is a control structure used to repeat a block of code a specific
number of times. It is especially useful when the number of iterations is known in advance,
such as printing numbers, processing arrays, or performing calculations repeatedly.
Example
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
This program prints the numbers 1 to 5. The loop starts with i = 1, continues while i <= 5,
and increases i by 1 after each iteration.
SK THOTTARATH 48
Introduction to C Programming
Conclusion
The for loop is a fundamental and powerful feature in C programming. It helps programmers
perform repetitive tasks efficiently and keeps programs organized and readable. Mastering
the for loop is an important step in learning C and developing logical thinking in
programming.
Below is a long, exam-ready essay (about 3 pages) on the for loop in C programming,
written in clear, student-friendly language. You can shorten or expand it if your teacher
requires a specific word count.
C is a powerful and widely used programming language that forms the foundation of many
modern programming languages. One of the most important features of C is its ability to
perform repetitive tasks efficiently using looping statements. Among the different types of
loops available in C—such as while, do-while, and for—the for loop is the most commonly
used when the number of iterations is known in advance. The for loop helps programmers write
clean, structured, and efficient code by reducing repetition and improving readability.
A for loop in C is a control structure that allows a block of code to be executed repeatedly
based on a specified condition. It is mainly used when a programmer knows how many times
a statement or group of statements needs to be executed. The for loop combines initialization,
condition checking, and updating of the loop variable into a single line, making it compact and
easy to understand.
SK THOTTARATH 49
Introduction to C Programming
Initialization: This part initializes the loop control variable. It is executed only once
at the beginning of the loop.
Condition: The condition is checked before each iteration. If it evaluates to true, the
loop continues; if false, the loop terminates.
Increment/Decrement: This updates the loop control variable after each iteration.
Once the condition is false, the control exits the loop and moves to the next statement in the
program.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
return 0;
}
SK THOTTARATH 50
Introduction to C Programming
Explanation:
This is the most commonly used form where all three parts of the loop are present.
for (;;) {
printf("Hello\n");
}
A for loop inside another for loop is called a nested for loop. It is commonly used in matrix
SK THOTTARATH 51
Introduction to C Programming
Because of its flexibility and efficiency, the for loop is essential in both beginner and
advanced C programs.
Despite these limitations, proper use of the for loop makes programs more effective and
manageable.
While Loop: Used when the number of iterations is not known beforehand.
Do-While Loop: Executes the loop body at least once, even if the condition is false.
For Loop: Best used when the number of iterations is fixed or known.
Thus, the for loop is preferred for counting and repetition-based tasks.
SK THOTTARATH 52
Introduction to C Programming
Break Statement in C
The break statement is used to immediately terminate the execution of a loop or a switch
statement. When a break statement is encountered inside a loop, the control exits the loop and
moves to the statement following the loop. It is commonly used when a certain condition is
met and further execution of the loop is unnecessary.
The break statement can be used inside for, while, and do-while loops.
When executed, it stops the loop instantly.
Control is transferred to the statement immediately after the loop.
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
printf("%d\n", i);
}
return 0;
}
Explanation:
The loop prints numbers from 1 to 4. When the value of i becomes 5, the break statement is
executed, and the loop terminates.
SK THOTTARATH 53
Introduction to C Programming
Uses of Break Statement
Continue Statement in C
The continue statement is used to skip the remaining code inside the loop for the current
iteration and move directly to the next iteration. Unlike the break statement, continue does
not terminate the loop; it only skips the current cycle.
int main() {
int i;
for (i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("%d\n", i);
}
return 0;
}
Explanation:
The loop prints numbers 1, 2, 4, and 5. When i equals 3, the continue statement skips the
print statement and moves to the next iteration.
SK THOTTARATH 54
Introduction to C Programming
To avoid deeply nested conditional statements
Disadvantages
SK THOTTARATH 55
Introduction to C Programming
A nested loop in C programming refers to a loop that is placed inside the body of another loop.
The outer loop controls the number of times the inner loop executes. For each iteration of the
outer loop, the inner loop runs completely from start to end. Nested loops are commonly used
when a task involves repeated processing within another repeated process.
Any type of loop (for, while, or do-while) can be nested inside another loop. There is no
fixed limit on the level of nesting, but deep nesting should be avoided as it can make programs
difficult to understand and maintain.
In this structure:
Thus, the inner loop executes multiple times for each iteration of the outer loop.
SK THOTTARATH 56
Introduction to C Programming
int main() {
int i, j;
for (i = 1; i <= 3; i++) {
for (j = 1; j <= 2; j++) {
printf("i = %d, j = %d\n", i, j);
}
}
return 0;
}
Explanation:
The outer loop runs 3 times. For each iteration of the outer loop, the inner loop runs 2 times.
As a result, the inner loop executes a total of 6 times.
This is the most common type of nested loop and is widely used for pattern printing and
matrix operations.
SK THOTTARATH 57
Introduction to C Programming
int i = 1;
do {
int j = 1;
while (j <= 3) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
} while (i <= 3);
Output:
*
* *
* * *
* * * *
SK THOTTARATH 58
Introduction to C Programming
In this example, the outer loop controls the number of rows, while the inner loop controls the
number of stars in each row.
Nested loops help access each element of the matrix row by row and column by column.
Careful planning and proper indentation are necessary to minimize these disadvantages.
SK THOTTARATH 59
Introduction to C Programming
SK THOTTARATH 60
Introduction to C Programming
1. Introduction
C programming is a structured and powerful programming language widely used for system
software, application development, and academic learning. One of the most important
features of C is its ability to handle large amounts of data efficiently. When a program needs
to store and process multiple values of the same data type, using separate variables becomes
inefficient and confusing. To overcome this problem, arrays are used.
An array allows the storage of multiple values of the same data type under a single name.
Along with arrays, C provides advanced features such as enumerated data types, type
definitions, and powerful algorithms like searching and sorting. Concepts such as single-
dimensional arrays, two-dimensional arrays, matrix processing, sequential search, and
bubble sort form the foundation of data handling in C programming.
2. Arrays in C Programming
Definition of an Array
An array is a collection of elements of the same data type stored in contiguous memory
locations. Each element in an array is accessed using an index number.
A single dimensional array is a linear list of elements stored in a single row. It uses only
one index to access elements.
SK THOTTARATH 61
Introduction to C Programming
Example:
int marks[5];
Defining an Array
data_type array_name[size];
Example:
float temperature[10];
Here:
Array Initialization
Array initialization means assigning values to array elements at the time of declaration.
Array elements are accessed using index numbers. Indexing starts from 0.
SK THOTTARATH 62
Introduction to C Programming
Example:
printf("%d", num[0]);
Limitations of Arrays
Fixed size
Stores only similar data types
Wastage of memory if size is large
An enumerated data type is a user-defined data type that assigns names to integral
constants. It improves code readability and reduces errors.
Syntax
enum days {Monday, Tuesday, Wednesday, Thursday, Friday};
SK THOTTARATH 63
Introduction to C Programming
Example Program
#include <stdio.h>
int main() {
enum days d;
d = Wed;
printf("%d", d);
return 0;
}
Advantages of enum
Meaning of typedef
The typedef keyword is used to create a new name (alias) for an existing data type.
Syntax
typedef data_type new_name;
Example
typedef int number;
number a, b;
Uses of typedef
SK THOTTARATH 64
Introduction to C Programming
Example:
int matrix[3][3];
Syntax:
data_type array_name[rows][columns];
Example:
int marks[2][3];
int main() {
int a[2][2], b[2][2], sum[2][2], i, j;
SK THOTTARATH 65
Introduction to C Programming
return 0;
}
8. Sequential Search
Meaning of Sequential Search
Sequential search is a searching technique in which each element is checked one by one
until the desired element is found or the list ends.
Algorithm
int main() {
int a[5] = {10, 20, 30, 40, 50};
int key = 30, i;
SK THOTTARATH 66
Introduction to C Programming
for(i = 0; i < 5; i++) {
if(a[i] == key) {
printf("Element found at position %d", i+1);
break;
}
}
return 0;
}
Simple to understand
Works on unsorted data
Easy to implement
Disadvantages
9. Bubble Sort
Meaning of Bubble Sort
Bubble sort is a simple sorting technique that repeatedly compares adjacent elements and
swaps them if they are in the wrong order.
int main() {
int a[5] = {5, 1, 4, 2, 8};
int i, j, temp;
SK THOTTARATH 67
Introduction to C Programming
for(j = 0; j < 5-1-i; j++) {
if(a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return 0;
}
Easy to understand
Simple implementation
Useful for small data sets
Disadvantages
SK THOTTARATH 68
Introduction to C Programming
STRINGS IN C PROGRAMMING
1. Introduction
C programming is a powerful and flexible language that supports various data types to store
and manipulate information. While numbers are handled using basic data types like int,
float, and double, handling textual data such as names, sentences, and messages requires a
different approach. This is where strings are used.
2. Meaning of String in C
In C programming, a string is defined as a collection of characters enclosed within double
quotation marks. Internally, a string is stored as a character array, where the last character is
always the null character ('\0'), which indicates the end of the string.
Example:
C o m p u t e r \0
Syntax
char string_name[size];
SK THOTTARATH 69
Introduction to C Programming
Example
char city[20];
Here:
4. Initialization of Strings
Strings can be initialized in several ways.
5. Reading Strings in C
C provides different ways to read strings from the user.
SK THOTTARATH 70
Introduction to C Programming
Safe
Reads spaces
Preferred in modern C programming
6. Displaying Strings in C
Strings can be displayed using:
6.1 printf()
printf("%s", name);
6.2 puts()
puts(name);
strlen()
strcpy()
strcat()
strcmp()
SK THOTTARATH 71
Introduction to C Programming
strlwr()
strupr()
strrev()
Example:
Example:
Returns:
0 if equal
SK THOTTARATH 72
Introduction to C Programming
int main() {
char str[50];
fgets(str, 50, stdin);
printf("Length = %d", strlen(str));
return 0;
}
String matching is the process of checking whether a particular string (pattern) exists within
another string (text). It is widely used in text searching, compilers, data validation, and search
engines.
SK THOTTARATH 73
Introduction to C Programming
int main() {
char s1[20], s2[20];
scanf("%s %s", s1, s2);
if(strcmp(s1, s2) == 0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
int main() {
char s1[50], s2[50];
int i = 0, flag = 1;
if(flag)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
SK THOTTARATH 74
Introduction to C Programming
int main() {
char text[100], pattern[20];
if(strstr(text, pattern))
printf("Pattern found");
else
printf("Pattern not found");
return 0;
}
SK THOTTARATH 75
Introduction to C Programming
User interaction
File handling
Data communication
Software development
Without strings, meaningful interaction between programs and users would not be possible.
SK THOTTARATH 76