Stud Notes
Stud Notes
Examples:
• If your computer is not turning on — that’s a problem.
• If you don’t know how to answer a question in your homework — that’s a problem.
• If water is leaking from a tap — again, a problem.
It’s something that stops you or troubles you, and you need to find a solution for it.
India is a big country and we have an enormous railway network. Thus, railway reservation is a complex
task. Making reservation involves information about many aspects, such as details of trains (train type,
types of berth and compartments in each train, their schedule, etc.), simultaneous booking of tickets
by multiple users and many other related factors.
We usually use the term computerisation to indicate the use of computer to develop software in order
to automate any routine human task efficiently. Computers are used for solving various day-to-day
problems and thus problem solving is an essential skill that a computer science student should know.
Note:- GIGO (Garbage In Garbage Out) The correctness of the output that a computer gives depends
upon the correctness of input provided.
Problem Identification:- Problem identification is the crucial first step in problem-solving, involving
recognizing and clearly defining the specific issue that needs to be addressed. It's the process of
understanding what needs to be fixed or improved before attempting to find a solution. This stage is
essential for ensuring that the subsequent steps in the problem-solving process are focused and
effective.
• Ensures focused solutions: By clearly identifying the problem, you can focus your efforts on
addressing the core issue rather than addressing symptoms or unrelated factors.
• Increases the likelihood of success: When the problem is well-defined, it's easier to develop
targeted solutions and evaluate their effectiveness.
• Saves time and resources: Misidentifying the problem can lead to wasted time and resources
on ineffective solutions.
• Facilitates communication and collaboration: A clear problem statement helps to ensure that
everyone involved in the problem-solving process is on the same page.
Suppose following are the steps required for an activity ‘riding a bicycle’:
The algorithm to find square of a number can be represented pictorially using flowchart as shown
Flowcharts:- A flowchart is a visual representation of an algorithm. A flowchart is a diagram made up
of boxes, diamonds and other shapes, connected by arrows. Each shape represents a step of the
solution process and the arrow represents the order or link among the steps. There are standardised
symbols to draw flowcharts.
Flowchart to calculate square of a number
Example
Flowgorithm:- Flowgorithm is a free, easy-to-use software tool that helps you create and visualize
algorithms using flowcharts.
Key Features
Feature Description
Flowchart Editor Drag-and-drop shapes to build logic easily
Simulation Run your algorithm and see the steps in action
Loop & Condition Blocks Visualize while/for loops and if/else conditions
Code Conversion Convert flowchart to real code (C, Python, etc.)
Feature Description
Educational Focus Designed especially for beginners and teaching
History of C Language
1. Before C – Early Languages
• In the 1960s, computers were programmed using low-level languages like:
o Assembly Language
o Machine Code (very difficult to read/write)
• High-level languages like ALGOL and BCPL were developed to make programming easier.
2. BCPL (1967)
• Developed by: Martin Richards
• Purpose: Writing system software like compilers.
• Limitation: Too basic and lacked structure.
3. B Language (1969)
• Developed by: Ken Thompson at Bell Labs
• Based on: BCPL
• Used in: Early Unix systems
• Limitation: Did not support data types like int, float properly.
4. Creation of C (1972)
• Developed by: Dennis Ritchie at Bell Labs
• Main Goal: Improve B by adding data types, better control structures.
• Key Use: Rewriting the UNIX operating system kernel in C.
• Impact: Made operating systems more portable and efficient.
6. Standardization
• ANSI C (1989): Standardized version known as C89 or ANSI C
• ISO C (1990): International standard known as C90
• Further updates: C99, C11, C17, and C23
Summary
C language has several basic building blocks. These are the elements that make up any C program.
2. Identifiers:-Refers to the names used to identify variables, functions, arrays, etc. The rules
to be followed while naming an identifiers are :-
o Must start with a letter (uppercase or lowercase) or an underscore (_).
o Can consist of letters, digits, and underscores.
o Cannot be a keyword in C (like int, if, while, etc.).
o Case-sensitive (myVar and myvar are considered different).
o Cannot contain spaces or special characters (except underscore).
o The length of identifiers has a practical limit (often 31 characters are significant).
Types:
- Integer: 10
- Float: 3.14
- Character: 'A'
- String: "Hello"
5. Data Types:-Tells the compiler what type of data a variable will store.
Common types:
6. Variables:-Used to store data that can change during [Link] be declared before use.
Example:
int a = 5;
float pi = 3.14;
[Link]:-
An operator is a symbol that tells the compiler to perform certain mathematical or logical
manipulations. They form expressions.
3. LOGICAL OPERATORS : An expression of this kind which combines two or more relational
expressions is termed as a logical expressions or a compound relational expression. The
operators and truth values are
op-1 op-2 op-1 && op-2 op-1 || op-2
non-zero non-zero 1 1
non-zero 0 0 1
0 non-zero 0 1
0000
op-1 !op-1
non-zero zero
zero non-zero
4. ASSIGNMENT OPERATORS : They are used to assign the result of an expression to a variable.
The assignment operator is '='.
v op=exp
v is variable
op binary operator
exp expression
op= short hand assignment operator
short hand assignment operators
use of simple assignment operators use of short hand assignment operators
a=a+1 a+=1
a=a-1 a-=1
a=a%b a%=b
7. BIT WISE OPERATORS : C supports special operators known as bit wise operators for
manipulation of data at bit level. They are not applied to float or double.
operator meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
~ one's complement
8. SPECIAL OPERATORS : These operators which do not fit in any of the above classification
are ,(comma), sizeof, Pointer operators(& and *) and member selection operators (. and ->).
The comma operator is used to link related expressions together.
sizeof operator is used to know the sizeof operand.
[Link] Section:-Short: Contains comments about the [Link] section is used for
writing comments that describe the program's purpose, author name, date, or other details.
Comments improve readability and maintainability but are ignored by the compiler.
Example:
/*Programto calculate factorial/* */ is multi line comment
Author: Srinivas
Date: 24/09/2025 */
//This is a single line comment
[Link] Section:-
Short: Includes header files using #[Link] section is used to link the built-in and user-defined
header files. Header files contain predefined functions (like printf, scanf, strlen, etc.). Without linking
them, you can’t use standard library functions.
Example:
#include <stdio.h>
#include <math.h>
[Link] Section: Defines constants using #define or [Link] section is used for defining
symbolic constants or macros before program execution. It increases readability and makes code easy
to maintain.
Example:
#define PI 3.14159
#define SQUARE(x) (x*x)
[Link] Declaration Section:- Declares global variables and function [Link] this section,
variables and functions are declared globally so they can be accessed throughout the program (inside
main() and other functions).
Example:
int total; // global variable
void display(); // function prototype
6. Main() Function Section:-Short: Entry point of every C [Link] C program must have a main()
function. Execution starts from here.
- Declaration Part: Local variable declarations.
- Executable Part: Actual program logic (statements).
Example:
int main() {
int a, b, sum; // Declaration part
a = 10; b = 20;
sum = a + b; // Executable part
printf("Sum = %d", sum);
return 0;
}
7. Subprogram Section (User-defined Functions):-Functions created by the programmer.
Detail:
Besides main(), a program may have multiple user-defined functions. This section contains their
definitions. These help in modular programming, reusability, and better structure.
Example:
void display() {
printf("Hello, World!");
}
C Tokens- Variables and Data Types:-In C programming, a token is the smallest individual unit of a
program that is meaningful to the compiler. Think of them as the fundamental building blocks from
which all C programs are constructed. When the C compiler processes source code, it first breaks it
down into these distinct tokens to understand the program's structure and intent.
• Keywords:
Reserved words that have a predefined meaning in the C language, such as int, if, while, for, return,
etc.
• Identifiers:
Names given by the programmer to entities like variables, functions, arrays, and structures. They must
follow specific naming rules (e.g., cannot start with a digit, cannot be a keyword).
• Constants:
Fixed values that do not change during program execution. These include integer constants
(e.g., 10, 0xFF), floating-point constants (e.g., 3.14, 2.5e-3), character constants (e.g., 'A', '\n'), and
string literals (e.g., "Hello, World!").
• Operators:
Symbols that perform operations on operands, such as arithmetic operators (+, -, *, /), relational
operators (<, >, ==), logical operators (&&, ||, !), and assignment operators (=).
• Special Symbols (Punctuators):
Symbols that have specific meanings for structuring or separating code elements, including
parentheses (), braces {}, square brackets [], comma ,, semicolon ;, colon :, and others.
• String Literals:
Sequences of characters enclosed in double quotes, representing text.
Each token type plays a crucial role in defining the syntax and logic of a C program, enabling the
compiler to interpret and translate the source code into an executable program.
Keywords:-Keywords in C are predefined, reserved words that possess special meanings to the C
compiler. These words are integral to the C language's syntax and cannot be used by programmers as
identifiers (e.g., variable names, function names, or struct names). Each keyword has a fixed meaning
and serves a specific purpose in defining control structures, data types, function declarations, and
other fundamental elements within C programs.
Special Symbols:- Special symbols in C are characters that hold specific syntactic or operational
meanings within the language and are not part of the standard alphabetic or numeric character
sets. They are crucial for structuring code, performing operations, and defining program flow.
Common special symbols in C include:
• Punctuation and Separators:
• ; (Semicolon): Terminates statements.
• , (Comma): Separates items in a list (e.g., variables in a declaration, arguments in a
function call).
• : (Colon): Used in labels for switch statements and goto statements.
• . (Dot): Accesses members of structures or unions.
• Brackets and Braces:
• () (Parentheses): Enclose function parameters, control expressions
in if, while, for statements, and dictate operator precedence.
• {} (Curly Braces): Define code blocks for functions, loops, conditional statements, and
structure/union definitions.
• [] (Square Brackets): Used for declaring and accessing array elements.
• Operators:
• Arithmetic operators: +, -, *, /, % (modulus).
• Relational operators: ==, !=, <, >, <=, >=.
• Logical operators: && (AND), || (OR), ! (NOT).
• Bitwise operators: &, |, ^, ~, <<, >>.
• Assignment operator: =
• Increment/Decrement operators: ++, --.
• Address-of operator: & (returns the memory address of a variable).
• Dereference operator: * (accesses the value at a memory address pointed to by a
pointer).
• Other Special Characters:
• # (Hash/Number sign): Used for preprocessor directives (e.g., #include, #define).
• ' (Single Quote): Encloses single character literals.
• " (Double Quote): Encloses string literals.
• `\` (Backslash): Used in escape sequences (e.g., \n for newline, \t for tab).
Constants:-In C programming, constants are fixed values that cannot be modified during the execution
of a program. Once a constant is defined and assigned a value, that value remains unchanged
throughout the program's lifecycle.
There are two primary ways to define constants in C: Using the const keyword.
The const keyword is used to declare a variable as read-only, effectively making it a constant. The value
is assigned at the time of declaration and cannot be altered later.
const int MAX_VALUE = 100;
const float PI = 3.14159;
using the #define preprocessor directive.
The #define directive is a preprocessor command that defines a symbolic constant. Before
compilation, the preprocessor replaces all occurrences of the symbolic constant with its defined value.
#define MAX_BUFFER_SIZE 256
#define GRAVITY 9.81
Types of Constants:
Constants in C can be of various data types, including:
• Integer Constants: Whole numbers (e.g., 10, -5, 0xFF).
• Floating-point Constants: Numbers with decimal points (e.g., 3.14, 1.2e-5).
• Character Constants: Single characters enclosed in single quotes (e.g., 'A', '7', '\n').
• String Literals: Sequences of characters enclosed in double quotes (e.g., "Hello, World!").
Key Characteristics of Constants:
• Immutability: Their values cannot be changed after initialization.
• Readability: Using named constants instead of "magic numbers" improves code clarity.
• Maintainability: If a constant value needs to be updated, only the definition needs to be
changed, not every instance where the value is used.
Expressions and Type Conversions:-An expression in C is a combination of operators, operands, and
function calls that evaluates to a single value. Expressions can be simple, like a single variable or a
constant, or complex, involving multiple operations.
Examples of Expressions:
x (a variable),
10 (a constant),
a + b (addition operation),
c * (d - e) (multiplication and subtraction),
and sqrt(f) (function call).
Type Conversion in C
Type conversion, also known as type casting, is the process of converting a value of one data type into
another.
C supports two types of type conversion
• Implicit Type Conversion (Coercion):
o Performed automatically by the compiler when operations involve operands of
different data types.
o The compiler promotes the "smaller" data type to the "larger" data type to prevent
data loss during calculations. This follows a hierarchy (e.g., int to float, float to double).
o Example:
int i = 10;
float f = 5.5;
float result = i + f; // 'i' is implicitly converted to float before addition
• Note: While generally safe, implicit conversions can lead to precision loss or unexpected
behaviour in certain cases (e.g., converting a float to an int truncates the decimal part).
Programs can choose which part of the code to execute based on some condition. This ability is
called decision making and the statements used for it are called conditional statements. These
statements evaluate one or more conditions and make the decision whether to execute a block of code
or not.
In C we have different types of conditional statements in c. They are as follows:-
Selection Statements-
A condition is any expression that evaluates to either a true or false (or values convertible to true or
false).
#include <stdio.h>
int main()
{
int i = 10;
// If statement
if (i < 18) {
printf("Eligible for vote");
}
}
The expression inside () parenthesis is the condition and set of statements inside {} braces is its body.
If the condition is true, only then the body will be executed.
If there is only a single statement in the body, {} braces can be omitted.
2. if-else:-
The if statement alone tells us that if a condition is true, it will execute a block of statements and if the
condition is false, it won’t. But what if we want to do something else when the condition is false? Here
comes the C else statement. We can use the else statement with the if statement to execute a block
of code when the condition is false. The if-else statement consists of two blocks, one for false
expression and one for true expression.
#include <stdio.h>
int main()
{
int i = 10;
if (i > 18)
{
printf("Eligible for vote");
}
else
{
printf("Not Eligible for vote");
}
return 0;
}
The block of code following the else statement is executed as the condition present I the if statement
is false.
3. Nested if-else:-
A nested if in C is an if statement that is the target of another if statement. Nested if statements mean
an if statement inside another if statement. Yes, C allow us to nested if statements within if statements,
i.e, we can place an if statement inside another if statement.
#include <stdio.h>
int main()
{
int i = 10;
if (i == 10)
{
if (i < 18)
printf("Still not eligible for vote");
else
printf("Eligible for vote\n");
}
else {
if (i == 20) {
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}
return 0;
}
4. if-else-if Ladder:-The if else if statements are used when the user has to decide among multiple
options. The C if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if
ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. if-
else-if ladder is similar to the switch statement.
#include <stdio.h>
int main() {
int i = 20;
return 0;
}
5. Switch Statement in C
The switch case statement is an alternative to the if else if ladder that can be used to execute the
conditional code based on the value of the variable specified in the switch statement. The switch block
consists of cases to be executed based on the value of the switch variable.
#include <stdio.h>
int main() {
return 0;
}
2. Iterative Statements:- Iteration statements, commonly known as loops, are statements in
programming used to execute part of code repeatedly based on condition or set of conditions. These
constructs are important for performing repetitive tasks efficiently. In this article, we will discuss
various types of iteration statements and their use in different programming languages.
Entry Controlled also called as Pre Test loops and Exit Controlled are called as Post Test Loops.
1. For Loop: For loops iterate over a range of values or elements in a collection. These are mainly used
where the number of iterations is known beforehand like iterating through elements in an array or
predefined range.
#include <stdio.h>
int main() {
printf("Hello \n");
return 0;
2. while loop: The while loop repeatedly executes a block of code as long as a specified condition
remains true. The condition is checked before each iteration.
while (condition)
#include <stdio.h>
int main()
// Initialization expression
int i = 0;
// Test expression
while(i <= 5)
// update expression
i++;
return 0;
3. do-while loop: The do-while loop is similar to the while loop, but it guarantees that the code block
will be executed at least once, as the condition is checked after the first iteration.
Do
while (condition);
#include <stdio.h>
int main() {
// Initialization expression
int i = 0;
do
// loop body
// Update expression
i++;
// Condition to check
return 0;
3. Jump Statements:
• break statement:
Terminates the execution of the innermost enclosing loop (or switch statement) and transfers control
to the statement immediately following the loop.
• continue statement:
Skips the remaining statements in the current iteration of the loop and proceeds to the next iteration.
Basic purpose Terminates the loop entirely. Skips the current iteration of the loop and
proceeds to the next one.
Effect on Ends all remaining iterations. Terminates only the current iteration.
iterations
Code skipped All code after the break statement Only the code after the continue statement
inside the loop is skipped, and no within the current iteration is skipped.
further iterations occur.
Applicability Can be used in loops (for, while, do- Can only be used inside loops
while) and switch statements. (for, while, do-while).
Nested loops In a nested loop, break exits only the In a nested loop, continue skips only the
innermost loop it's placed in. current iteration of the innermost loop it's
placed in.
Use cases Exiting a search once an item is found, Skipping over invalid or unwanted data
or terminating a loop due to an error. points, such as ignoring a negative number
when calculating a sum.
Conditional Operator in C
The conditional operator is used to add conditional code in our program. It is similar to the if-else
statement. It is also known as the ternary operator as it works on three operands.
#include <stdio.h>
int main()
{
int var;
int flag = 0;
// using conditional operator to assign the value to var
// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);
return 0;
}
#include <stdio.h>
int main() {
int number;
return 0;
}
Output:-
Enter an integer: 7
7 is Odd.
Unit -3
Arrays and Functions
Key Differences:
• Storage:
Normal variables store a single value, while arrays store multiple values of the same type.
• Memory Allocation:
Normal variables get a single memory location, while arrays get a contiguous block of memory.
• Access:
Normal variables are accessed directly by their name. Array elements are accessed using the array
name and an index (e.g., numbers[0], name[3]).
• Purpose:
Normal variables are used for individual data points, while arrays are used for collections of related
data.
Arrays: An array is a linear data structure that stores a fixed-size sequence of elements of the same
data type in contiguous memory locations. Each element can be accessed directly using its index, which
allows for efficient retrieval and modification.
Arrays are used to store multiple values of the same data type in a single, organized structure, making
code more concise and efficient. They provide fast access to elements using an index, are memory-
efficient due to contiguous storage, and are fundamental for managing large datasets.
Types of Arrays in C:
One-Dimensional Arrays:
• These are the simplest form of arrays, representing a linear list of elements.
• They are declared with a single set of square brackets [] specifying the size.
int numbers[5]; // Declares an array named 'numbers' that can hold 5 integers.
• These arrays have more than one dimension and can be visualized as grids or tables.
• They are declared with multiple sets of square brackets, each representing a dimension.
• Two-Dimensional Arrays (Matrices):
• Represent data in rows and columns.
Example:
int matrix[3][4]; // Declares a 2D array with 3 rows and 4 columns.
Three-Dimensional Arrays:
• Represent data in layers, rows, and columns, often used for 3D graphics or simulations.
• Example:
int cube[2][3][4]; // Declares a 3D array with 2 layers, 3 rows, and 4 columns.
Syntax for declaring a 1-D Array:-
datatype array name[size of the array];
Ex:-int a[10];
Creating an Array
The whole process of creating an array can be divided into two primary sub processes i.e.
1. Array Declaration
Array declaration is the process of specifying the type, name, and size of the array. In C, we have to
declare the array like any other variable before using it.
When we declare an array in C, the compiler allocates the memory block of the specified size to the
array name.
2. Array Initialization
When the array is declared or allocated memory, the elements of the array contain some garbage
value. So, we need to initialize the array to some meaningful values.
• We can skip mentioning the size of the array if declaration and initialisation are done at the
same time.
• We can also partially initialize while declaring. In this case, the remaining elements will be
assigned the value 0 (or equivalent according to the type).
#include <stdio.h>
int main() {
return 0;
}
5. Examples
int main() {
int a[5];
6. Important Points
• Arrays have fixed size.
• Index starts at 0.
• All elements stored in contiguous memory.
• Array name itself is the base address.
• Can access any element with a[index].
7. Types of Arrays
1) One-Dimensional Array
int a[10];
2) Two-Dimensional Array
int b[3][3];
A multi-dimensional array is an array of arrays.
The most common is the 2D array, which you can imagine as a table (rows × columns).
3. Accessing Elements
Use two indexes:
a[row][col]
Example:
printf("%d", a[1][2]); // prints element at row 1, column 2
5. Operations on 2D Arrays
5.1 Addition of Two Matrices
int c[10][10];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
5.2 Subtraction
c[i][j] = a[i][j] - b[i][j];
6. Memory Representation
A 2D array is stored in row-major order:
all elements of the first row, followed by the second row, etc.
Example:
int a[2][3] = {{1,2,3},{4,5,6}};
Memory layout:
123456
7. 3D Arrays
Declaration
int a[2][3][4];
Meaning:
• 2 blocks
• each block has 3 rows
• each row has 4 columns
Initialization
int a[2][2][2] = {
{ {1,2}, {3,4} },
{ {5,6}, {7,8} }
};
Access
a[x][y][z];
8. Example Programs
int main() {
int a[3][3];
printf("Enter 9 numbers:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
}
}
printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", a[i][j]);
}
printf("\n");
}
return 0;
}
int main() {
int a[10][10], b[10][10], c[10][10];
int r1, c1, r2, c2;
if (c1 != r2) {
printf("Multiplication not possible.");
return 0;
}
printf("Result matrix:\n");
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
printf("%d ", c[i][j]);
}
printf("\n");
}
return 0;
}
Functions:-
Function is a block of code that performs a specific task and has its own scope. It is a basic building
block in c programming.
All c programs have at least one function in a program for example main() function and every function
has its own scope.
A function can also be referred as a method or a sub-routine or a procedure, etc.
Uses of function
• Functions are used for understandability, re-usability, so that you don’t have to write same
code again and again.
• We can use the functions any number of times in a program.
• Massive programs can be tracked when the program is divided into functions.
Parts of function
There are 3 important parts of function
• Function declaration/prototype –
this tells the compiler about the name of the function,
function parameters( type of value the function will accept) and
return type of function(what type of value the function will return)
• Function definition – In this part you will define what the function will do, function body.
• Function call – In this part you will use the function in the program where it is needed, at that
time you don’t have to write the code again.
Syntax of function
return_type function_name( parameter list)
{
body of the function
}
User defined function
C allows users to define their functions as their requirements, these functions which are defined by
user are known as user defined functions.
For example:
#include <stdio.h>
void add(); // declaration of function(prototype)
int main()
{
add(); //function call
}
void add() // body of the function
{
float a,b,c;
printf("\tenter two numbers to add\n\t");
scanf("%f%f",&a,&b);
c=a+b;
printf("\t addtion is:%f",c);
}
Standard library functions:
The standard library functions are built in functions in C programming language which are already
included in the header file that you are using, you don’t have to define them separately.
For example, printf() which is defined in the header file stdio.h and some other built in functions of
stdio.h are scanf()
printf()
getchar()
etc.
#include <stdio.h>
void add(); // declaration of void type function function(prototype)
int main()
{
add(); //function call
}
void add() // body of the function
{
float a,b,c;
printf("\tenter two numbers to add\n\t");
scanf("%f%f",&a,&b);
c=a+b;
printf("\t addtion is:%f",c);
}
2. Function with argument and no return type
In this method, argument type is defined in the function argument and the return type of the function
is void. Let’s take an example to understand it,
#include <stdio.h>
void add(int); // declaration of function(prototype)
int main()
{
}
void add(int n) // body of the function
{
int a,c;
printf("\tenter a number to add\n\t");
scanf("%d",&a);
c=n+a;
printf("\t addtion is:%d",c);
}
3. Function with no argument and return type
In this method no argument is passed in the function and the return type of the function is [Link]
type of function return some value when we call the function from the main().
Let’s take an example to understand it,
#include <stdio.h>
int add(); // declaration of int type function(prototype)
int main()
{
int k;
k=add(); //function call with return type no argument
printf("\t answer is %d",k);
}
int add() // body of the function
{
int a,b,c;
printf("\tenter two numbers to add\n\t");
scanf("%d%d",&a,&b);
c=b+a;
return c;
}
4. Function with argument and return type
In this method argument is passed while defining, declaring and calling the [Link] type of
function return some value when we pass an argument in function calling statement in main() function.
void fun()
{
int m=111,n=222,o=333,p=444;
printf("\n\t can only be accessed inside this fun function %d %d %d %d",m,n,o,p);
#include <stdio.h>
Void printArr(int [], int );
// Array passed as an array without the size of its
// dimension
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5};
return 0;
}
Explanation: In this example, we pass an integer array arr to the function printArr(). In the function
prototype, we define the array as the array of integers with no size information.
Here, you may also notice that we have passed the size of the array as second parameter to the
function. It is recommended to pass the size of the array to the function as another parameter,
otherwise we won't know how many elements to process.
The other ways of passing arrays as pointers include:
Passing as Sized Array
Similar to the above method, we can also define the size of the array while passing it to the function.
But it still will be treated as pointer in the function.
Recursion:- Recursion is a programming technique where a function calls itself to solve a problem. It's
often used to break down complex problems into smaller, similar sub-problems. A recursive function
must have a base case to prevent infinite recursion, which is a condition that stops the function from
calling itself further.
#include <stdio.h>
return 0;
}
Storage Classes:- In C, storage classes define the lifetime, scope, and visibility of variables. They specify
where a variable is stored, how long its value is retained, and how it can be accessed which help us to
trace the existence of a particular variable during the runtime of a program.
auto
This is the default storage class for all the variables declared inside a function or a block. Auto variables
can be only accessed within the block/function they have been declared and not outside them (which
defines their scope).
Properties of auto Variables
• Scope: Local
• Default Value: Garbage Value
• Memory Location: RAM
• Lifetime: Till the end of its scope
#include <stdio.h>
int main() {
// Prints: Count = 1
counter();
// Prints: Count = 2
counter();
return 0;
}
Explanation: The static variable count retains its value between function calls. Unlike local variables,
which are reinitialized each time the function is called, static variables remember their previous value.
register
This storage class declares register variables that have the same functionality as that of the auto
variables. The only difference is that the compiler tries to store these variables in the register of the
microprocessor if a free register is available making it much faster than any of the other variables.
Properties of register Storage Class Objects
• Scope: Local
• Default Value: Garbage Value
• Memory Location: Register in CPU or RAM
• Lifetime: Till the end of its scope
#include <stdio.h>
int main() {
// Global variable
int globalVar = 100;
void printGlobalVar();
int main() {
Pointer:- One of the powerful features of C is ability to access the memory variables by their memory
address. This can be done by using Pointers. The real power of C lies in the proper use of Pointers.
A pointer is a variable that can store an address of a variable (i.e., 112300).We say that a pointer points
to a variable that is stored at that address. A pointer itself usually occupies 4 bytes of memory (then it
can address cells from 0 to 232-1).
Advantages of Pointers:
1. A pointer enables us to access a variable that is defined out side the function.
2. Pointers are more efficient in handling the data tables.
3. Pointers reduce the length and complexity of a program.
4. They increase the execution speed.
Definition :
A variable that holds a physical memory address is called a pointer variable or Pointer.
Declaration :
Datatype * Variable-name;
Eg:- int *ad; /* pointer to int */
char *s; /* pointer to char */
float *fp; /* pointer to float */
char **s; /* pointer to variable that is a pointer to char */
A pointer is a variable that contains an address which is a location of another variable in memory.
Consider the Statement
p=&i;
Here & is called address of a variable. p contains the address of a variable i.
The operator & returns the memory address of variable on which it is operated, this is called
Referencing.
The * operator is called an indirection operator or dereferencing operator which is used to display the
contents of the Pointer Variable.
Consider the following Statements :
int *p,x;
x =5;
p= &x;
Assume that x is stored at the memory address 2000. Then the output for the following printf
statements is :
Output
Pointer Arithmetic :-Pointer Arithmetic is the set of valid arithmetic operations that can be performed
on pointers. The pointer variables store the memory address of another variable. It doesn't store any
value.
Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C
pointer arithmetic operations are slightly different from the ones that we generally use for
mathematical calculations. These operations are:
1. Increment/Decrement of a Pointer
2. Addition of integer to a pointer
3. Subtraction of integer to a pointer
4. Subtracting two pointers of the same type
5. Comparison of pointers
Note: When we use pointers in programs, their addresses keep changing on every run because modern
operating systems use ASLR(Address space layout randomization), which randomizes memory
locations for security.
1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually
increments by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int),
and the new address will point to 1004. While if a float type pointer is incremented then it will
increment by 4(size of a float) and the new address will be 1004.
Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it
actually decrements by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an
int), and the new address will point to 996. While if a float type pointer is decremented then it will
decrement by 4(size of a float) and the new address will be 996.
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // Points to first element
printf("Initial pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);
// Pointer + 1
ptr = ptr + 1;
printf("After ptr = ptr + 1\n");
printf("Pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);
// Pointer - 1
ptr = ptr - 1;
printf("After ptr = ptr - 1\n");
printf("Pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);
// Pointer increment (ptr++)
ptr++;
printf("After ptr++\n");
printf("Pointer address: %p\n", ptr);
printf("Value at ptr: %d\n\n", *ptr);
// Pointer difference
int *p1 = &arr[1];
int *p2 = &arr[4];
printf("Pointer difference (p2 - p1): %ld elements apart\n", p2 - p1);
return 0;
}
Difference between Pass By Value and Pass By Reference(Call by value and Call by reference)
Use when you want to protect original data. Use when you want to modify original data.
printf("%d", *p); // 10
p++;
printf("%d", *p); // 20
Each increment moves by size of data type (4 bytes for int).
No multiplication or division on pointers for element access.
Accessing Array Elements Using Pointers
Example:
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
printf("%c", *p); // H
printf("%c", *(p+1)); // e
int main() {
int a[5] = {1,2,3,4,5};
display(a); // base address sent
}
In Simple Words:
Dynamic memory = memory given at runtime → flexible, efficient and adjustable.
Dynamic Memory Allocation (DMA) means allocating memory at runtime using pointers.
C provides 4 functions (in <stdlib.h>):
1. malloc()
The malloc() (stands for memory allocation) function is used to allocate a single block of contiguous
memory on the heap at runtime. The memory allocated by malloc() is uninitialized, meaning it contains
garbage values.
Assume that we want to create an array to store 5 integers. Since the size of int is 4 bytes, we need 5
* 4 bytes = 20 bytes of memory. This can be done as shown:
int *p = (int*)malloc(5 * sizeof(int));
• Memory contains garbage values.
2. calloc()
The calloc() (stands for contiguous allocation) function is similar to malloc(), but it initializes the
allocated memory to zero. It is used when you need memory with default zero values.
int *p = (int*)calloc(5, sizeof(int));
3. realloc()
realloc() function is used to resize a previously allocated memory block. It allows you to change the
size of an existing memory allocation without needing to free the old memory and allocate a new
block.
Suppose we initially allocate memory for 5 integers but later need to expand the array to hold 10
integers. We can use realloc() to resize the memory block:
p = (int*)realloc(p, 10 * sizeof(int));
4. free()
The memory allocated using functions malloc() and calloc() is not de-allocated on their own.
The free() function is used to release dynamically allocated memory back to the operating system. It
is essential to free memory that is no longer needed to avoid memory leaks.
free(p);
Program to implement dynamic memory
#include <stdio.h>
#include <stdlib.h>
int main() {
int *p, n, i;
// allocate memory
p = (int *) malloc(n * sizeof(int));
// store values
for (i = 0; i < n; i++) {
printf("Enter value %d: ", i + 1);
scanf("%d", &p[i]);
}
// print values
printf("\nYou entered:\n");
for (i = 0; i < n; i++) {
printf("%d ", p[i]);
}
Strings:- You need to often manipulate strings according to the need of a problem. Most, if not all, of
the time string manipulation can be done manually but, this makes programming complex and large.
To solve this, C supports a large number of string handling functions in the standard library "string.h".
Few commonly used string handling functions are discussed below:
int main() {
char s1[50] = "Hello";
char s2[50] = "World";
char s3[50];
// 1. strlen()
printf("Length of s1 = %lu\n", strlen(s1));
// 2. strcpy()
strcpy(s3, s1);
printf("After strcpy, s3 = %s\n", s3);
// 3. strcat()
strcat(s1, s2);
printf("After strcat, s1 = %s\n", s1);
// 4. strcmp()
if (strcmp("abc", "abc") == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
char temp[50] = "ABCDEF", rev[50];
int len = strlen(temp);
for (int i = 0; i < len; i++)
rev[i] = temp[len - 1 - i];
rev[len] = '\0';
printf("Reversed string = %s\n", rev);
return 0;
}
Preprocessors
Preprocessors are programs that process the source code before the actual compilation begins. They
are not part of the compilation process but operate separately, allowing programmers to modify the
code before compilation.
• It is the first step that the C source code goes through when being converted into an executable
file.
• Main types of Preprocessor Directives are Macros, File Inclusion, Conditional Compilation and
Other directives like #undef, #pragma, etc.
• Mainly these directives are used to replace a given section of C code with another C code. For
example, if we write "#define PI 3.14", then PI is replaced with 3.14 by the preprocessor.
#include <stdio.h>
// Macro Definition
#define LIMIT 5
int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
Unit 5
Structures
Structure (also called structs) is a way to group several related variables into one place.
Each variable in the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, float, char, etc.).
Create a Structure
You can create a structure by using the struct keyword and declare each of its members inside
curly braces:
example
// Create a structure called myStructure
#include<stdio.h>
struct myStructure
{
int myNum;
char myLetter;
};
int main()
{
// Create a structure variable of myStructure called s1
struct myStructure s1;
// Print values
printf("My number: %d\n", [Link]);
printf("My letter: %c\n", [Link]);
return 0;
}
struct Address
{
char city[20];
int pincode;
};
struct Student {
char name[20];
int roll;
struct Address addr; // Nested structure
};
int main() {
struct Student s;
// Assign values
printf("Enter name: ");
scanf("%s", [Link]);
// Display
printf("\n--- Student Details ---\n");
printf("Name: %s\n", [Link]);
printf("Roll: %d\n", [Link]);
printf("City: %s\n", [Link]);
printf("Pincode: %d\n", [Link]);
return 0;
}
#include <stdio.h>
struct Student {
char name[20];
int roll;
};
int main() {
struct Student s[3]; // Array of structures
int i;
// Input details
for(i = 0; i < 3; i++) {
printf("Enter name of student %d: ", i+1);
scanf("%s", s[i].name);
// Display details
printf("\n--- Student Details ---\n");
for(i = 0; i < 3; i++) {
printf("Name: %s, Roll: %d\n", s[i].name, s[i].roll);
}
return 0;
}
struct Student {
char name[20];
int roll;
};
int main() {
struct Student s1 = {"Ravi", 10};
return 0;
}
struct Student {
char name[20];
int roll;
};
int main() {
struct Student s1 = getStudent();
printf("\nStudent Details:\n");
printf("Name: %s\nRoll: %d\n", [Link], [Link]);
return 0;
}
Union:-
A union is like a structure, but with one major difference:
All members share the same memory location.
So, only one member can store a value at a time.
Because of shared memory, a union uses less memory than a structure.
union unionName {
dataType member1;
dataType member2;
...
};
Passing a Union to a Function:-
#include <stdio.h>
union Data {
int i;
float f;
char ch;
};
int main() {
union Data d;
return 0;
}
union Data {
int i;
float f;
char ch;
};
int main() {
union Data d1 = getData();
return 0;
}
return 0;
}
What are argc and argv?
Name Full Form Meaning
argc Argument Count Number of inputs + program name
argv Argument Vector Array of strings containing inputs
Simple Program: Add Two Numbers (Command Line Arguments)
#include <stdio.h>
#include <stdlib.h> // for atoi()
if (argc < 3) {
printf("Please provide two numbers.\n");
return 0;
}
sum = a + b;
return 0;
}
File:-
What is a File in C?
A file is a permanent storage area on disk. In C, files are handled using the FILE pointer. Basic file
operations include opening (fopen), reading (fscanf, fgetc), writing (fprintf, fputc), and closing
(fclose). File modes like "r", "w", and "a" control how the file is accessed.
A file is a place on your storage (like hard disk) where data is permanently stored.
Example files:
• text file → .txt
• data file → .dat
• student record file
• marks file, etc.
int main() {
FILE *fp;
fp = fopen("[Link]", "w"); // open file in write mode
if (fp == NULL) {
printf("Error opening file.\n");
return 0;
}
return 0;
}
int main() {
FILE *fp;
char ch;
fp = fopen("[Link]", "r");
if (fp == NULL) {
printf("File not found.\n");
return 0;
}
fclose(fp);
return 0;
}
Meaning of FILE *fp
FILE → data type
fp → file pointer (points to a file)
It is used by all file functions.
program to copy the content of one file to anothere
#include <stdio.h>
int main() {
FILE *src, *dest;
char ch;
fclose(src);
fclose(dest);
return 0;
}
program to display the largest of three numbers passed as arguments
#include <stdio.h>
#include <stdlib.h>
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = atoi(argv[3]);
int largest = a;
if (b > largest)
largest = b;
if (c > largest)
largest = c;
return 0;
}