0% found this document useful (0 votes)
15 views72 pages

C Programming Notes Unit-1&2

Uploaded by

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

C Programming Notes Unit-1&2

Uploaded by

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

Unit-1

Basics of C, I/O, Branching and Loops


What is C Programming?
C is a powerful and flexible programming language used for a wide range of applications, from developing
software to operating systems. It’s known for its ability to interact directly with hardware, making it an
excellent choice for tasks that require high performance and efficiency.

C allows programmers to write code that runs fast, while also offering features like structured
programming and a rich set of functions. Even though it’s considered a low-level language, C provides a
solid foundation for learning other programming languages like C++, Java, and Python.

Key Features of C Language


Below are the main C programming features that make it popular and widely used:

 Simple and Efficient: C offers straightforward syntax and commands, making it easy to learn
and use while maintaining high performance.
 Structured Programming: C language allows the breaking down of a program into
functions, making the code easier to understand and manage.
 Low-level Access: C gives direct access to memory through pointers, allowing fine control over
hardware resources.
 Portability: C programs can be run on different machines with minimal or no modification.
 Rich Library Support: C language has a vast collection of built-in functions and libraries
for various tasks.
 Modularity: C enables code reusability by allowing functions and modules to be reused
in different programs.
 Dynamic Memory Allocation: C programming language provides functions to allocate memory
dynamically, giving control over memory management.
 Fast Execution: Programs written in C are compiled, making them faster compared to interpreted
languages.

Why is C Language Still Popular?


C is still popular for several reasons, despite being one of the oldest programming languages:

1. High Performance

C is known for its speed. The language allows for direct memory manipulation, which makes it ideal for
systems where performance is critical, like operating systems and embedded systems.

2. System-Level Programming
C is widely used in developing operating systems, drivers, and other low-level software. It gives
programmers close control over the hardware, which is essential for system-level tasks.

3. Foundation for Other Languages

Many modern languages like C++, Java, and Python are either directly based on or influenced by C. Learning
C provides a solid foundation for learning other programming languages.

4. Portability

C programs can be easily adapted to different machines and operating systems with minimal changes, making
it a versatile choice for cross-platform development.

5. Widely Used in Industry

C is still the go-to language in industries like embedded systems, game development, and operating system
development. It is also heavily used in compilers and network programming.

6. Community and Resources

With its long history, C has a vast community and a wealth of learning resources, libraries, and frameworks,
making it easier for beginners to find support.

Basic Structure of C Program


Syntax

A C program consists of the following elements:

 Headers: These include necessary libraries using #include, such as #include <stdio.h>, which
allows input/output functions.

 Main Function: Every C program must have a main() function, which is the entry point of
the program.

 Statements: Inside main(), we write the program logic, typically as a series of function calls
and operations.

 Semicolons and Braces: Semicolons (;) are used to end statements, and braces ({ }) define code
blocks, ensuring the program’s structure.

Example: "Hello, World!" Program

#include <stdio.h>

int main() {
printf("Hello, World!\n"); }
Output:
Hello, World!
Explanation:

 #include <stdio.h>: Includes the standard I/O library for printf().


 int main(): Entry point of the program.
 printf("Hello, World!\n");: Prints "Hello, World!" to the console

Basics of C Language
Now that you know what is C programming and its key features & uses, let’s move to learn the basics of C:

1. Data Types

C supports multiple data types to store different kinds of values:

Category Data Types

Basic Data Types int (for integers), float (for floating-point numbers), double (for precision floating-point),
char (for characters)

Derived Data Arrays, pointers, and functions


Types

User-defined struct (structure), union, and enum


Types

2. Variables

Variables in C store data and need to be declared with a specific data type.

For example, int a; declares an integer variable a. Variables must be declared before they are used.

3. Operators

There are several operators in C to perform different operations on variables:

Category Description

Arithmetic Operators + (Addition)


- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
Relational Operators == (Equal to)
!= (Not equal to)
> (Greater than)
< (Less than)
>= (Greater than or equal to)
<= (Less than or equal to)

Logical Operators && (Logical AND)


|| (Logical OR)
! (Logical NOT)

Bitwise Operators & (AND)


| (OR)
^ (XOR)
~ (NOT)
<< (Left Shift)
>> (Right Shift)

Assignment Operators = (Simple assignment)


+= (Add and assign)
-= (Subtract and assign)
*= (Multiply and assign)
/= (Divide and assign)
%= (Modulus and assign)

Unary Operators ++ (Increment)


-- (Decrement)

Ternary Operator ? : (for conditional expressions)

4. Control Structures

Control structures are used to direct the flow of execution in a program:

 Decision Making: if, else, switch statements.


 Loops: for, while, and do-while loops for repeated execution of a block of code.
 Break and Continue: These statements alter the flow within loops.

5. Functions

C programs are modular and reusable through functions. A function is defined with a return type, a name,
and parameters (optional).

For example:

int add(int a, int b) {


return a + b;
}
Functions help break the code into smaller, manageable parts.
6. Pointers

Pointers are variables that store the memory address of another variable. They are an essential feature of C,
allowing for:

 Dynamic memory allocation.


 Efficient array and string manipulation.
 Function pointers, passing by reference.

7. Arrays

Arrays in C are used to store multiple values of the same data type. They are defined by specifying the data
type, followed by square brackets:

int arr[10]; // Array of 10 integers


8. Strings

Strings in C are arrays of characters terminated by a null character (\0).

They are declared as:

char str[20] = "Hello, World!";


9. Structures

Structures are user-defined data types that group different types of data together.

Example

struct student {
int id;
char name[50];
float marks;
};

10. Dynamic Memory Allocation

C provides functions like malloc(), calloc(), realloc(), and free() to allocate and deallocate memory
dynamically. This gives programmers control over the system’s memory.

11. File Handling

C allows reading from and writing to files using functions like fopen(), fclose(), fread(), fwrite(), and more
from the <stdio.h> library. File operations are important for saving data permanently.

12. Preprocessor Directives

C programs use preprocessor directives like #include and #define for including files and macros, which are
processed before compilation
13. Comments

Comments in C are ignored by the compiler and are used to make the code more readable:

 Single-line Comment:// This is a comment


 Multi-line Comment:/* This is a multi-line comment */

Keywords in C
We will first go through the definition of keywords in C.

The keywords are reserved words that have predefined meanings and functions within the C language.
These words cannot be used as variable names, function names, or identifiers because they are integral to
the language's syntax.

For example, int, if, return, and for are commonly used C keywords. Each keyword has a specific purpose,
and knowing how to use them correctly is essential for writing functional C programs.

List of Keywords in C
The total number of keywords in C language is 32. The table below presents all 32 keywords:

Keyword Meaning

auto Declares automatic (local) variables.

break Exits from loops or switch statements.

case Defines a case in a switch statement.

char Declares a character variable.

const Declares a constant, immutable value.

continue Skips the current iteration of a loop and proceeds to the next one.

default Specifies the default case in a switch statement.

do Executes a block of code at least once in a do-while loop.

double Declares a double-precision floating-point variable.

else Specifies the alternative branch in an if-else statement.

enum Declares an enumeration, which is a list of named integer constants.

extern Declares a global variable or function that is defined elsewhere.

float Declares a floating-point variable.

for Starts a loop that repeats until a condition is false.

goto Transfers control to a labeled statement.


if Specifies a condition to execute a block of code.

int Declares an integer variable.

long Declares a long integer variable.

register Declares a variable that should be stored in a register for quick access.

return Exits a function and optionally returns a value.

short Declares a short integer variable.

signed Declares a signed variable that can hold both positive and negative values.

sizeof Returns the size, in bytes, of a data type or variable.

static Declares variables with static lifetime or functions with limited visibility.

struct Declares a structure, a collection of variables of different data types.

switch Starts a multi-way branch based on the value of a variable.

typedef Defines a new name for an existing data type.

union Declares a union, a data type that can store different data types in the same memory location.

unsigned Declares a variable that holds only non-negative values.

void Specifies that a function does not return a value.

volatile Indicates that a variable’s value can be changed unexpectedly.

while Starts a loop that repeats while a condition is true.

Data Types in C
Data types in C program help define the kind of data a variable can store, like numbers or letters. Each
data type tells the compiler how much memory to allocate and how to interpret the data.

For instance, numbers without decimal points use a type like int, while numbers with decimal points use
float or double. Characters, which store single letters or symbols, use the char type.

Data types are essential for organizing information efficiently and ensuring your program works as
expected by managing memory properly.

Types of Data Type in C Language


C program data types are classified into three main categories:

1. Basic Data Types: These include fundamental types like int (for integers), char (for characters), float
(for floating-point numbers), and double (for double-precision floating-point numbers).
2. Derived Data Types: These are derived from basic data types and include arrays,
pointers, and functions.

3. User-Defined Data Types: These are created by the programmer and include structures (struct),
unions (union), and enumerations (enum).

Basic Data Types Derived Data Types User-Defined Data Types

int Arrays struct

char Pointers union

float Functions enum

double typedef

void

Data Types in C With Size and Range


Different data types in C consume varying amounts of memory. For example, an int uses 2 or 4 bytes, a
char uses 1 byte, a float uses 4 bytes, and a double uses 8 bytes. The size of these data types can vary
depending on the system architecture (32-bit vs. 64-bit).

The table below shows the data types in C and their size along with range:

Data Memory Signed Range Unsigned Range


Type Size

char 1 byte -128 to 127 0 to 255

short 2 bytes -32,768 to 32,767 0 to 65,535

int 4 bytes -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295

long 4 bytes -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295

long 8 bytes -9,223,372,036,854,775,808 to 0 to


long 9,223,372,036,854,775,807 18,446,744,073,709,551,615

float 4 bytes 3.4E-38 to 3.4E+38 N/A

double 8 bytes 1.7E-308 to 1.7E+308 N/A


sizeof Operator:

The sizeof operator is used to determine the size (in bytes) of any data type or variable.

Example:

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


Output:

Size of int: 4 bytes


This helps programmers manage memory efficiently.

Variables in C
Variables in C language are like containers used to store data that a program needs to process. Imagine
you’re working with numbers or words while solving a problem. In the same way, a C program uses
variables to store values such as numbers, characters, or more complex types of data.

Each variable has a name, a type, and a value. The type defines what kind of data the variable can hold,
like an integer or a decimal number. The variable's name helps us refer to it later in the code, and its value
is the actual data stored in it.

Syntax for Declaration of Variables in C


The general syntax for declaring variables in C is as follows:

data_type variable_name;
 data_type: Specifies the type of data the variable will hold, such as int for integers, float
for floating-point numbers, or char for characters.
 variable_name: The name you assign to the variable, which must follow the rules for
valid identifiers in C (e.g., must start with a letter or underscore, no spaces, etc.).

Example:

int age; // Declares an integer variable named 'age'


float salary; // Declares a floating-point variable named 'salary'
char grade; // Declares a character variable named 'grade'

Multiple variables of the same type can also be declared in one line:

int x, y, z;

Types of Variables in C
C language variables can be classified into several types based on their scope, lifetime, and storage class:
1. Local Variables
Local variables in C are declared inside a function or a block of code and can only be accessed within that
specific function or block. Their scope is limited to the function they are declared in, and their lifetime
exists only as long as the function is executing.

Example:

void display() {
int x = 10; // Local variable
printf("%d", x); // Can be accessed only within this function
}
 Scope: Limited to the function/block they are declared in.
 Lifetime: Exists only while the function or block is executing.

2. Global Variables

Global variables in C are declared outside of all functions, usually at the beginning of the program. They
can be accessed by any function within the same program, making their scope the entire program.
Global variables retain their values throughout the program’s execution.

Example:

int globalVar = 100; // Global variable

void function1() {
printf("%d", globalVar); // Accessible here
}

void function2() {
printf("%d", globalVar); // Accessible here too
}
 Scope: Entire program (available to all functions).
 Lifetime: Exists for the entire duration of the program.

3. Static Variables

Static variables in C can be either local or global, but their key feature is that they retain their value
between function calls. If declared inside a function, a static variable is initialized only once and
maintains its value across multiple calls to that function.

Example:

void increment() {
static int count = 0; // Static variable
count++;
printf("%d", count);
}

int main() {
increment(); // Output: 1
increment(); // Output: 2 (retains value from previous call)
return 0;
}
 Scope: If declared globally, they have global scope. If declared locally, they are limited to
the function but retain their value across function calls.
 Lifetime: Exists for the entire duration of the program.

4. Automatic Variables

By default, all local variables in C are automatic variables. These variables are created when a function is
called and destroyed when the function exits. The keyword auto can be used to explicitly declare automatic
variables, though it is rarely used as this is the default behavior.

Example:

void display() {
auto int x = 5; // Automatic variable (default behavior for local variables)
printf("%d", x);
}
 Scope: Limited to the function/block they are declared in.
 Lifetime: Exists only during the function’s execution.

5. External Variables (extern)

External variables in C language are declared outside of all functions (like global variables) but can be
accessed across multiple files in a project using the extern keyword. They are defined in one file and can
be used in others by declaring them with extern.

Example (File 1 - Declaration):

int globalVar = 50; // External/global variable


Example (File 2 - Usage):

extern int globalVar; // Referencing external variable


void display() {
printf("%d", globalVar); // Can be accessed in this file
}
 Scope: Entire program across multiple files.
 Lifetime: Exists for the entire duration of the program.

Rules for Naming Variables in C


The following are the main rules for naming variables in C programming:

Rule Description Example

Start with a Letter or Variable names must begin with a letter (a-z, int age;, float _salary;
Underscore A-Z) or an underscore (_), but not a number.

No Spaces Allowed Variable names cannot contain spaces. int user_age; (correct), int
user age; (incorrect)
Only Letters, Digits, and After the first character, variable names can char name1;, int
Underscores have letters, digits, and underscores (_). employee_id;

Case-Sensitive C is case-sensitive, so age, Age, and AGE are int Age;, int age; (distinct)
different variables.

No Reserved Keywords Variable names cannot be any of the C int return; (incorrect)
language’s reserved keywords (e.g., int, float).

No Special Characters Special characters like @, #, %, etc., are not int num@; (incorrect)
allowed.

Reasonable Length It’s a good practice to keep variable names —


concise and readable, though no strict limit
exists.

Avoid Starting with Variable names cannot start with a digit. int 1number; (incorrect), int
Numbers number1; (correct)

Operators in C
Operators in C are symbols that instruct the compiler to perform specific operations on variables and data.
They are used to manipulate data, perform calculations, make decisions, and control the flow of a program.
Operators work with operands, which are the values or variables involved in the operation.

C programming provides various categories of operators, such as arithmetic, relational, logical, bitwise,
and more. Each type of operator serves a different purpose, from performing basic arithmetic operations
to advanced bit-level manipulations.

For instance:

 If you want to add two numbers, you use the + operator.


 If you want to compare two values, you use operators like > (greater than) or < (less than).
 If you want to check if something is true or false, you use logical operators like && (AND) or
|| (OR).

Arithmetic Operators in C
Arithmetic operators in C language are used to perform basic mathematical operations on variables and
values. These include addition, subtraction, multiplication, division, and modulus operations.

Arithmetic operators work on numeric data types like int and float. They help perform simple and complex
calculations efficiently.
Name of the Operator Arithmetic Operation Syntax

Addition Adds two operands a+b

Subtraction Subtracts one from another a-b

Multiplication Multiplies two operands a*b

Division Divides one by another a/b

Modulus Finds the remainder a%b

Example:
// C program to demonstrate arithmetic operators
#include <stdio.h>

int main() {
int x = 15, y = 6;
int result;

// Print initial values


printf("x = %d and y = %d\n", x, y);

// Addition
result = x + y;
printf("x + y = %d\n", result);

// Subtraction
result = x - y;
printf("x - y = %d\n", result);

// Multiplication
result = x * y;
printf("x * y = %d\n", result);

// Division
result = x / y;
printf("x / y = %d\n", result);

// Modulus
result = x % y;
printf("x %% y = %d\n", result); // Use %% to print '%'

return 0;
}
Output:
x = 15 and y = 6
x + y = 21
x-y=9
x*y=
90 x / y =
2 x%y
=3
Relational Operators in C
Relational operators in C language are used to compare two values. They evaluate the relationship between
the operands and return true (1) or false (0) based on the result.

These operators are generally used in conditional statements in C, such as if, while, and for, to control the
flow of the program.

Operator Symbol Name Syntax

== Equal to x == y

!= Not equal to x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Example:

// C program to demonstrate relational operators


#include <stdio.h>

int main() {
int a = 12, b = 8;

// Printing a and b
printf("a = %d and b = %d\n", a, b);

// Equal to
if (a == b) {
printf("a is equal to b\n");
} else {
printf("a is not equal to b\n");
}

// Not equal to
if (a != b) {
printf("a is not equal to b\n");
}

// Greater than
if (a > b) {
printf("a is greater than b\n");
}

// Less than
if (a < b) {
printf("a is less than b\n");
}
// Greater than or equal to
if (a >= b) {
printf("a is greater than or equal to b\n");
}

// Less than or equal to


if (a <= b) {
printf("a is less than or equal to b\n");
}

return 0;
}
Output:

a = 12 and b = 8
a is not equal to b
a is not equal to b
a is greater than b
a is greater than or equal to b

Logical Operators in C
Logical operators in C language are used to combine or invert conditions, returning true (1) or false (0)
based on the evaluation of the expressions. They are essential for decision-making in conditional
statements, such as if, while, and for.

Types of Logical Operators:

 AND (&&): Returns true if both conditions are true.


 OR (||): Returns true if at least one condition is true.
 NOT (!): Inverts the value of the condition.

Example:

// C program to demonstrate logical


operators #include <stdio.h>

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

// AND operator
if (x > 0 && y > 0) {
printf("Both x and y are positive\n");
}

// OR operator
if (x > 0 || y < 0) {
printf("At least one condition is true\n");
}

// NOT operator
if (!(x == y)) {
printf("x is not equal to y\n");
}

return 0;
}
Output:

Both x and y are positive


At least one condition is true
x is not equal to y

Bitwise Operators in C
Bitwise operators in C language allow operations directly on bits of integer values. These operators are
used for manipulating individual bits within an integer, making them essential for low-level programming,
cryptography, and hardware interactions. The operations are performed at the binary level.

Types of Bitwise Operators:

 AND (&): Performs a bitwise AND.


 OR (|): Performs a bitwise OR.
 XOR (^): Performs a bitwise XOR (exclusive OR).
 NOT (~): Inverts the bits.
 Left Shift (<<): Shifts bits to the left.
 Right Shift (>>): Shifts bits to the right.

Example:

// C program to demonstrate bitwise operators


#include <stdio.h>
int main() {
int a = 5, b = 3, result;

// Bitwise AND
result = a & b;
printf("a & b = %d\n", result); // 1

// Bitwise OR
result = a | b;
printf("a | b = %d\n", result); // 7

// Bitwise XOR
result = a ^ b;
printf("a ^ b = %d\n", result); // 6

// Bitwise NOT
result = ~a;
printf("~a = %d\n", result); // -6

// Left shift
result = a << 1;
printf("a << 1 = %d\n", result); // 10

// Right shift
result = a >> 1;
printf("a >> 1 = %d\n", result); // 2

return 0;
}
Output:

a&b=
1a|b=
7 a^b=
6
~a = -6
a << 1 = 10
a >> 1 = 2

Assignment Operators in C
Assignment operators in C programming are used to assign values to variables. The basic assignment
operator is = which assigns the right-hand value to the left-hand variable. C also provides compound
assignment operators like +=, -=, *=, and /= for shorthand operations, combining arithmetic and
assignment.

