0% found this document useful (0 votes)
3 views76 pages

C Programming

C programming, developed in the 1970s, is a foundational language known for its efficiency, flexibility, and close relationship with hardware, making it essential for various applications including operating systems and embedded systems. It features a procedural structure, a simple character set, and powerful constructs like pointers, which enhance memory management and performance. Despite the emergence of newer languages, C remains relevant in modern computing and is a critical subject in computer science education.

Uploaded by

riyahameedc
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)
3 views76 pages

C Programming

C programming, developed in the 1970s, is a foundational language known for its efficiency, flexibility, and close relationship with hardware, making it essential for various applications including operating systems and embedded systems. It features a procedural structure, a simple character set, and powerful constructs like pointers, which enhance memory management and performance. Despite the emergence of newer languages, C remains relevant in modern computing and is a critical subject in computer science education.

Uploaded by

riyahameedc
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

Introduction to 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.

C is known as a procedural programming language, meaning programs are structured around


functions and procedures. A C program typically consists of functions that perform specific
tasks, with the main() function serving as the starting point of execution. This structured
approach helps programmers break large problems into smaller, manageable parts, improving
readability and maintainability.

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.

The C character set is broadly divided into the following categories:

1. Alphabets

C supports uppercase and lowercase English letters:

 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

C supports ten 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).

3. White Space Characters

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

Common white space characters include:

 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.

Some commonly used special symbols are:

+ - * / %
= < > !
& | ^
~ ?
: ;
, .
# '
" \ ( ) [ ] { }

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.

Common escape sequences in C include:

 \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

Integer constants are whole numbers without any decimal point.

Examples:

10
-25
0

Types of integer constants:

 Decimal (base 10): 10, 123


 Octal (base 8, starts with 0): 017
 Hexadecimal (base 16, starts with 0x or 0X): 0x1A

b) Floating-Point Constants

Floating-point constants contain a decimal point or are written in exponential form.

SK THOTTARATH 5
Introduction to C Programming

Examples:

3.14
-0.5
2.5e3

2. Character Constants

Character constants are single characters enclosed in single quotes.

Examples:

'A'
'9'
'$'

Each character constant has an associated ASCII value.

3. String Constants (String Literals)

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:

enum days { MON, TUE, WED, THU, FRI };

Here, MON has the value 0, TUE has 1, and so on.

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.

6. Constant Variables (const keyword)

C also allows variables to be declared as constants using the const keyword. Once assigned,
their value cannot be changed.

Example:

const int AGE = 18;

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;

Here, total and average are identifiers.

Rules for Naming Identifiers in C

C follows specific rules for creating valid identifiers:

SK THOTTARATH 7
Introduction to C Programming

1. An identifier must begin with a letter (A–Z or a–z) or an underscore (_).


2. The remaining characters may be letters, digits, or underscores.
3. Identifiers cannot start with a digit.
4. No special symbols (such as @, #, $, %) are allowed.
5. Keywords cannot be used as identifiers (e.g., int, while, return).
6. Identifiers are case-sensitive, so Sum, sum, and SUM are different.
7. Identifiers should not contain spaces.
8. Length of identifiers is typically limited to 31 characters for portability (though
many compilers allow more).

Examples of Valid Identifiers

count
_total
marks1
student_name
Sum

Examples of Invalid Identifiers

1number // starts with a digit


total-marks // contains special character
float // keyword
total marks // space not allowed

Types of Identifiers in C

Identifiers can be classified based on their usage:

1. Variable identifiers – used to name variables


Example: int age;
2. Function identifiers – used to name functions
Example: main(), calculateSum()
3. Array identifiers – used to name arrays
Example: int marks[10];
4. User-defined identifiers – used for structures, unions, enums
Example:
5. struct student { int id; };

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

 Keywords have fixed meanings defined by the C language standard.


 They are case-sensitive (for example, int is a keyword, but Int is not).
 Keywords cannot be redefined or overridden by the programmer.
 The number of keywords depends on the C standard (C90, C99, C11, etc.).

Keyword Keyword Keyword Keyword

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

SK THOTTARATH 9
Introduction to C Programming

Basic or Fundamental Data Types in C Programming


In the C programming language, data types specify the type of data that a variable can store.
They determine the size of memory allocated, the range of values, and the operations that
can be performed on the data. Among various categories of data types in C, basic (or primary)
data types are the fundamental building blocks used to construct programs.

Understanding basic data types is essential for writing efficient, correct, and readable C
programs.

What Are Basic Data Types?

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.

The main basic data types in C are:

 int
 char
 float
 double
 void

1. int (Integer Data Type)

The int data type is used to store whole numbers (both positive and negative) without any
decimal part.

Features:

 Stores integers like 10, -5, 0


 Typically occupies 4 bytes of memory (system-dependent)
 Commonly used for counting, indexing, and loop control

Example:

int age = 20;


int marks = -15;

SK THOTTARATH 10
Introduction to C Programming

Variations of int:

 short int
 long int
 signed int
 unsigned int

Example:

unsigned int count = 100;


long int population = 1000000;

2. char (Character Data Type)

The char data type is used to store single characters such as letters, digits, or symbols.

Features:

 Occupies 1 byte of memory


 Characters are enclosed in single quotes
 Internally stored as ASCII values

Example:

char grade = 'A';


char symbol = '#';

Signed and Unsigned char:

 signed char stores values from -128 to 127


 unsigned char stores values from 0 to 255

3. float (Floating-Point Data Type)

The float data type is used to store real numbers with decimal points.

Features:

SK THOTTARATH 11
Introduction to C Programming

 Occupies 4 bytes of memory


 Precision up to 6 decimal places
 Suitable for values requiring fractional representation

Example:

float price = 45.75;


float temperature = -12.5;

Note:

Floating-point numbers may have rounding errors due to limited precision.

4. double (Double Precision Floating-Point Data Type)

The double data type is used to store decimal numbers with higher precision than float.

Features:

 Occupies 8 bytes of memory


 Precision up to 15 decimal places
 Used in scientific and mathematical calculations

Example:

double pi = 3.14159265359;
double distance = 12345.6789;

Variations:

 long double (provides even higher precision)

5. void Data Type

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:

1. Function with no return value


2. Function with no parameters
3. Generic pointer

Example:

void display() {
printf("Hello World");
}

void *ptr;

Size of Basic Data Types (Typical)

Data Type Size

char 1 byte

int 4 bytes

float 4 bytes

double 8 bytes

void No storage

(Note: Sizes may vary depending on compiler and system architecture.)

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.

Understanding variables is essential for learning C programming, as almost every program


relies on variables to perform calculations, make decisions, and produce output.

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.

Syntax of Variable Declaration

data_type variable_name;

Example:

int number;
float price;
char grade;

Rules for Naming Variables

While naming variables in C, certain rules must be followed:

 Variable names must begin with a letter (a–z or A–Z) or an underscore (_).

SK THOTTARATH 14
Introduction to C Programming

 They can contain letters, digits, and underscores only.


 Variable names cannot start with a digit.
 Keywords of C cannot be used as variable names.
 Variable names are case-sensitive (total and Total are different).

Examples of valid variable names:

sum, _count, marks1

Examples of invalid variable names:

1value, float, total marks

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:

 Created when the function is called


 Destroyed when the function ends
 Do not retain their values between function calls

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:

 Declared at the top of the program


 Accessible by all functions
 Retain their value throughout program execution

Example:

int count = 0; // global variable

3. Static Variables

Static variables are declared using the static keyword. They retain their value even after
the function exits.

Characteristics:

 Lifetime is the entire program


 Scope may be local or global
 Useful for maintaining values between function calls

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:

 Faster access compared to memory variables


 Address of register variable cannot be accessed
 Mostly used for frequently accessed variables

SK THOTTARATH 16
Introduction to C Programming

Example:

register int i;

Variable Initialization

Variable initialization means assigning an initial value to a variable at the time of


declaration.

Example:

int x = 5;
float rate = 2.5;

Uninitialized variables may contain garbage values, which can cause unexpected results in a
program.

Scope and Lifetime of Variables

 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.

Operators and Precedence in C Programming


In C programming, operators are special symbols that perform specific operations on one or
more operands. Operands may be variables, constants, or expressions. Operators play a vital
role in C programs as they are used for calculations, comparisons, logical decisions, and
manipulation of data. Along with operators, operator precedence determines the order in
which operations are evaluated in an expression.

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

What Are Operators?

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;

Here, = and + are operators, and a and b are operands.

Types of Operators in C

C programming provides several types of operators, each serving a specific purpose.

1. Arithmetic Operators

Arithmetic operators are used to perform basic mathematical operations.

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

Logical operators are used to combine multiple conditions.

Operator Meaning
&& LogicalAND
|| Logical OR
! Logical NOT

Example:

if (a > 0 && b > 0)


printf("Both are positive");

4. Assignment Operators

Assignment operators assign values to variables.

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

5. Increment and Decrement Operators

These operators increase or decrease the value of a variable by one.

Operator Meaning
++ Increment
-- Decrement

Example:

i++;
--j;

6. Bitwise Operators

Bitwise operators perform operations at the bit level.

Operator Operation

& BitwiseAND
| Bitwise OR
^ Bitwise XOR

~ Bitwise NOT

<< Left shift


>> Right shift

SK THOTTARATH 20
Introduction to C Programming

7. Conditional Operator

The conditional (ternary) operator is used to make decisions.

Syntax:

condition ? expression1 : expression2;

Example:

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

8. Special Operators

C provides some special-purpose operators.

 sizeof – returns the size of a data type


 , (comma) – separates expressions
 & – address operator
 * – pointer operator

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.

Operator Precedence Table (High to Low)

Precedence Operators
(), [], ->,
Highest
.
++, --
*, /, %

SK THOTTARATH 21
Introduction to C Programming

+, -
<, <=, >, >=
==, !=
&&
` `
?:
Lowest = , +=, -=

Importance of Operator Precedence

 Prevents logical errors in expressions


 Improves accuracy of calculations
 Helps write clear and efficient code
 Reduces the need for excessive parentheses

When in doubt, parentheses () should be used to ensure the desired order of evaluation.

Bitwise Operators in C Programming


In C programming, bitwise operators are used to perform operations directly on the binary
representation of data. Unlike arithmetic or logical operators that work on values as a whole,
bitwise operators manipulate individual bits (0s and 1s) of integer data. These operators are
especially useful in low-level programming, system software, embedded systems, device
drivers, and performance-critical applications.

Understanding bitwise operators helps programmers gain deeper insight into how data is stored
and processed inside the computer.

What Are Bitwise Operators?

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

Types of Bitwise Operators in C

C language provides six bitwise operators:

Operator Name

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise NOT (One's Complement)

<< Left Shift

>> Right Shift

1. Bitwise AND (&)

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:

 Masking specific bits


 Checking whether a particular bit is set

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:

 Setting specific bits


 Combining flags

3. Bitwise XOR (^)

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:

 Swapping two numbers without a temporary variable


 Toggling bits

4. Bitwise NOT (~)

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.

5. Left Shift Operator (<<)

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:

 Multiplying a number by powers of 2


 Efficient arithmetic operations

6. Right Shift Operator (>>)

The right shift operator shifts all bits of a number to the right by a specified number of
positions.

Example:

int a = 10; // 00001010


int b = a >> 1; // 00000101 (5)

Uses:

 Dividing a number by powers of 2


 Extracting specific bits

Advantages of Bitwise Operators

SK THOTTARATH 25
Introduction to C Programming

 Faster execution compared to arithmetic operations


 Efficient use of memory
 Essential for low-level and system programming
 Useful in hardware interaction and embedded systems

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

An expression in C can be defined as a valid combination of operands and operators that


yields a result. Operands may be constants, variables, or function calls, while operators specify
the operation to be performed.

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

An expression mainly consists of the following components:

1. Operands – Variables, constants, or values on which operations are performed.


2. Operators – Symbols that specify the operation to be carried out.
3. Constants – Fixed values that do not change during program execution.

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;

Arithmetic expressions may include integers or floating-point values.

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:

if (a > 0 && b > 0)

Logical expressions are widely used in decision-making and looping statements.

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:

condition ? expression1 : expression2;

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

These expressions are commonly used in system-level and embedded programming.

7. Increment and Decrement Expressions

Increment (++) and decrement (--) operators are used to increase or decrease the value of a
variable by one.

Example:

i++;
--count;

These expressions are frequently used in loops.

Operator Precedence in Expressions

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;

The multiplication operator is evaluated first, resulting in the value 20.

Using parentheses can help control the order of evaluation and improve code clarity.

Input and Output Statements in C Programming


Input and output operations are essential parts of any programming language. In C
programming, input statements are used to accept data from the user, while output
statements are used to display results on the screen. These operations allow interaction
between the user and the program, making programs dynamic and useful.

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

Concept of Input and Output in C

 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);

Common Format Specifiers:

 %d – integer
 %f – float
 %c – character
 %s – string

Reading Multiple Values:

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

The printf() function is used to print formatted output to the screen.

Syntax:

printf("format_string", variables);

Example:

int marks = 85;


printf("Marks = %d", marks);

Common Format Specifiers:

 %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

Basic Structure of a C Program

A C program is generally divided into the following main sections:

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:

/* Program to calculate the sum of two numbers */


/* Author: Student */

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

4. Global Declaration Section

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;
}