Operator Symbol Name Syntax

= Assignment a=b

+= Add and Assign a += b

-= Subtract and Assign a -= b

*= Multiply and Assign a *= b

/= Divide and Assign a /= b

%= Modulus and Assign a %= b


Example:

// C program to demonstrate assignment operators


#include <stdio.h>

int main() {
int a = 10, b = 5;

// Basic assignment
a = b;
printf("a = %d\n", a); // a becomes 5

// Compound assignment operators


a += 3; // equivalent to a = a + 3
printf("a += 3 -> %d\n", a);

a *= 2; // equivalent to a = a * 2
printf("a *= 2 -> %d\n", a);

a -= 4; // equivalent to a = a - 4
printf("a -= 4 -> %d\n", a);
a /= 3; // equivalent to a = a / 3
printf("a /= 3 -> %d\n", a);

return 0;
}
Output:

a=5
a += 3 -> 8
a *= 2 -> 16
a -= 4 -> 12
a /= 3 -> 4

Increment and Decrement Operators in C


Increment (++) and decrement (--) operators in C are used to increase or decrease the value of a variable by
1. They can be used in two forms: prefix (before the variable) and postfix (after the variable).

In prefix, the operation is performed before the value is used, while in postfix, the original value is used
first, and then the operation is performed.

Operator Symbol Name Syntax

++ Increment ++x or x++

-- Decrement --x or x--

Example:

// C program to demonstrate increment and decrement operators


#include <stdio.h>

int main() {
int x = 5;

// Postfix increment
printf("x++ = %d\n", x++); // Prints 5, then x becomes 6

// Prefix increment
printf("++x = %d\n", ++x); // Increments to 7, then prints 7

// Postfix decrement
printf("x-- = %d\n", x--); // Prints 7, then x becomes 6

// Prefix decrement
printf("--x = %d\n", --x); // Decrements to 5, then prints 5

return 0;
}
Output:

x++ = 5
++x = 7
x-- = 7 --x = 5
Conditional (Ternary) Operator in C
The conditional or ternary operator in C is a shorthand way of writing an if-else statement. It uses the
symbols ? and : and returns one of two values depending on the evaluation of a condition.

If the condition is true, the first expression is executed, otherwise, the second expression is executed.

Syntax:

condition ? expression_if_true : expression_if_false;


Example:

// C program to demonstrate conditional operator


#include <stdio.h>

int main() {
int a = 10, b = 20;
int max;

// Conditional operator to find the maximum value


max = (a > b) ? a : b;
printf("The maximum value is %d\n", max);

return 0;
}
Output:

The maximum value is 20

sizeof Operator in C
The sizeof operator in C is used to determine the size, in bytes, of a data type or a variable. It returns the
memory size required to store the variable or type and is essential for dynamic memory allocation and
understanding memory usage in programs.

The sizeof operator is evaluated at compile-time, except in the case of dynamically allocated memory.

Example:

// C program to demonstrate sizeof operator


#include <stdio.h>

int main() {
int a = 10;
double b = 12.5;

// Using sizeof operator


printf("Size of int: %zu bytes\n", sizeof(a));
printf("Size of double: %zu bytes\n", sizeof(b));
printf("Size of char: %zu bytes\n", sizeof(char));

return 0;
}
Output:

Size of int: 4 bytes


Size of double: 8 bytes
Size of char: 1 byte

Operator Precedence in C
Operator precedence in C programming defines the priority of operators when evaluating an expression. It
decides which operator gets applied first when there are multiple operators.

For example, multiplication (*) has higher precedence than addition (+), so it is evaluated first unless
parentheses are used to change the order. Precedence ensures that expressions are evaluated correctly.

Imagine a to-do list where tasks are ranked by importance. High-priority tasks (like an urgent meeting) are
done first, even if other tasks (like checking emails) are listed before them.

Example:

In x = 3 + 4 * 2;, multiplication is done first.

So x becomes 3 + 8 = 11.

What is Associativity of Operators in C?


Operator associativity in C programming tells us the order in which operators of the same precedence are
evaluated. It shows whether the evaluation starts from the left and moves to the right, or from the right and
moves to the left.

Think of a group of kids taking turns on a swing. If the rule is left-to-right, the kid on the left swings first.
If the rule is right-to-left, the kid on the right goes first.

Associativity helps to avoid confusion when there are multiple operators in an expression.

Types of Associativity:

 Left-to-right: Most operators, like +, -, or *, follow this rule.


 Right-to-left: Operators like = (assignment) or ? : (conditional) follow this rule.

Example:

In x = y = 10;, the right-to-left associativity means y = 10 happens first, then x = 10.


Associativity and Precedence Table in C Language
Below is the Operator Precedence and Associativity Table:

Precedence Operator Description Associativity

1 () [] -> . Parentheses, Array subscript, Member access Left-to-right

2 ++ -- Postfix increment/decrement Left-to-right

3 ++ -- + - ~ ! Prefix increment/decrement, Unary plus/minus, Logical Right-to-left


NOT, Bitwise NOT

4 */% Multiplication, Division, Modulus Left-to-right

5 +- Addition, Subtraction Left-to-right

6 << >> Bitwise shift left, shift right Left-to-right

7 < <= > >= Relational operators Left-to-right

8 == != Equality operators Left-to-right

9 & Bitwise AND Left-to-right

10 ^ Bitwise XOR Left-to-right

11 ` ` Bitwise OR

12 && Logical AND Left-to-right

13 ` `

14 ?: Conditional operator Right-to-left

15 = += -= *= /= Assignment operators Right-to-left


%=

16 , Comma operator Left-to-right

Things to Remember:

1. The Precedence column indicates priority; higher numbers mean lower precedence.
2. Associativity decides the direction of operation when operators have the same precedence.
3. Use parentheses to explicitly set the order of operations and ensure clarity in complex expressions.

Examples of Operator Precedence in C


Let’s know understand the operator precedence in C with example:
Example 1: Multiplication and Addition

int x = 5 + 3 * 2;
Explanation:

Multiplication (*) has higher precedence than addition (+).

Execution:

First 3 * 2 = 6, then 5 + 6 = 11.

Result:

x = 11.
Example 2: Parentheses to Change Precedence

int x = (5 + 3) * 2;
Explanation:

Parentheses () have the highest precedence, so the addition happens first.

Execution:

First 5 + 3 = 8, then 8 * 2 = 16.

Result:

x = 16.
Example 3: Relational and Logical Operators

int a = 10, b = 5, c = 2;
int result = a > b && b > c;

Explanation:

Relational operators (>) are evaluated first because they have higher precedence than logical AND (&&).

Execution:

a > b → 10 > 5 → true (1).

b > c → 5 > 2 → true (1).

true && true → 1 && 1 → true (1).

Result:

result = 1.
Example 4: Division and Modulus

int x = 20 / 4 % 3;
Explanation:

Division (/) and modulus (%) have the same precedence, so they are evaluated left to right.

Execution:

20 / 4 = 5.

5 % 3 = 2.

Result:

x = 2.
Example 5: Assignment with Arithmetic

int x = 5;
x = 10 + x * 2;
Explanation:

Multiplication (*) happens first because it has higher precedence than addition (+).

Execution:

x * 2 → 5 * 2 = 10.

10 + 10 = 20.

x = 20.

Result:

x = 20.

Examples of Associativity of Operators in C


Let’s understand associativity of operators in C with example:

Example 1: Left-to-Right Associativity (Arithmetic Operators)

int x = 10 - 5 - 2;
Explanation:

The subtraction (-) operator has left-to-right associativity.

Execution:

First, 10 - 5 = 5.
Then, 5 - 2 = 3.

Result:

x = 3.
Example 2: Right-to-Left Associativity (Assignment Operators)

int x, y, z;
x = y = z = 5;
Explanation:

The assignment (=) operator has right-to-left associativity.

Execution:

First, z = 5.

Then, y = 5 (using the result of z).

Finally, x = 5 (using the result of y).

Result:

x = 5, y = 5, z = 5.
Example 3: Conditional Operator (?:)

int x = 10, y = 5;
int result = (x > y) ? (x - y) : (y - x);
Explanation:

The conditional operator (?:) has right-to-left associativity.

Execution:

Evaluate (x > y) → 10 > 5 → true.

Since the condition is true, execute (x - y) → 10 - 5 = 5.

Result:

result = 5.
Example 4: Logical AND (&&) and OR (||)

int a = 1, b = 0, c = 1;
int result = a && b || c;
Explanation:

Both && and || have left-to-right associativity.

Execution:
First, evaluate a && b → 1 && 0 → 0.

Then, evaluate 0 || c → 0 || 1 → 1.

Result:

result = 1.
Example 5: Mixed Operators with Associativity

int x = 5 + 10 / 2 * 3;
Explanation:

 Division (/) and multiplication (*) have left-to-right associativity.


 Addition (+) has lower precedence, so it is executed last.

Execution:

First, 10 / 2 = 5.

Then, 5 * 3 = 15.

Finally, 5 + 15 = 20.

Result:

x = 20.

How Operator Precedence and Associativity in C Work


Together?
Precedence determines which operator is executed first in an expression, while associativity determines
the direction of execution when operators have the same precedence. Together, they help in resolving
complex expressions and deciding the correct order of operations.

1. Check Precedence First

 Identify the operators in the expression.


 Start with the operator with the highest precedence.

2. Use Associativity for Same Precedence

If two or more operators have the same precedence, use their associativity (left-to-right or right-to-left) to
decide the order.

3. Execute the Operators

Perform the operations step by step, following operator precedence and associativity rules.
4. Use Parentheses to Override

Parentheses have the highest precedence and can be used to change the natural order of execution.

Constants in C
Constants in C programming are fixed values that do not change during the execution of a program. Unlike
variables, which can store different values throughout the program’s runtime, constants are used to
represent data that remains the same.