Features of main() Function:

 Contains executable statements


 Controls the flow of the program

SK THOTTARATH 33
Introduction to C Programming

 return 0 indicates successful program termination

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");
}

Sample C Program Showing Structure

/* Program to display Hello World */


#include <stdio.h>
#define MSG "Hello World"

int main() {
printf(MSG);
return 0;
}

This example demonstrates the basic structure of a C program.

Importance of Structured C Programs

 Improves program readability


 Makes debugging and testing easier
 Supports modular and reusable code
 Enhances program maintenance

SK THOTTARATH 34
Introduction to C Programming

1. Program to Print “Hello World”

#include <stdio.h>

int main() {
printf("Hello World");
return 0;
}

2. Program to Add Two Numbers

#include <stdio.h>

int main() {
int a, b, sum;
a = 10;
b = 20;
sum = a + b;
printf("Sum = %d", sum);
return 0;
}

3. Program to Add Two Numbers Using User Input

#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

4. Program to Find Area of a Rectangle

#include <stdio.h>

int main() {
int length = 5, breadth = 4;
int area = length * breadth;
printf("Area of rectangle = %d", area);
return 0;
}

5. Program to Find Area of a Circle

#include <stdio.h>

int main() {
float radius = 3.5;
float area = 3.14 * radius * radius;
printf("Area of circle = %.2f", area);
return 0;
}

6. Program to Find Simple Interest

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

7. Program to Swap Two Numbers (Using Temporary Variable)

#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;
}

8. Program to Calculate Average of Three Numbers

#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

Control Statements in C Programming


In C programming, control statements are used to control the flow of execution of a program
based on certain conditions. Normally, a program executes statements sequentially from top to
bottom. However, in real-world applications, decisions must be made, and different actions
must be performed depending on different situations. Control statements help achieve this
decision-making capability.

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.

What Are Decision-Making Statements?

Decision-making statements allow a program to evaluate a condition and execute certain


statements only if the condition is true. If the condition is false, the program either skips those
statements or executes an alternative block of code.

Conditions are usually formed using relational and logical operators.

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:

 The condition inside the parentheses is evaluated.


 If the condition is true, the statements inside the if block are executed.
 If the condition is false, the statements are skipped.

SK THOTTARATH 38
Introduction to C Programming

Example:

if (marks >= 40) {


printf("Pass");
}

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:

 If the condition is true, the if block is executed.


 If the condition is false, the else block is executed.

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:

 The outer if condition is checked first.


 If it is true, the inner if condition is evaluated.
 Statements are executed only when all required conditions are satisfied.

Example:

if (marks >= 40) {


if (marks >= 75) {
printf("Distinction");
}
}

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

Advantages of if, if-else, and Nested if Statements

 Enable decision-making in programs


 Make programs flexible and dynamic
 Improve program logic and control
 Useful for validating conditions and data

Differences Between if, if-else, and Nested if

Statement Description

if Executes code only when condition is true

if-else Executes one block if true, another if false

nested if Checks multiple conditions step by step

4. Switch Statement in C Programming


In C programming, decision-making is an essential part of writing useful and practical
programs. While if and if-else statements are commonly used for decision-making, they can
become complex and difficult to read when there are many conditions to check. To overcome
this problem, C provides the switch statement, which is a multi-way decision-making
statement.

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.

What Is a Switch Statement?

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.

Syntax of Switch Statement

switch (expression) {
case constant1:
// statements
break;
case constant2:
// statements
break;
default:
// statements
}

Working of Switch Statement

1. The expression inside the switch is evaluated.


2. The value of the expression is compared with each case label.
3. When a matching case is found, the statements under that case are executed.
4. The break statement terminates the switch block.
5. If no case matches, the default block is executed.

Example of Switch Statement

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.

Importance of break Statement

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.

Rules for Using Switch Statement

 The expression must be an integer or character type.


 Case labels must be constant values.
 Duplicate case values are not allowed.
 The break statement is optional but recommended.
 The default case can appear anywhere in the switch block.

Advantages of Switch Statement

 Makes code easier to read and understand


 Efficient for handling multiple choices
 Reduces complexity compared to multiple if-else statements
 Improves program structure

Limitations of Switch Statement

 Cannot use floating-point values


 Conditions must be constant expressions
 Less flexible compared to if-else ladder

SK THOTTARATH 44
Introduction to C Programming

Looping Statements in C Programming


In C programming, looping statements are used to execute a block of code repeatedly as long
as a specified condition is true. Loops help reduce code repetition and make programs efficient
and concise. Among the looping statements available in C, the while and do-while statements
are important entry-controlled and exit-controlled loops.

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

C programming provides three main looping statements:

1. while loop
2. do-while loop
3. for loop

This essay focuses on the while and do-while looping statements.

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.

Syntax of while Loop

while (condition) {
// statements
}

SK THOTTARATH 45
Introduction to C Programming

Working of while Loop

1. The condition is evaluated first.


2. If the condition is true, the loop body is executed.
3. After executing the statements, control goes back to check the condition again.
4. The loop continues until the condition becomes false.