For example, if you need to use the value of pi (3.14159) or the number of days in a week (7), you can
define them as constants so they cannot be accidentally changed.

Constants help make your code more reliable and easier to understand by ensuring that important values
stay unchanged, making the program predictable and reducing errors.

Difference Between Constants and Variables in C


Let’s know about the difference between variables and constants in C programming:

Feature Constants Variables

Definition Constants are fixed values that cannot be Variables are data holders whose values can be
changed once defined. modified during program execution.

Value Cannot be changed after initialization. Can be changed throughout the program.
Modification

Declaration Declared using const keyword or #define Declared by specifying data type and variable
Syntax directive. name.

Memory Value is stored at a fixed memory Memory is allocated for storing data that can be
Allocation location that is protected. changed.

Use Cases Used for fixed values like pi, number of Used when data changes during program
days, etc. execution, like user input or calculation results.

Scope Scope can be local or global. Scope can be local or global, depending on where
it's declared.

Mutability Immutable (cannot be changed). Mutable (can be changed).

Storage Class Generally stored in read-only memory. Stored in read/write memory.

Example const int DAYS_IN_WEEK = 7; int age = 25;


Types of Constants in C
Below are the different types of constants in C with examples:

1. Integer Constants

Integer constants in C represent whole numbers without any fractional or decimal components. These
constants can be positive or negative, and are written without any quotes.

Example:

int daysInWeek = 7; // Integer constant 7


int temperature = -15; // Integer constant -15
 Decimal (Base 10): Numbers like 123, -45.
 Octal (Base 8): Numbers preceded by 0, like 075, represent octal values.
 Hexadecimal (Base 16): Numbers preceded by 0x, like 0x1A3, represent hexadecimal values.

2. Floating-Point Constants

Floating-point constants in C represent real numbers with a decimal point or in exponential notation. These
constants are used to represent fractional values.

Example:

float pi = 3.14159; // Floating-point constant 3.14159


double gravity = 9.81; // Floating-point constant 9.81
 Floating-point constants can be written in standard decimal form (3.14) or scientific
notation (1.23e4, which is equivalent to 1.23 × 10^4).

3. Character Constants

A character constant in C represents a single character enclosed within single quotes (' '), such as a
letter, number, or special symbol. These constants are stored as integers in C, following the ASCII value
of the character.

Examples:

char grade = 'A'; // Character constant 'A'


char newline = '\n'; // Special character constant representing newline
 char constant in C can also include escape sequences like '\n' for newline or '\t' for a tab.

4. String Constants

String constants in C represent a sequence of characters enclosed within double quotes (" "). Strings are
treated as arrays of characters and always end with a null character (\0) to mark the end of the string.

Examples:

char greeting[] = "Hello, World!"; // String constant "Hello, World!"


char name[] = "John"; // String constant "John"
 Each character in the string is stored in consecutive memory locations, followed by a \0 character.

5. Enumeration Constants

Enumeration constants in C are user-defined constants that represent a set of integer values. They are
defined using the enum keyword. Each enumeration constant is assigned an integer value, starting from 0
by default, unless explicitly specified.

Examples:

enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; // Enumeration constant for
days of the week
enum week today = Wednesday; // Assigns Wednesday (which equals 3) to the variable today
You can also specify custom values for enum members:

enum colors {Red = 1, Green = 2, Blue = 3};


6. Double Precision Floating-Point Constant

A double-precision floating-point constant is similar to a floating-point constant but provides greater


precision and is stored using the double data type, which occupies more memory.

Example:

double largeValue = 12345678.987654321; // Double precision floating-point constant


7. Array Constant

Arrays in C are collections of elements of the same type stored in contiguous memory locations. An array
constant can be thought of as a fixed set of values used to initialize an array at the time of declaration.

Example:

struct Point {
int x;
int y;
};
struct Point p = {10, 20}; // Structure constant

How to Declare and Define Constants in C?


Constants in C can be defined using two primary methods: the #define preprocessor directive and the const
keyword:

1. Using #define Preprocessor Directive

The #define directive is used to define constant values or macros at the start of a program. It instructs the
compiler to replace all occurrences of the defined constant with its value before the actual compilation
begins.
Syntax:

#define CONSTANT_NAME value


 CONSTANT_NAME: The name of the constant (conventionally written in uppercase).
 value: The constant value being assigned.

Example:

#define PI 3.14159
#define MAX_SIZE 100
#define MESSAGE "Hello, World!"

int main() {
printf("Value of PI: %f\n", PI); // Outputs: Value of PI: 3.14159
printf("Max size is: %d\n", MAX_SIZE); // Outputs: Max size is: 100
printf(MESSAGE); // Outputs: Hello, World!
return 0;
}
2. Using const Keyword

The const keyword in C allows you to declare a variable whose value cannot be changed after
initialization. It provides type safety, meaning the compiler knows the type of the constant and ensures no
modification is made during the program's execution.

Syntax:

const data_type variable_name = value;

 data_type: The type of the constant (e.g., int, float, etc.).

 variable_name: The name of the constant variable.


Example:

const float PI = 3.14159;


const int MAX_SIZE = 100;

int main() {
printf("Value of PI: %f\n", PI); // Outputs: Value of PI: 3.14159
printf("Max size is: %d\n", MAX_SIZE); // Outputs: Max size is: 100
return 0;
}
Input in C
Input in C programming means gathering data from the user or external sources for processing. The most
common way is through the console, where functions like scanf() are used for formatted input, and
getchar() reads a single character.

Additionally, data can be read from files using functions like fscanf() and fgets().

For example, scanf("%d", &num); takes an integer input from the user.
Output in C
Output in C programming means displaying results or information from a program on the console or
writing it to a file. Console output functions like printf() allow formatted data to be printed, while putchar()
is used for single characters. File output operations in C involve writing data to a file using functions like
fprintf() and fputs().

For example, printf("Result: %d", result); displays the value of a variable.

Input and Output Functions in C Programming


Below is the list of input and output functions in C language:

Function Category Description

scanf() Input (Console) Reads formatted input (e.g., integers, floats, strings) from the
user.

getchar() Input (Console) Reads a single character from the user.

gets() Input (Console) Reads a string from the user (deprecated due to safety
issues).

fscanf() Input (File) Reads formatted data from a file.

fgets() Input (File) Reads a line of text from a file.

printf() Output Prints formatted output to the console.


(Console)

putchar() Output Outputs a single character to the console.


(Console)

puts() Output Outputs a string to the console.


(Console)

fprintf() Output (File) Writes formatted data to a file.

fputs() Output (File) Writes a string to a file.

fopen() File Operation Opens a file for reading, writing, or appending.

fclose() File Operation Closes an opened file.

fread() Input (File) Reads binary data from a file.

fwrite() Output (File) Writes binary data to a file.

feof() File Operation Checks if the end of a file has been reached.
Input Functions in C
Below is a detailed explanation of common input functions in C programming:

1. scanf()

Reads formatted input from the user, such as integers, floats, and strings.

Example:

int num;
printf("Enter a number: ");
scanf("%d", &num); // Takes integer input
printf("You entered: %d\n", num);

2. getchar()

Reads a single character from the user.

Example:

char ch;
printf("Enter a character: ");
ch = getchar(); // Reads one character
printf("You entered: %c\n", ch);

3. gets()

Reads a string from the user, including spaces (deprecated due to safety concerns).

Example:

char str[50];
printf("Enter a string: ");
gets(str); // Reads the entire string
printf("You entered: %s\n", str);
4. fscanf()

Reads formatted data from a file.

Example:

FILE *file = fopen("[Link]", "r");


int num;
fscanf(file, "%d", &num); // Reads an integer from the
file printf("The number in the file is: %d\n", num);
fclose(file);
5. fgets()

Reads a line of text from a file or the console.


Example:

FILE *file = fopen("[Link]", "r");


char line[100];
fgets(line, 100, file); // Reads a line from the file
printf("The line in the file is: %s\n", line);
fclose(file);

Output Functions in C
Below is the explanation of common output functions in C programming:

1. printf()

Prints formatted output to the console.

Example:

int num = 10;


printf("The number is: %d\n", num); // Prints the value of num

2. putchar()
Outputs a single character to the console.

Example:

char ch = 'A';
putchar(ch); // Outputs the character 'A'
printf("\n");

3. puts()

Outputs a string to the console with a newline at the end.

Example:

char str[] = "Hello, World!";


puts(str); // Prints the string with a newline

4. fprintf()

Writes formatted data to a file.

Example:

FILE *file = fopen("[Link]", "w");


int num = 20;
fprintf(file, "The number is: %d\n", num); // Writes to the file
fclose(file);

5. fputs()

Writes a string to a file.

Example:

FILE *file = fopen("[Link]", "w");


fputs("This is a test string.", file); // Writes the string to the file
fclose(file);
Key Notes:

 Input functions like scanf() and fgets() are used to take data from the user or files.
 Output functions like printf() and fprintf() are used to display or save data.
 Always use fopen() and fclose() when working with files to ensure proper file handling.

Formatted Input and Output in C


Formatted input and output in C refers to the ability to control how data is entered and displayed in a
structured way. With formatted input and output, you can specify how numbers, characters, and strings are
read or displayed, making the program more organized and user-friendly.

How Does Formatted Input/Output in C Help Developers?

 Clear Presentation: It allows developers to align text, control decimal places, and format outputs
for better readability.
 Accurate Input Handling: It ensures the program accepts data in the correct format
(e.g., integers, floats, or strings).
 Custom Layouts: Developers can customize outputs, such as aligning columns of numbers or
formatting dates.

Example

Below is a simple example to demonstrate formatted input and output:

#include <stdio.h>

int main() {
int age;
float height;
char name[50];

// Formatted input
printf("Enter your name: ");
scanf("%s", name); // Reads a single word
printf("Enter your age: ");
scanf("%d", &age); // Reads an integer
printf("Enter your height (in meters): ");
scanf("%f", &height); // Reads a float

// Formatted output
printf("\n--- User Details ---\n");
printf("Name: %s\n", name);
printf("Age: %d years\n", age);
printf("Height: %.2f meters\n", height); // Displays height with 2 decimal places

return 0;
}
Run Code
Output:

Enter your name: Alice


Enter your age: 25
Enter your height (in meters): 1.68

--- User Details ---


Name: Alice
Age: 25 years
Height: 1.68 meters
Explanation:

 Input: The program uses scanf() to read the user’s name, age, and height in specific formats (%s,
%d, %f).

 Output: The program uses printf() to display the details in a structured format. For
example, "Height: %.2f meters" ensures the height is shown with exactly two decimal
places.

Formatted Input and Output Functions in C


Function Purpose Data Description
Source/Destination

printf() Formatted output Standard output Displays data on the console in a structured
(console) format.

scanf() Formatted input Standard input Reads data from the user in a specific
(keyboard) format.

fprintf() Formatted output to File or stream Writes formatted data to a file.


file

fscanf() Formatted input from File or stream Reads formatted data from a file.
file

Key Points

 printf() and scanf() are ideal for console-based interactions.


 fprintf() and fscanf() extend formatted I/O functionality to files, allowing data persistence and
manipulation.

printf() Function for Formatted Output in C


Purpose: Used for formatted output to the standard output (console).

Usage: Allows displaying text, variables, and other data types with custom formatting.

Syntax:

printf("format string", variable1, variable2, ...);


Example:

#include <stdio.h>

int main() {
int age = 25;
printf("Age: %d\n", age); // Displays the age with an integer format specifier
return 0;
}
Run Code
Output:

Age: 25
Purpose: Used for formatted input from the standard input (keyboard).

Usage: Reads data of specific types (integers, floats, strings, etc.) into variables.

Syntax:

scanf("format string", &variable1, &variable2, ...);


Example:

#include <stdio.h>

int main()
{ int age;
printf("Enter your age: ");
scanf("%d", &age); // Reads an integer from the user
printf("You entered: %d\n", age);
return 0;
}
Run Code
Output:

Enter your age: 27


You entered: 27
fprintf() Function for Formatted Output to File
Purpose: Used for formatted output to a file.

Usage: Writes data to files with formatting, similar to printf() but for file streams.

Syntax:

fprintf(FILE *stream, "format string", variable1, variable2, ...);


Example:

#include <stdio.h>

int main() {
FILE *file = fopen("[Link]", "w"); // Opens a file in write mode

if (file != NULL) {
int age = 25;
fprintf(file, "Age: %d\n", age); // Writes formatted data to the file
fclose(file);
} else {
printf("Error opening file.\n");
}

return 0;
}
Run Code
Output:

Age: 25

fscanf() Function for Formatted Input from File


1. Purpose: Used for formatted input from a file.

2. Usage: Reads data from a file into variables, similar to scanf() but for file streams.

Syntax:

fscanf(FILE *stream, "format string", &variable1, &variable2, ...);


Example:

#include <stdio.h>

int main() {
FILE *file = fopen("[Link]", "r"); // Opens a file in read mode

if (file != NULL) {
int age;
fscanf(file, "%d", &age); // Reads an integer from the file
printf("Age from file: %d\n", age);
fclose(file);
} else {
printf("Error opening file.\n");
}

return 0;
}
Run Code
Output:

Age from file: 25

Format Specifiers in C
Format specifiers in C are placeholders used in formatted input/output functions like printf() and scanf() to
indicate the type of data being handled. They help the compiler understand how to read input or display
output.

Below is a list of commonly used format specifiers in C:

Specifier Description Example Input Example Usage

%d Integer (signed) 25, -50 printf("Age: %d", age);

%u Unsigned integer 50, 100 printf("Score: %u", score);

%f Floating-point number 3.14, -0.001 printf("PI: %.2f", pi);

%lf Double precision float 3.141592 scanf("%lf", &num);

%c Single character A, z printf("Grade: %c", grade);

%s String (char array) "Hello" printf("Name: %s", name);

%x Hexadecimal (lowercase) 0x1a printf("Hex: %x", num);

%X Hexadecimal (uppercase) 0x1A printf("Hex: %X", num);

%o Octal number 075 printf("Octal: %o", num);

%p Pointer address 0x7ffc... printf("Address: %p", &var);

%e Scientific notation 2.3e+01 printf("Exp: %e", num);

%% Prints % character % printf("Discount: 10%%");


Control Statements in C
Control statements in C language are instructions that determine the flow of a program's execution based
on certain conditions or repetitions. They help decide whether a block of code should run, repeat, or skip.
These statements make programs dynamic by adding decision-making, looping, and jumping capabilities,
which are essential for solving real-world problems.

Let’s understand it with a real-life example:

Think of control statements like traffic signals. A green light allows cars to move (execution), a red light
stops them (condition not met), and a yellow light prepares them for the next action (transition).

Types of Control Statements in C


There are three types of control statements in C programming:

1. Decision-Making Statements: These statements allow the program to make decisions and execute
specific blocks of code based on conditions.

2. Loop Control Statements: These statements repeatedly execute a block of code as long as a specified
condition is true.

3. Jump Statements: These statements transfer the program's control from one part of the code to
another, either conditionally or unconditionally.

Decision-Making Control Statements in C


Decision-making statements in C allow the program to make choices and execute specific blocks of code
based on conditions. These statements enable a program to behave dynamically and handle different
scenarios effectively.

Let’s discuss the different types of decision control statements in C:

1. if Statement

The if statement in C executes a block of code only if the given condition is true.

Syntax:

if (condition) {
// Code to execute if condition is true
}
Example:

#include <stdio.h>
int main() {
int number = 10;
if (number > 0) {
printf("The number is positive.");
}
return 0;
}
When to Use: Use the if statement when you need to perform an action based on a single condition.

2. if-else Statement

The if-else statement in C executes one block of code if the condition is true and another block if it is false.

Syntax:

if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:

#include <stdio.h>
int main() {
int number = -5;
if (number >= 0) {
printf("The number is non-negative.");
} else {
printf("The number is negative.");
}
return 0;
}
When to Use: Use if-else control statement in C programming when you need to perform one action for a
true condition and another for a false condition.

3. nested if Statement

It is an if statement inside another if statement, used to check multiple conditions.

Syntax:

if (condition1) {
if (condition2) {
// Code if both conditions are true
}
}
Example:

#include <stdio.h>
int main() {
int number = 5;
if (number > 0) {
if (number % 2 == 0) {
printf("The number is positive and even.");
} else {
printf("The number is positive and odd.");
}
}
return 0;
}
When to Use: Use nested if when you need to test multiple related conditions.

4. if-else-if Ladder

This conditional statement in C checks multiple conditions one by one until a true condition is found.

Syntax:

if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example:

#include <stdio.h>
int main() {
int marks = 85;
if (marks >= 90) {
printf("Grade: A");
} else if (marks >= 75) {
printf("Grade: B");
} else if (marks >= 50) {
printf("Grade: C");
} else {
printf("Grade: F");
}
return 0;
}
When to Use: Use the if-else-if ladder when you need to check multiple conditions in sequence.

5. switch case Statement

The switch case in C tests a variable against multiple values (cases) and executes the matching block of
code.

Syntax:

switch (variable) {
case value1:
// Code for case 1
break;
case value2:
// Code for case 2
break;
default:
// Code if no case matches
}
Example:

#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}
return 0;
}
When to Use: Use switch when you need to test a variable against a fixed set of values.

Loop Control Statements in C


Loop control statements in C are used to repeatedly execute a block of code as long as a specific condition
is true. They simplify repetitive tasks and help in writing concise programs.

Imagine you are filling bottles with water. You continue filling bottles one by one until you run out of
empty bottles. Similarly, in programming, looping statements repeatedly perform tasks until a condition is
met.

Let’s understand the different loops in C programming:

1. for Loop

The for loop in C executes a block of code a specific number of times, controlled by an initialization,
condition, and increment/decrement.

Syntax:

for (initialization; condition; increment/decrement) {

// Code to execute in each iteration

Example:

#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
printf("Number: %d\n", i);
}
return 0;
}
Output:
1
2
3
4
5
When to Use: Use the for loop when the number of iterations is known beforehand.

2. while Loop

The while loop in C executes a block of code repeatedly as long as the specified condition is true.

Syntax:

while (condition) {
// Code to execute while condition is true
}
Example:

#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("Number: %d\n", i);
i++;
}
return 0;
}
Output:
1
2
3
4
5
When to Use: Use the while loop when the number of iterations is not known and depends on a condition.

3. do-while Loop

The do-while loop in C executes a block of code at least once and then continues to execute as long as the
condition is true.

Syntax:

do {
// Code to execute
} while (condition);

Example:

#include <stdio.h>
int main() {
int i = 1;
do {
printf("Number: %d\n", i);
i++;
} while (i <= 5);
return 0;
}

Output:
1
2
3
4
5
When to Use: Use the do-while loop when you want the code to execute at least once, regardless of the
condition.

Comparison of Looping Control Statements in C

Loop Type Condition Checked Best Used For

for Before the first iteration Known number of iterations.

while Before each iteration Unknown iterations, based on a condition.

do-while After the first iteration Code must run at least once.

Difference between for, while, and do-while Loops in C


Aspect for Loop while Loop do-while Loop

Condition At the beginning of each At the beginning of each After executing the loop
Evaluation iteration. iteration. body.

Execution Executes only if the condition is Executes only if the Executes the loop body at
Guarantee true. condition is true. least once.

Use Case When the number of iterations is When the number of When the loop body must run
known. iterations depends on a at least once.
condition.