Example of while Loop

int i = 1;
while (i <= 5) {
printf("%d ", i);
i++;
}

This program prints numbers from 1 to 5.

Advantages of while Loop

 Simple and easy to use


 Suitable when the number of iterations is unknown
 Entry-controlled loop ensures condition checking before execution

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.

Syntax of do-while Loop

do {
// statements
} while (condition);

SK THOTTARATH 46
Introduction to C Programming

Note: The semicolon at the end of the while condition is mandatory.

Working of do-while Loop

1. The loop body is executed first.


2. After execution, the condition is evaluated.
3. If the condition is true, the loop repeats.
4. If the condition is false, the loop terminates.

Example of do-while Loop

int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);

This program also prints numbers from 1 to 5.

Advantages of do-while Loop

 Executes at least once


 Useful for menu-driven programs
 Suitable when one execution is mandatory

Difference Between while and do-while

while Loop do-while Loop

Entry-controlled loop Exit-controlled loop

Condition checked before execution Condition checked after execution

Loop body may not execute Loop body executes at least once

No semicolon after while Semicolon required

SK THOTTARATH 47
Introduction to C Programming

Importance of while and do-while Statements

 Help perform repetitive tasks efficiently


 Reduce code length and duplication
 Improve program clarity and structure
 Essential for real-world programming logic

For Loop in 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.

Syntax of the for Loop


for (initialization; condition; increment/decrement) {
// statements to be executed
}

 Initialization: Sets the starting value of the loop control variable.


 Condition: The loop continues to run as long as this condition is true.
 Increment/Decrement: Updates the loop control variable after each iteration.

How the for Loop Works

1. The initialization statement is executed once at the beginning.


2. The condition is checked.
3. If the condition is true, the loop body executes.
4. After execution, the increment or decrement statement runs.
5. Steps 2–4 repeat until the condition becomes false.

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

Advantages of the for Loop

 Makes code shorter and easier to understand.


 Reduces repetition and improves efficiency.
 Ideal for counting and looping through arrays.

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.

for loop in c programming essay 3 page

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.

For Loop in C Programming

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.

Definition of For Loop

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

Syntax of For Loop

The general syntax of a for loop in C is:

for (initialization; condition; increment/decrement) {


// body of the loop
}

Each part of the syntax has a specific purpose:

 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.

Working of the For Loop

The execution of a for loop follows a step-by-step process:

1. The initialization statement is executed first.


2. The condition is evaluated.
3. If the condition is true, the loop body is executed.
4. After executing the loop body, the increment or decrement statement is executed.
5. The condition is checked again.
6. The loop continues until the condition becomes false.

Once the condition is false, the control exits the loop and moves to the next statement in the
program.

Example of For Loop

Consider the following example that prints numbers from 1 to 5:

#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:

 The variable i is initialized to 1.


 The loop runs as long as i <= 5.
 After each iteration, the value of i is increased by 1.
 The program prints numbers from 1 to 5 on separate lines.

Types of For Loop in C

1. Simple For Loop

This is the most commonly used form where all three parts of the loop are present.

2. Infinite For Loop

If the condition is omitted or always true, the loop runs infinitely.

for (;;) {
printf("Hello\n");
}

This loop continues forever unless terminated using a break statement.

3. Nested For Loop

A for loop inside another for loop is called a nested for loop. It is commonly used in matrix

operations and pattern printing.

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 3; j++) {
printf("* ");
}
printf("\n");
}

SK THOTTARATH 51
Introduction to C Programming

Applications of For Loop

The for loop is widely used in many programming tasks, including:

 Printing series of numbers


 Traversing arrays
 Searching and sorting data
 Performing mathematical calculations
 Generating patterns
 Processing strings and matrices

Because of its flexibility and efficiency, the for loop is essential in both beginner and
advanced C programs.

Advantages of For Loop

1. Reduces code repetition and improves efficiency


2. Easy to read and maintain
3. Best suited for counter-controlled loops
4. Keeps all loop control statements in one place
5. Helps in writing structured and organized programs

Disadvantages of For Loop

1. Not suitable when the number of iterations is unknown


2. Incorrect conditions can lead to infinite loops
3. Beginners may find nested loops confusing

Despite these limitations, proper use of the for loop makes programs more effective and
manageable.

Comparison with Other Loops

 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 and Continue Statements in C Programming


C programming provides various control statements that help programmers manage the flow
of execution in a program. Among these control statements, break and continue play an
important role when working with loops and decision-making structures. These statements
allow programmers to control the execution of loops by either terminating them completely or
skipping certain iterations. Proper use of break and continue statements makes programs more
efficient, readable, and flexible.

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.

Syntax of Break Statement


break;
Working of Break Statement

 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.

Example of Break Statement


#include <stdio.h>

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

 To stop a loop when a required value is found


 To exit infinite loops
 To terminate a switch case
 To improve efficiency by avoiding unnecessary iterations

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.

Syntax of Continue Statement


continue;
Working of Continue Statement

 When continue is encountered, the current iteration ends.


 Control goes to the increment or condition checking part of the loop.
 The loop continues with the next iteration.

Example of Continue Statement


#include <stdio.h>

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.

Uses of Continue Statement

 To skip unwanted values


 To ignore specific conditions
 To simplify loop logic

SK THOTTARATH 54
Introduction to C Programming
 To avoid deeply nested conditional statements

Difference Between Break and Continue

Break Statement Continue Statement

Terminates the loop completely Skips the current iteration

Control exits the loop Control stays inside the loop

Used to stop execution Used to skip execution

Works with loops and switch Works only with loops

Advantages of Break and Continue Statements

1. Improves program control


2. Reduces unnecessary computations
3. Makes code clearer and more flexible
4. Helps in managing complex looping conditions

Disadvantages

1. Overuse may reduce readability


2. Can make program logic harder to follow
3. Not recommended in poorly structured loops

Proper planning and disciplined usage are necessary to avoid confusion.

Nested Loops in C Programming


C programming is a structured and powerful language that allows programmers to solve
complex problems efficiently. One of the most important features of C is its ability to perform
repetitive tasks using loops. Loops such as for, while, and do-while are used to execute a
block of code repeatedly. In many programming situations, a single loop is not sufficient to
solve a problem. In such cases, nested loops are used. A nested loop is a loop inside another
loop, and it plays a crucial role in solving problems related to matrices, patterns, tables, and
multi-dimensional data. Understanding nested loops is essential for developing strong
programming logic.

SK THOTTARATH 55
Introduction to C Programming

Meaning of Nested Loops

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.

Syntax of Nested Loops


The general syntax of nested loops is as follows:

for (initialization; condition; increment) {


for (initialization; condition; increment) {
// statements
}
}

In this structure:

 The outer loop controls the main repetition.


 The inner loop executes completely for every iteration of the outer loop.

Working of Nested Loops


The execution of nested loops follows a systematic pattern:

1. The outer loop starts and checks its condition.


2. If the condition is true, the inner loop begins execution.
3. The inner loop runs fully until its condition becomes false.
4. Once the inner loop completes, control returns to the outer loop.
5. The outer loop updates its counter and repeats the process.
6. This continues until the outer loop condition becomes false.

Thus, the inner loop executes multiple times for each iteration of the outer loop.

SK THOTTARATH 56
Introduction to C Programming

Example of Nested Loops

Simple Nested Loop Example


#include <stdio.h>

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.

Types of Nested Loops

1. For Loop Inside For Loop

This is the most common type of nested loop and is widely used for pattern printing and
matrix operations.

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 3; j++) {
printf("* ");
}
printf("\n");
}

2. While Loop Inside While Loop


int i = 1;
while (i <= 3) {
int j = 1;
while (j <= 3) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
}

SK THOTTARATH 57
Introduction to C Programming

3. Mixed Nested Loops

Different types of loops can also be nested together.

int i = 1;
do {
int j = 1;
while (j <= 3) {
printf("%d ", j);
j++;
}
printf("\n");
i++;
} while (i <= 3);

Applications of Nested Loops


Nested loops are used in various real-world and programming scenarios, such as:

 Printing number and star patterns


 Generating multiplication tables
 Working with two-dimensional arrays
 Matrix addition and multiplication
 Sorting algorithms
 Searching data in multi-dimensional structures
 Game development logic
 Data processing and simulations

Their versatility makes nested loops a fundamental concept in programming.

Pattern Printing Using Nested Loops

Pattern printing is one of the most popular applications of nested loops.

Example: Star Pattern


for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}

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 in Array and Matrix Operations

Two-dimensional arrays require nested loops for processing.

Example: Matrix Input and Output


int a[2][2], i, j;

for (i = 0; i < 2; i++) {


for (j = 0; j < 2; j++) {
scanf("%d", &a[i][j]);
}
}

Nested loops help access each element of the matrix row by row and column by column.

Advantages of Nested Loops

1. Helps solve complex problems easily


2. Essential for multi-dimensional data handling

3. Reduces code duplication


4. Makes pattern and matrix operations simple
5. Improves logical thinking

Disadvantages of Nested Loops


1. Increases program complexity
2. Difficult to debug if poorly written
3. Consumes more execution time
4. Reduces readability when deeply nested

Careful planning and proper indentation are necessary to minimize these disadvantages.