Syntax Compact with initialization, Requires a separate Similar to while, but checks
condition, and increment in a initialization and increment condition last.
single line. statement.

Structure Entry-controlled loop. Entry-controlled loop. Exit-controlled loop.

Flexibility Best for counter-based loops. Best for condition-based Best for condition-based
loops. loops requiring at least one
execution.

Examples Iterating over arrays, printing Validating user input, Menu-driven programs, input
patterns. waiting for events. validation.
Jumping Control Statements in C
Jumping statements in C are used to transfer control of the program from one point to another. These
statements enable conditional or unconditional jumps, allowing flexibility in program flow.

Real-Life Example:

Imagine reading a book:

 You can skip pages you don’t need (continue).


 You can stop reading altogether (break).
 You can flip directly to a specific page (goto).

Jumping statements in C programming work similarly by moving control within the code.

There are four main jump control statements in C language:

1. break Statement

The break statement in C terminates the nearest enclosing loop or switch statement and transfers control to
the next statement after it.

Syntax:

break;
Example:

#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
printf("Number: %d\n", i);
}
return 0;
}
When to Use: Use break to exit a loop or switch prematurely when a specific condition is met.

2. continue Statement

The continue statement in C skips the current iteration of the loop and moves to the next iteration.

Syntax:

continue;
Example:

#include <stdio.h>
int main() {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
printf("Number: %d\n", i);
}
return 0;
}
When to Use: Use continue when you want to skip specific iterations of a loop without exiting it.

3. goto Statement

The goto statement in C transfers control to a labeled statement within the program.

Syntax:

goto label;
...
label:
// Code to execute
Example:

#include <stdio.h>
int main() {
int number = 3;
if (number < 5) {
goto small;
}
printf("Number is not small.\n");
return 0;

small:
printf("Number is small.\n");
}
When to Use: Use goto sparingly, typically in cases like error handling, where other approaches may
complicate the code.

4. return Statement

The return statement in C exits the current function and optionally returns a value to the calling function.

Syntax:

return; // Without value


return value; // With value
Example:

#include <stdio.h>
int add(int a, int b) {
return a + b;
}

int main() {
int result = add(3, 5);
printf("Result: %d\n", result);
return 0;
}
When to Use: Use return to exit a function and optionally pass a value back to the calling function.

Comparison of Jumping Statements

Jump Type Purpose Best Used For

break Exit a loop or switch To terminate loops/switch on a condition.

continue Skip to the next iteration To bypass specific iterations in a loop.

goto Jump to a labeled statement Rarely, for complex flow control or errors.

return Exit a function To end function execution and return a value.

Examples of Control Statements in C


Below are some examples of C language control statements:

1. Decision-Making: Checking Eligibility for a Driving License

Scenario: A person needs to be at least 18 years old to apply for a driving license.

#include <stdio.h>
int main() {
int age;
printf("Enter your age: ");
scanf("%d", &age);

if (age >= 18) {


printf("You are eligible for a driving license.\n");
} else {
printf("You are not eligible for a driving license.\n");
}
return 0;
}
Output:

Enter your age: 24


You are eligible for a driving license.

2. Looping: Printing Multiplication Table

Scenario: Generate and display the multiplication table of a given number in C.

#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
for (int i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", num, i, num * i);
}
return 0;
}
Output:

Enter a number: 12
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120

3. Combining Decision and Loop: Odd or Even Numbers in a Range

Scenario: Print all odd numbers in a given range.

#include <stdio.h>
int main() {
int start, end;
printf("Enter the start and end of the range: ");
scanf("%d %d", &start, &end);
for (int i = start; i <= end; i++) {
if (i % 2 != 0) {
printf("%d ", i);
}
}
return 0;
}
Output:

Enter the start and end of the range: 5 100


5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77
79 81 83 85 87 89 91 93 95 97 99

4. Nested Loops: Printing a Star Pattern

Scenario: Create a pyramid-like star pattern for user-defined rows.

#include <stdio.h>
int main() {
int rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);

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


for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Output:

Enter the number of rows: 7

*
**
***
****
*****
******
*******

5. switch Statement: Simple Calculator

Scenario: Write a simple calculator program in C to perform addition, subtraction, multiplication, or


division based on user input.

#include <stdio.h>
int main() {
char operator;
double num1, num2;
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);

switch (operator) {
case '+':
printf("Result: %.2lf\n", num1 + num2);
break;
case '-':
printf("Result: %.2lf\n", num1 - num2);
break;
case '*':
printf("Result: %.2lf\n", num1 * num2);
break;
case '/':
if (num2 != 0) {
printf("Result: %.2lf\n", num1 / num2);
} else {
printf("Error: Division by zero.\n");
}
break;
default:
printf("Invalid operator.\n");
}
return 0;
}
Output:

Enter an operator (+, -, *, /): *


Enter two numbers: 2 5
Result: 10.00
6. Jump Statements: Skipping Numbers in a Loop

Scenario: Print numbers from 1 to 10 but skip 5 using continue.


#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
printf("%d ", i);
}
return 0;
}
Output:

1 2 3 4 6 7 8 9 10

7. Real-Life Example: Login System

Scenario: Check if a user enters the correct username and password within three attempts.

#include <stdio.h>
#include <string.h>
int main() {
char username[20], password[20];
char correctUser[] = "admin";
char correctPass[] = "1234";

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


printf("Attempt %d - Enter username: ", i);
scanf("%s", username);
printf("Enter password: ");
scanf("%s", password);

if (strcmp(username, correctUser) == 0 && strcmp(password, correctPass) == 0) {


printf("Login successful!\n");
return 0;
} else {
printf("Incorrect username or password. Try again.\n");
}
}

printf("Login failed. Please try later.\n");


return 0;
}
Best Practices for Using Control Statements in C
 Keep the Logic Simple: Avoid overly complex conditions and deeply nested control
statements in C for better readability.
 Use Proper Indentation: Maintain clear indentation to make the code structure easy
to understand.
 Add Comments: Explain the purpose of critical control statements or complex conditions
using comments in C program.
 Avoid Unnecessary Nesting: Limit the use of nested loops and conditions; refactor into functions
if needed.
 Prefer switch Over Multiple if-else: Use switch case when dealing with a variable with
many possible values for better clarity and performance.
 Minimize Use of goto: Avoid the goto statement unless absolutely necessary, as it makes the
code harder to debug and maintain.
 Avoid Infinite Loops: Ensure loop conditions are well-defined and prevent infinite loops unless
explicitly required.
 Use Meaningful Conditions: Write conditions that are intuitive and self-explanatory.
 Test Edge Cases: Test control structures for boundary and edge cases to ensure
correct functionality.
 Break Down Complex Logic: Split lengthy and complicated logic into smaller functions for
better maintainability.
 Validate Inputs: Check user inputs or variables before using them in C control statements
to avoid errors.
 Avoid Overusing break and continue: Use these jump statements judiciously to avoid
making the program flow confusing.
 Use return to Simplify Flow: Use the return statement to exit functions early when conditions
are met, instead of using nested if blocks.

 Handle Default Cases: Always include a default case in switch statements to handle unexpected
inputs.
Unit-2
Arrays and Strings
An array in C is a collection of multiple values of the same data type stored together under a single variable
name. Instead of creating separate variables for each value, you can use an array to store and manage them
efficiently using index numbers.

These index numbers start from 0, allowing easy access to each element. Arrays are especially useful when you
need to work with lists, such as marks of students, temperatures, or items in a menu.

Syntax of Array in C
The basic syntax for declaring an array in C is:

data_type array_name[array_size];
data_type: Type of data (e.g., int, float, char)
 array_name: Any valid identifier
 array_size: Number of elements (must be a constant or macro)

Example:

Here’s how you declare different types of arrays:

int numbers[5]; // array of 5 integers


float scores[10]; // array of 10 floats
char letters[26]; // array of 26
characters
Note: When you declare an array, memory is allocated for the specified number of elements.

Types of Arrays in C Language


There are three types of arrays in C programming:

1. One-Dimensional Array

A one-dimensional array in C is the simplest form of an array. It stores a list of elements of the same data type
in a single row (linear structure), accessed using a single index.

Declaration:

int numbers[5];
Initialization:

int numbers[5] = {10, 20, 30, 40, 50};


Accessing Elements:

printf("%d", numbers[2]); // Output: 30


Example:

#include <stdio.h>

int main() {
int marks[3] = {85, 90, 95};
for (int i = 0; i < 3; i++) {
printf("marks[%d] = %d\n", i, marks[i]);
}
return 0;
}
2. Two-Dimensional Array

A two-dimensional array in C stores data in a table-like structure using rows and columns. It’s often used
to represent matrices.

Declaration:

int matrix[2][3]; // 2 rows, 3 columns


Initialization:

int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Accessing Elements:

printf("%d", matrix[1][2]); // Output: 6


Example:

#include <stdio.h>

int main() {
int matrix[2][2] = {{10, 20}, {30, 40}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("matrix[%d][%d] = %d\n", i, j, matrix[i][j]);
}
}
return 0;
}
3. Multi-Dimensional Array

A multi-dimensional array in C contains more than two dimensions (like 3D or 4D arrays). These are
rarely used but helpful in special cases like 3D games or image processing.

Declaration:

int cube[2][2][2];
Initialization:

int cube[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
Accessing Elements:

printf("%d", cube[1][0][1]); // Output: 6

Array Initialization Techniques in C


When you declare an array in C, you can also assign values to it using different initialization methods.
Let’s explore the common techniques:

1. Compile-Time Initialization

You assign values to the array at the time of declaration.

Example:

int numbers[5] = {10, 20, 30, 40, 50};


 Values are stored in order.
 If fewer values are provided than the size, remaining elements are set to 0.

2. Initialization Without Specifying Size

The compiler automatically determines the size based on the number of elements.

Example:

int marks[] = {50, 60, 70}; // Array of size 3


 Useful for shorter code when you know the values.

3. Partial Initialization

Only the first few elements are initialized, rest are automatically set to 0.

Example:

int data[4] = {9}; // {9, 0, 0, 0}

4. Zero Initialization

You can explicitly initialize all values to 0 using {0}.

Example:

int arr[5] = {0}; // All 5 elements set to 0

5. Run-Time Initialization (Using Loops)

You can assign values to each element using a loop, especially when taking input from the user.
Example:

int n[3];
for (int i = 0; i < 3; i++) {
scanf("%d", &n[i]);
}
Examples of Arrays in C Language
1. Program to Print Elements of an Array

#include <stdio.h>

int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
Explanation:

A simple loop is used to access and print each array element.

2. Program to Take Input in an Array and Print Sum

#include <stdio.h>

int main() {
int arr[5], sum = 0;
printf("Enter 5 numbers:\n");
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}
printf("Sum = %d", sum);
return 0;
}
Explanation:

Takes user input into an array and calculates the total sum.

3. Program to Find Maximum Element in an Array

#include <stdio.h>

int main() {
int arr[5] = {11, 25, 9, 43, 31};
int max = arr[0];

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


if (arr[i] > max) {
max = arr[i];
}
}
printf("Maximum element = %d", max);
return 0;
}
Explanation:

Iterates through the array and tracks the highest value.

4. Program to Reverse an Array

#include <stdio.h>

int main() {
int arr[5] = {1, 2, 3, 4, 5};
printf("Reversed array: ");
for (int i = 4; i >= 0; i--) {
printf("%d ", arr[i]);
}
return 0;
}
Explanation:

Prints array elements in reverse order using a loop.

5. Program to Copy One Array to Another

#include <stdio.h>

int main() {
int original[5] = {3, 6, 9, 12, 15};
int copy[5];

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


copy[i] = original[i];
}

printf("Copied array: ");


for (int i = 0; i < 5; i++) {
printf("%d ", copy[i]);
}

return 0;
}
Explanation:

Uses a loop to copy elements from one array to another.


Character Arrays and Strings in C
A character array is a sequence of characters stored in contiguous memory locations. In C, strings are
represented using character arrays terminated with a null character \0, which tells the compiler where the
string ends.

Declaring a Character Array (String)

Method 1: Using Character List: Must include \0 at the end to make it a valid string. Size must be 1
more than the number of characters to accommodate the null terminator.

char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


Method 2: Using String Literal (Recommended): Automatically adds \0 at the end. It has easier and
cleaner syntax.

char name[] = "Hello";


Initializing and Printing Strings

#include <stdio.h>

int main() {
char city[] = "Delhi";
printf("City: %s", city); // Output: City: Delhi
return 0;
}
Reading Strings from User

Using scanf() (Stops at space)

char name[20];
scanf("%s", name);
Using fgets() (Reads full line including spaces)

fgets(name, 20, stdin);


Accessing Individual Characters

char str[] = "C Language";


printf("%c", str[2]); // Output: L

Advantages of Arrays in C
 Efficient Data Storage: Arrays allow storing multiple values of the same data type using a
single variable name.
 Indexed Access: Elements can be easily accessed, modified, or iterated using index numbers (0-
based indexing).
 Reduced Code Complexity: You don’t need to declare multiple variables — one array can hold
hundreds of values.
 Easy Looping and Traversal: Arrays can be easily processed using loops (for, while),
making operations like printing, summing, or searching simpler.
 Improved Memory Management: Arrays use contiguous memory, which helps in faster
data access and better memory locality.
 Useful in Algorithms: Arrays are widely used in sorting, searching, matrix operations, and many
algorithms.
 Foundation for Advanced Structures: Arrays form the basis of more advanced data
structures like strings, matrices, stacks, queues, and linked lists.
 Cleaner and Organized Code: Helps organize related data under a single name,
improving readability and maintainability.

Disadvantages of Arrays in C
 Fixed Size: Once declared, the size of an array cannot be changed during program execution.
 Static Memory Allocation: Memory is allocated at compile time, which may lead to
inefficient memory usage if the size is too large or too small.
 No Bound Checking: C does not check whether an index is within array limits, which can
cause unexpected behavior or segmentation faults.
 Only Homogeneous Data Types: Arrays can store elements of the same data type only (e.g., all
int or all char).
 No Built-in Dynamic Resizing: You cannot grow or shrink an array at runtime without
using dynamic memory (malloc, realloc, etc.).
 No Built-in Insertion or Deletion: Inserting or deleting elements requires manual shifting
of elements, unlike in higher-level data structures like lists.
 Wastage of Memory: If the allocated size is larger than needed, the unused memory is wasted.

Uses and Applications of Arrays in C


 Storing Multiple Values: To store a collection of values (like marks, prices, or scores) using a
single variable name.
 Handling Tabular Data (2D Arrays): Arrays are used to represent matrices, tables, and grids
in a structured format.
 String Handling (Character Arrays): Arrays of characters (char[]) are used to store and
manipulate strings.
 Sorting and Searching Algorithms: Arrays are essential in implementing algorithms like
bubble sort, binary search, merge sort, etc.
 Loop-Based Operations: Arrays make it easy to perform repetitive operations on data using
loops.
 Storing Input Data: Arrays are commonly used to take multiple inputs from the user and store
them temporarily.
 Mathematical Computations: Arrays are used in vector and matrix calculations,
statistical analysis, and numeric simulations.
 Buffer Handling: Arrays can be used as buffers for reading/writing data in
file handling and input/output operations.
 Simulating Real-World Collections: Like storing student names, temperatures of the week,
scores in a game, etc.
 Implementing Data Structures: Arrays are the foundation of stacks, queues, heaps, and hash
tables.
 Storing Command Line Arguments: In main(int argc, char *argv[]), argv is an array of
strings passed from the command line.

2D Array in C Language
A two dimensional array in C is like a collection of data stored in rows and columns, similar to a table or grid.
It allows you to organize related information in a structured format, making it easier to access specific
elements using their row and column numbers.

For example, storing numbers in a 2D array means each number can be identified clearly by its position, such
as "third row, second column."

Imagine a cinema hall with rows and seats. To find your seat easily, you simply check your ticket, which
indicates your exact row number and seat number—just like locating elements in a 2D array.

Declaration of Two Dimensional Array in C


Syntax:

data_type array_name[rows][columns];
 data_type: Specifies the type of elements the array will store (like int, float, or char).
 array_name: The name given to the array.
 [rows] and [columns]: Define the size of the array, specifying how many rows and columns
it contains.

Example:

int matrix[3][4];
This example declares a two-dimensional array named matrix of type int with 3 rows and 4 columns. In total,
this array can hold 3 x 4 = 12 integer values.

Initialization of 2D Array in C Programming


Initialization of two-dimensional arrays in C can be done in two main ways:

1. Initialization at Declaration:

You can initialize a 2D array at the time you declare it using braces {}.

Syntax:

data_type array_name[rows][columns] = {
{val1, val2, val3},
{val4, val5, val6}
};
Example:

int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
2. Initialization Using Loops:

You can also initialize a 2D array using nested loops:

Example:

int matrix[2][3];
int value = 1;

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


for(int j = 0; j < 3; j++) {
matrix[i][j] = value;
value++;
}
}
Accessing Elements in 2D Arrays in C
To access elements in a two-dimensional array in C, you use the row and column index numbers. The indexing
always starts from 0.
Syntax:

array_name[row_index][column_index];
 row_index: Specifies the row position of the element.
 column_index: Specifies the column position of the element.

Example:

Consider the following 2D array declaration and initialization:

int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};
To access specific elements:

 matrix[0][1] accesses the element in the first row, second column (20).
 matrix[1][2] accesses the element in the second row, third column (60).

Practical Example:

#include <stdio.h>

int main() {
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};

printf("Element at [0][1]: %d\n", matrix[0][1]); // outputs 20


printf("Element at [1][2]: %d\n", matrix[1][2]); // outputs 60

return 0;
}

Output:

Element at [0][1]: 20
Element at [1][2]: 60
Input and Output with 2D Arrays in C
Below is how you can handle input and output with two dimensional arrays in C:

Taking Input from User

To accept input into a 2D array from the user, use nested loops:

Example:

#include <stdio.h>
int main() {
int rows = 2, columns = 3;
int matrix[2][3];

printf("Enter 6 elements for 2x3 matrix:\n");


for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
printf("matrix[%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}

return 0;
}
Displaying Output of a 2D Array

To print a two-dimensional array, again use nested loops:

Example (Continued from above):

printf("\nMatrix elements are:\n");


for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++)
{ printf("%d ", matrix[i][j]);
}
printf("\n"); // new line after each row
}
Run Code
Output:

Enter 6 elements for 2x3 matrix:


matrix[0][0]: 1
matrix[0][1]: 2
matrix[0][2]: 3
matrix[1][0]: 4
matrix[1][1]: 5
matrix[1][2]: 6
Matrix elements are:

123

456

Passing Two Dimensional Arrays to Functions


Passing two-dimensional arrays to functions in C allows you to reuse code and operate on arrays
effectively. Here's how you can do it:

Syntax for Passing 2D Arrays to Functions:

return_type function_name(data_type array_name[][columns], int rows, int columns);


You must specify the number of columns explicitly; rows can be optional or passed as an argument.
Example:

The following is a complete example showing passing and printing a 2D array using a function:

#include <stdio.h>

void printMatrix(int matrix[][3], int rows, int columns) {


printf("Matrix elements:\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int matrix[2][3] = {
{10, 20, 30},
{40, 50, 60}
};

printMatrix(matrix, 2, 3); // function call


return 0;
}
Output:

Matrix elements:
10 20 30
40 50 60
Examples of 2D Arrays in C
1: Addition of Two Matrices

#include <stdio.h>

int main() {
int rows = 2, columns = 2;
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int sum[2][2];

// Adding matrices
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}

// Displaying sum matrix