SK THOTTARATH 59
Introduction to C Programming

Comparison Between Single and Nested Loops

Single Loop Nested Loop

Executes one repetition cycle Executes multiple cycles

Simpler logic More complex logic

Used for basic repetition Used for advanced tasks

Less execution time More execution time

SK THOTTARATH 60
Introduction to C Programming

ARRAYS AND RELATED CONCEPTS IN 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.

Arrays help in:

 Reducing code length


 Improving program efficiency
 Organizing related data
 Simplifying complex calculations

3. Single Dimensional Arrays


Meaning of Single Dimensional Array

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];

This array can store 5 integer values.

Defining an Array

The general syntax for defining an array is:

data_type array_name[size];

Example:

float temperature[10];

Here:

 float is the data type


 temperature is the array name
 10 is the size of the array

Array Initialization

Array initialization means assigning values to array elements at the time of declaration.

Method 1: Compile-time Initialization


int num[5] = {1, 2, 3, 4, 5};
Method 2: Partial Initialization
int num[5] = {1, 2};

Remaining elements are set to zero.

Method 3: Without Specifying Size


int num[] = {10, 20, 30};

Accessing Array Elements

Array elements are accessed using index numbers. Indexing starts from 0.

SK THOTTARATH 62
Introduction to C Programming

Example:

printf("%d", num[0]);

To access all elements:

for(int i = 0; i < 5; i++) {


printf("%d ", num[i]);
}

Advantages of Single Dimensional Arrays

 Stores multiple values efficiently


 Reduces number of variables
 Simplifies repetitive tasks
 Improves code readability

Limitations of Arrays

 Fixed size
 Stores only similar data types
 Wastage of memory if size is large

4. Enumerated Data Type (enum)

Meaning of Enumerated Data Type

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>

enum days {Mon, Tue, Wed, Thu, Fri};

int main() {
enum days d;
d = Wed;
printf("%d", d);
return 0;
}

Advantages of enum

 Makes programs more readable


 Improves maintainability
 Restricts values to predefined constants

5. Type Definition (typedef)

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

 Simplifies complex declarations


 Improves code readability
 Useful in structures and pointers

SK THOTTARATH 64
Introduction to C Programming

6. Two Dimensional Arrays


Meaning of Two Dimensional Array

A two-dimensional array is an array of arrays. It is commonly used to represent tables,


matrices, and grids.

Example:

int matrix[3][3];

Defining a Two-Dimensional Array

Syntax:

data_type array_name[rows][columns];

Example:

int marks[2][3];

Initialization of Two-Dimensional Array


int matrix[2][2] = {{1, 2}, {3, 4}};

Accessing Two-Dimensional Array Elements


printf("%d", matrix[0][1]);

7. Programs for Matrix Processing

Matrix Addition Program


#include <stdio.h>

int main() {
int a[2][2], b[2][2], sum[2][2], i, j;

SK THOTTARATH 65
Introduction to C Programming

for(i = 0; i < 2; i++)


for(j = 0; j < 2; j++)
scanf("%d", &a[i][j]);

for(i = 0; i < 2; i++)


for(j = 0; j < 2; j++)
scanf("%d", &b[i][j]);

for(i = 0; i < 2; i++)


for(j = 0; j < 2; j++)
sum[i][j] = a[i][j] + b[i][j];

return 0;
}

Matrix Multiplication (Concept)

 Rows of first matrix × columns of second matrix


 Uses three nested loops
 Common application of two-dimensional arrays

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

1. Start from first element


2. Compare with key
3. If match found, stop
4. Else move to next element

Program for Sequential Search


#include <stdio.h>

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;
}

Advantages of Sequential Search

 Simple to understand
 Works on unsorted data
 Easy to implement

Disadvantages

 Slow for large datasets


 Time-consuming

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.

Working of Bubble Sort

 Largest element moves to the end in each pass


 Process repeats until list is sorted

Bubble Sort Program


#include <stdio.h>

int main() {
int a[5] = {5, 1, 4, 2, 8};
int i, j, temp;

for(i = 0; i < 5-1; i++) {

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;
}

Advantages of Bubble Sort

 Easy to understand
 Simple implementation
 Useful for small data sets

Disadvantages

 Very slow for large data


 Not efficient

10. Applications of Arrays and Sorting


 Student records management
 Banking systems
 Inventory control
 Data analysis
 Scientific calculations
 Image processing
 Game development

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.

A string in C is a sequence of characters stored in an array of characters and terminated by a


special character called the null character ('\0'). Strings are widely used in real-world
applications such as text editors, databases, operating systems, web applications, and
communication software. Understanding strings is essential for effective programming in C.

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:

char name[] = "Computer";

The string "Computer" is stored as:

C o m p u t e r \0

3. Declaring a String Variable


Since strings are stored as character arrays, declaring a string variable involves declaring a
character array.

Syntax
char string_name[size];

SK THOTTARATH 69
Introduction to C Programming

Example
char city[20];

Here:

 char specifies the character data type


 city is the string variable name
 20 is the maximum number of characters the string can hold (including '\0')

4. Initialization of Strings
Strings can be initialized in several ways.

Method 1: Using String Literal


char name[] = "C Programming";

Method 2: Character-wise Initialization


char name[] = {'C','o','m','p','u','t','e','r','\0'};

Method 3: Declaring and Assigning Later


char name[20];
strcpy(name, "Computer");

5. Reading Strings in C
C provides different ways to read strings from the user.

5.1 Using scanf()


scanf("%s", name);

⚠ Limitation: scanf() stops reading at whitespace.

5.2 Using gets() (Not Recommended)


gets(name);

SK THOTTARATH 70
Introduction to C Programming

 Reads the entire line


 Unsafe due to buffer overflow risk

5.3 Using fgets() (Recommended)


fgets(name, sizeof(name), stdin);

 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);

 Automatically moves to the next line


 Simple and efficient

7. String Handling Library (string.h)


C provides a standard library called <string.h> which contains predefined functions for
string manipulation.

Commonly Used String Functions:

 strlen()
 strcpy()
 strcat()
 strcmp()

SK THOTTARATH 71
Introduction to C Programming

 strlwr()
 strupr()
 strrev()

8. String Related Library Functions


8.1 strlen() – Find Length of String
#include <string.h>
int len = strlen(name);

Returns the number of characters excluding '\0'.

8.2 strcpy() – Copy String


strcpy(dest, src);

Example:

char a[20], b[20] = "Hello";


strcpy(a, b);

8.3 strcat() – Concatenate Strings


strcat(str1, str2);

Example:

char a[20] = "C ";


char b[] = "Programming";
strcat(a, b);

8.4 strcmp() – Compare Strings


strcmp(str1, str2);

Returns:

 0 if equal

SK THOTTARATH 72
Introduction to C Programming

 Negative if str1 < str2


 Positive if str1 > str2

8.5 strlwr() and strupr()


strlwr(name); // lowercase
strupr(name); // uppercase

8.6 strrev() – Reverse String


strrev(name);

9. Programs Using String Functions


Program: Find Length of String
#include <stdio.h>
#include <string.h>

int main() {
char str[50];
fgets(str, 50, stdin);
printf("Length = %d", strlen(str));
return 0;
}

10. String Matching in C Programming


Meaning of String Matching

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.

11. Methods of String Matching


1. Using built-in functions
2. Using user-defined logic (manual comparison)

SK THOTTARATH 73
Introduction to C Programming

12. String Matching Using Library Function


Using strcmp()
#include <stdio.h>
#include <string.h>

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;
}

13. Manual String Matching Program


Program Without Using Library Functions
#include <stdio.h>

int main() {
char s1[50], s2[50];
int i = 0, flag = 1;

scanf("%s %s", s1, s2);

while(s1[i] != '\0' || s2[i] != '\0') {


if(s1[i] != s2[i]) {
flag = 0;
break;
}
i++;
}

if(flag)
printf("Strings are equal");
else
printf("Strings are not equal");

return 0;
}

SK THOTTARATH 74
Introduction to C Programming

14. Substring Matching Program


#include <stdio.h>
#include <string.h>

int main() {
char text[100], pattern[20];

fgets(text, 100, stdin);


fgets(pattern, 20, stdin);

if(strstr(text, pattern))
printf("Pattern found");
else
printf("Pattern not found");

return 0;
}

15. Applications of String Matching


 Text editors
 Search engines
 Spell checkers
 DNA sequence matching
 Plagiarism detection
 Compiler design

16. Advantages of Using Strings


 Easy storage of text data
 Simplifies input/output operations
 Wide library support
 Essential for real-world applications

17. Limitations of Strings in C


 Fixed size
 No built-in string type
 Manual memory management
 Risk of buffer overflow

SK THOTTARATH 75
Introduction to C Programming

18. Best Practices for String Handling


 Use fgets() instead of gets()
 Always check array size
 Use <string.h> functions carefully
 Avoid unnecessary copying

19. Comparison Between Character Array and String


Character Array String

Stores characters Stores text

No termination required Ends with '\0'

Manual handling Library support

20. Importance of Strings in C Programming


Strings play a vital role in:

 User interaction
 File handling
 Data communication
 Software development

Without strings, meaningful interaction between programs and users would not be possible.

SK THOTTARATH 76

You might also like