printf("Sum of matrices:\n");
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
printf("%d ", sum[i][j]);
}
printf("\n");
}
return 0;
}
Output:

Sum of matrices:
68
10 12

2. Transpose of a Matrix

#include <stdio.h>

int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int transpose[3][2];

// Calculating transpose
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 3; j++) {
transpose[j][i] = matrix[i][j];
}
}

// Displaying transpose matrix


printf("Transpose of matrix:\n");
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 2; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}

return 0;
}

Output:

Transpose of matrix:
14
25
36

3. Finding the Largest Element in a Matrix

#include <stdio.h>

int main() {
int matrix[3][3] = {
{12, 25, 6},
{8, 15, 20},
{3, 50, 10}
};
int max = matrix[0][0];

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


for(int j = 0; j < 3; j++) {
if(matrix[i][j] > max) {
max = matrix[i][j];
}
}
}

printf("Largest element in the matrix: %d\n", max);


return 0;
}

Output:

Largest element in the matrix: 50

4. Multiplication of Two Matrices

#include <stdio.h>

int main() {
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int product[2][2] = {0};

// Multiplying matrices
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
product[i][j] += a[i][k] * b[k][j];
}
}
}

// Displaying product matrix


printf("Product of matrices:\n");
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
printf("%d ", product[i][j]);
}
printf("\n");
}

return 0;
}

Output:

Product of matrices:
19 22
43 50
5. Sum of Rows and Columns of a Matrix

#include <stdio.h>

int main() {
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
int rowSum, colSum;

// Sum of rows
for(int i = 0; i < 2; i++) {
rowSum = 0;
for(int j = 0; j < 3; j++) {
rowSum += matrix[i][j];
}
printf("Sum of elements in row %d: %d\n", i + 1, rowSum);
}

// Sum of columns
for(int j = 0; j < 3; j++) {
colSum = 0;
for(int i = 0; i < 2; i++) {
colSum += matrix[i][j];
}
printf("Sum of elements in column %d: %d\n", j + 1, colSum);
}

return 0;
}

Output:

Sum of elements in row 1: 6


Sum of elements in row 2: 15
Sum of elements in column 1: 5
Sum of elements in column 2: 7
Sum of elements in column 3: 9

Advantages of 2D Arrays in C
 Easy Data Representation: Ideal for representing matrices, tables, and grids clearly.
 Efficient Access: Quick element access using row and column indices.
 Contiguous Memory Allocation: Elements are stored contiguously in memory, enabling faster
processing.
 Easy Manipulation: Simplifies operations such as matrix addition, multiplication,
and transposition.
 Code Readability: Improves readability and clarity, especially in handling structured data.
Limitations of 2D Arrays in C
 Fixed Size: Array dimensions must be specified during declaration and cannot be
resized afterward.
 Memory Wastage: Possible memory wastage if the array is not fully utilized.
 No Built-in Boundary Check: Accessing elements outside array bounds leads to undefined
behavior.
 Complex Dynamic Allocation: Dynamic allocation and memory management for 2D arrays
can become complex, especially for beginners.
 Rigid Structure: Limited flexibility; unsuitable for datasets that frequently change size or
structure.

String in C
String in C programming language is a sequence of characters stored in a character array, ending with a special
null character \0 that marks the end of the string. It can include letters, numbers, symbols, or spaces—just
like a sentence.

Since C doesn’t have a built-in string type like some other languages, strings are managed using arrays and
standard library functions.

Think of a string in C like a train, where each character is a coach, and the last coach is always empty (null
character \0) to signal that the train has ended.

How to Declare String in C?


String declaration in C is done using a character array. This means you tell the program to set aside memory
space to hold a sequence of characters.

Syntax to declare string in C:

char str[size];
Example of string declaration in C:

char name[10];
Explanation:

Here, name is a character array that can hold up to 9 characters plus one null character \0. This is just a
declaration—no specific string is stored yet. It's like reserving space without filling it.

How to Initialize String in C?


After declaring, you can assign a value to the string either directly at the time of declaration or later using
functions. This is called string initialization in C programming.

Syntax (Direct Initialization):

char str[] = "Hello";


Syntax 2 (Character by Character):

char str[] = {'H', 'e', 'l', 'l', 'o', '\0'};


Explanation:

In both examples, a string "Hello" is stored in the array. The null character \0 is automatically added when
you use double quotes. This tells the compiler where the string ends. This process is called initializing
strings in C and is essential for proper string handling.

How to Define String in C?


Defining a string in C means declaring a character array and assigning a value to it in the same step. This
stores the string in memory and automatically adds the null character \0 at the end.

Syntax to define string in C:

char string_name[] = "YourText";


Example:

char city[] = "Delhi";


Explanation:

 char tells the compiler it's a character array.


 city[] is the name of the string.
 "Delhi" is the string value, and C automatically adds \0 at the end.

So, this defines a string "Delhi" and stores it in a character array named city.

You can also define a string using characters individually:

char city[] = {'D', 'e', 'l', 'h', 'i', '\0'};


But using double quotes is simpler and recommended.

Reading Strings in C
Reading strings in C language from the user means taking input that contains multiple characters, including
spaces (if needed). There are multiple ways to read strings in C, each with its pros and cons.

Method 1: Using scanf()

char name[50];
scanf("%s", name);
Note: This reads only a single word. It stops reading when it encounters a space.

Example:

If the user enters:

John Doe
Only John will be stored in the string.

Method 2: Using gets() (Not Recommended)

char name[50];
gets(name);
Note: This can read an entire line, including spaces. But it is unsafe and deprecated because it doesn’t
prevent buffer overflow.

Method 3: Using fgets() (Recommended)

char name[50];
fgets(name, sizeof(name), stdin);
What it does:

 Reads a full line of input, including spaces.


 Prevents buffer overflow by limiting the number of characters read.
 Adds a newline character \n at the end, which can be removed using string functions if needed.

Displaying Strings in C
After reading or defining a C language string, you’ll want to display the string to the user. In C, you can
print strings using a couple of standard functions:

Using printf()

char name[] = "Alice";


printf("%s", name);
Run Code
Explanation:

 %s is the format specifier used for strings.


 It prints all characters until the null character \0.

Output:

Alice
Using puts()

char name[] = "Alice";


puts(name);
Run Code
Explanation:
 puts() prints the string and automatically adds a newline (\n) at the end.
 Simpler to use when you just want to print the string without any formatting.

Output:

Alice

Common String Functions in C


C provides several built-in functions in the string.h header file to perform common operations on strings.
These functions make it easy to manipulate and process strings efficiently.

1. strlen() – Get Length of a String

Returns the number of characters in a string (excluding the null character)

#include <string.h>
int len = strlen("Hello");
printf("%d", len); // Output: 5

2. strcpy() – Copy One String to Another

Copies the contents of one string into another.

#include <string.h>
char src[] = "World";
char dest[20];
strcpy(dest, src);
printf("%s", dest); // Output: World

3. strcat() – Concatenate Two Strings

Appends one string to the end of another.

#include <string.h>
char str1[20] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
printf("%s", str1); // Output: Hello World

4. strcmp() – Compare Two Strings

Compares two strings character by character.

#include <string.h>
int result = strcmp("abc", "abc"); // Output: 0 (equal)
int result2 = strcmp("abc", "xyz"); // Output: negative (less than)

5. strrev() – Reverse a String (Not standard in GCC)


Reverses the string. Available in some compilers like Turbo C.

#include <string.h>
char str[] = "Hello";
strrev(str);
printf("%s", str); // Output: olleH
Note: In GCC or modern compilers, you’ll need to write your own strrev() function.

6. strchr() – Find First Occurrence of a Character

Searches for the first occurrence of a character in a string.

#include <string.h>
char *ptr = strchr("Hello", 'l');
printf("%s", ptr); // Output: llo

7. strstr() – Find Substring in a String

Searches for the first occurrence of a substring.

#include <string.h>
char *ptr = strstr("Hello World", "World");
printf("%s", ptr); // Output: World
These string functions in C help perform basic and advanced string operations with ease. Always include
#include <string.h> at the top of your program when using these functions.

Difference Between Character Array and String in C

Character Array String in C Language

Definition A collection of characters A character array terminated with \0

Null Terminator Not required Mandatory (\0 at the end)

Purpose Used to store multiple characters (not always Specifically used to represent textual data
a string)

Example char ch[] = {'A', 'B', 'C'}; char str[] = "ABC";

Length Handling Manual (no \0 to indicate end) Ends automatically at \0

Printing with %s May print garbage if \0 is missing Prints correctly until \0

String Functions Not fully compatible unless null-terminated Fully compatible with standard string
Compatibility functions
Examples of Strings in C
Program to Find the Length of a String

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

int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("Length = %lu", strlen(str));
return 0;
}
Program to Copy One String to Another

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

int main() {
char str1[100], str2[100];
printf("Enter a string: ");
gets(str1);
strcpy(str2, str1);
printf("Copied String: %s", str2);
return 0;
}
Program to Reverse a String

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

int main() {
char str[100];
printf("Enter a string: ");
gets(str);
strrev(str); // Note: Available in Turbo C. For GCC, use a custom function.
printf("Reversed String: %s", str);
return 0;
}
Program to Check if a String is Palindrome

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

int main() {
char str[100], temp[100];
printf("Enter a string: ");
gets(str);
strcpy(temp, str);
strrev(temp);
if(strcmp(str, temp) == 0)
printf("Palindrome");
else
printf("Not a Palindrome");
return 0;
}
Program to Count Vowels and Consonants in a String

#include <stdio.h>
#include <ctype.h>

int main() {
char str[100];
int vowels = 0, consonants = 0;
printf("Enter a string: ");
gets(str);
for(int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if(isalpha(ch)) {
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}
printf("Vowels: %d\nConsonants: %d", vowels, consonants);
return 0;
}

***** All the Best *****

You might also like