Bubble Sort Pass By Pass Animation
Pass : 0
Comparison : 0
Click Start
VILL- DEBANDI, AMTA, HOWRAH PIN-711410 Phone-9836357266
Computer Science NEP Syllabus
✅ Introduction to Programming
✅ What is C?
✅ History of C
✅ Evolution of C
✅ Features of C
✅ Advantages of C
✅ Applications of C
After completing this lesson, students will be able to:
Programming is the process of creating a sequence of instructions that enables a computer to perform a specific task. These instructions are written using a programming language and are collectively called a program.
A computer cannot understand human language directly. Therefore, programmers write instructions in a programming language, which are later translated into machine language by a compiler or interpreter.
Programming is not just about writing code; it also involves analyzing problems, designing solutions, testing programs, and maintaining software.
Programming is essential because computers require precise instructions to perform tasks. Without programming, computers cannot process data, solve problems, or execute applications.
Programming is used to develop:
A computer never guesses. It only performs the instructions provided by the programmer.
C is a general-purpose, procedural programming language designed to develop efficient and reliable software.
It provides the programmer with both high-level programming features and low-level memory access, making it suitable for developing operating systems as well as application software.
Because of its speed, simplicity, and flexibility, C is often referred to as the foundation of modern programming languages.
C is a procedural, compiled, and general-purpose programming language developed by Dennis Ritchie at Bell Laboratories in 1972 for developing the UNIX operating system.
During the 1960s and early 1970s, computer programmers required a language that was efficient, portable, and capable of system-level programming. Existing languages either lacked flexibility or were too closely tied to specific hardware.
To address these limitations, Dennis Ritchie developed the C programming language at Bell Laboratories in 1972. It was initially created to rewrite significant portions of the UNIX operating system.
The language quickly gained popularity because it combined the efficiency of low-level languages with the readability of high-level languages. Over time, C became one of the most influential programming languages in the history of computing.
Dennis MacAlistair Ritchie was an American computer scientist and one of the most influential pioneers in software development.
Bell Laboratories (Bell Labs) is a world-renowned research organization known for groundbreaking innovations in science and technology.
Notable inventions from Bell Labs include:
The C language evolved from earlier programming languages developed for system programming.
| Language | Developer | Year | Purpose |
|---|---|---|---|
| ALGOL | International Committee | 1960 | Scientific Computing |
| BCPL | Martin Richards | 1967 | System Programming |
| B | Ken Thompson | 1970 | UNIX Development |
| C | Dennis Ritchie | 1972 | General & System Programming |
ALGOL
↓
BCPL
↓
B Language
↓
C Language
↓
C++
↓
Java
↓
C#
The B programming language lacked several important features such as support for multiple data types and efficient system programming.
C was developed to overcome these limitations by providing:
C has a straightforward syntax and a relatively small set of keywords, making it easier to learn.
Programs written in C execute quickly because they are compiled into machine code.
The same C program can often run on different operating systems with little or no modification.
C encourages dividing large programs into smaller functions, improving readability and maintenance.
The C Standard Library provides numerous built-in functions for input/output, mathematics, string handling, memory management, and file operations.
C combines the advantages of high-level programming with the ability to perform low-level operations such as direct memory access.
C allows memory to be allocated and released during program execution using functions like malloc(), calloc(), realloc(), and free().
C is used in many areas of computing, including:
This part introduced the fundamentals of programming and the C programming language. We explored why programming is important, learned about the origin and evolution of C, discussed its major features and advantages, and examined its wide range of applications. These concepts provide the foundation for understanding the rest of the course.
After studying this chapter, you will be able to:
Every programming language follows a specific structure or format. Similarly, a C program consists of several components that work together to perform a task.
A well-structured C program is easier to understand, debug, modify, and maintain. Although some parts of a C program are optional, the main() function is mandatory because program execution always begins from this function.
A simple C program contains the following sections:
Documentation Section
↓
Link Section
↓
Definition Section
↓
Global Declaration Section
↓
main() Function
↓
User-defined Functions
This section contains comments that describe the purpose of the program.
Example
/* Program to print Hello World */
Comments improve readability but are ignored by the compiler.
The link section includes the required header files.
Example
#include<stdio.h>
The #include directive tells the compiler to include the contents of the header file before compilation.
This section defines symbolic constants using the #define directive.
Example
#define PI 3.14159
Here, every occurrence of PI is replaced with 3.14159 before compilation.
Variables and function prototypes declared outside all functions are called global declarations.
Example
int total;
float average;
These variables can be accessed by all functions in the program.
The main() function is the starting point of every C program.
General syntax:
int main()
{
statements;
return 0;
}
The statements inside the braces { } are executed sequentially.
These are additional functions created by the programmer to perform specific tasks.
Example
void display()
{
printf("Welcome");
}
Functions improve code reusability and modularity.
#include<stdio.h>
int main()
{
printf("Hello, World!");
return 0;
}
Hello, World!
#include<stdio.h>
Includes the Standard Input Output library.
int main()
Declares the main function.
{
Marks the beginning of the function body.
printf("Hello, World!");
Displays the message on the screen.
return 0;
Indicates successful completion of the program.
}
Marks the end of the function.
Source Code
│
▼
Compiler
│
▼
Object Code
│
▼
Linker
│
▼
Executable File
│
▼
Program Output
The execution of a C program takes place in four stages:
A header file contains declarations of library functions.
Common header files are:
| Header File | Purpose |
|---|---|
| stdio.h | Input and Output |
| math.h | Mathematical Functions |
| string.h | String Functions |
| stdlib.h | Memory Management |
| time.h | Date and Time |
The printf() function is used to display output.
Syntax
printf("message");
Example
printf("Programming in C");
Output
Programming in C
The return statement terminates the function and returns control to the operating system.
Example
return 0;
A return value of 0 generally indicates that the program executed successfully.
Comments are explanatory notes written within a program to improve readability. They are ignored by the compiler.
// This is a comment
/*
This
is
a
comment
*/
main() function.
;).
{} define the function body.
After studying this chapter, students will be able to:
An algorithm is a finite sequence of clear and logical steps designed to solve a specific problem or perform a particular task.
An algorithm is independent of any programming language. It focuses on the logic required to solve a problem rather than the syntax of a programming language.
An algorithm is a well-defined sequence of instructions that, when followed correctly, produces the desired output from the given input and terminates after a finite number of steps.
Before writing a program, a programmer should first think about the solution. An algorithm provides a systematic approach for solving a problem.
Prepare a cup of tea.
This example shows that an algorithm is simply a sequence of logical steps.
A good algorithm should have the following characteristics.
An algorithm should accept zero or more inputs.
Example
Input:
Two numbers
It should produce at least one output.
Example
Output:
Sum of two numbers
Every step should be precise and unambiguous.
Correct
Read two numbers.
Incorrect
Read some values.
An algorithm must terminate after a finite number of steps.
Each step should be simple and executable.
Problem
│
▼
Analysis
│
▼
Algorithm
│
▼
Flowchart
│
▼
Program
│
▼
Testing
│
▼
Output
| Algorithm | Program |
|---|---|
| Sequence of logical steps | Written in a programming language |
| Easy to understand | Requires knowledge of syntax |
| Independent of language | Language dependent |
| Cannot be executed directly | Executable by a computer |
| Used for planning | Used for implementation |
Find the sum of two numbers.
Find the largest of two numbers.
Calculate the area of a rectangle.
As software became larger and more complex, programmers needed a disciplined approach to writing programs. This led to the development of structured programming.
Structured programming is a programming methodology that organizes a program into smaller, manageable units and avoids unnecessary jumps in execution.
Structured programming is a programming approach in which a program is developed using well-defined control structures such as sequence, selection, and iteration.
Structured programming is based on three fundamental control structures.
Statements are executed one after another in the order they appear.
Example
int a = 5;
int b = 10;
int sum = a + b;
printf("%d", sum);
Selection allows the program to choose one path from multiple alternatives based on a condition.
Examples
Example
if (marks >= 40)
printf("Pass");
else
printf("Fail");
Iteration repeats a block of statements until a condition becomes false.
Examples
Example
for(i = 1; i <= 5; i++)
{
printf("%d", i);
}
| Structured Programming | Unstructured Programming |
|---|---|
| Uses functions | Often uses excessive goto statements |
| Easy to read | Difficult to understand |
| Easier debugging | Debugging is difficult |
| Modular | Monolithic |
| Better maintenance | Poor maintenance |
Structured programming is widely used in:
Algorithms provide a clear plan before programming begins. They help programmers think logically and organize solutions step by step. Structured programming builds on this idea by dividing programs into manageable components and using three basic control structures—sequence, selection, and iteration. Together, algorithms and structured programming form the foundation of effective software development in C.
After studying this chapter, students will be able to:
Just as every spoken language has its own alphabet, the C programming language has a defined set of valid characters. These characters are used to write program statements, variable names, operators, and symbols. This collection of permitted characters is known as the character set.
A C compiler accepts only characters that belong to the C character set. Using invalid characters may lead to compilation errors.
A character set is the collection of letters, digits, symbols, and special characters that are recognized by the C compiler.
Uppercase letters
A B C ... Z
Lowercase letters
a b c ... z
0 1 2 3 4 5 6 7 8 9
+ - * / % = < > ! & | ^ ~
( ) { } [ ] ; : , . # ? _ ' " \
These improve readability but generally do not affect program execution.
The character set forms the foundation of every C program. Variables, operators, keywords, and statements are all created using these characters.
A C program is made up of many small units such as keywords, identifiers, constants, operators, and punctuation symbols. These smallest meaningful units are called tokens.
A token is the smallest individual unit of a C program that carries meaning for the compiler.
| Token | Example |
|---|---|
| Keywords | int, if |
| Identifiers | total, marks |
| Constants | 10, 3.14 |
| String Literals | "Hello" |
| Operators | +, -, * |
| Special Symbols | ; , { } ( ) |
int age = 20;
Tokens are:
int
age
=
20
;
Keywords are reserved words that have predefined meanings in the C language. Their purpose is fixed, and they cannot be used as names for variables, functions, or arrays.
A keyword is a reserved word in C that has a predefined meaning and cannot be redefined by the programmer.
| Keyword | Purpose |
|---|---|
| int | Integer data type |
| float | Floating-point data type |
| char | Character data type |
| if | Conditional statement |
| else | Alternative condition |
| for | Loop |
| while | Loop |
| return | Return control |
| break | Exit loop |
| continue | Skip current iteration |
An identifier is a name given by the programmer to variables, functions, arrays, or other program elements.
total
studentName
_marks
salary2025
2marks
student name
float
Marks and marks are different).
A constant is a fixed value whose value remains unchanged throughout program execution.
10
250
-35
3.14
25.75
0.001
'A'
'Z'
'9'
"Computer"
"C Programming"
#define PI 3.14159
A variable is a named memory location used to store data during program execution. Unlike constants, variables can change their values whenever required.
int age;
float salary;
char grade;
int age = 20;
✔ Begin with a letter or underscore.
✔ Cannot contain spaces.
✔ Cannot use keywords.
✔ May contain digits after the first character.
A data type specifies the type of value that a variable can store and the amount of memory allocated to it.
| Data Type | Description | Example |
|---|---|---|
| int | Stores integers | int age; |
| char | Stores characters | char grade; |
| float | Stores decimal numbers | float price; |
| double | Stores large decimal values | double salary; |
| void | Represents no value | void display(); |
Storage classes determine where a variable is stored, how long it exists, and where it can be accessed.
Default storage class for local variables.
auto int x;
Requests storage in CPU registers for faster access.
register int count;
Retains its value between function calls.
static int total;
Used to access global variables declared in another file.
extern int marks;
| Storage Class | Scope | Lifetime | Default Value |
|---|---|---|---|
| auto | Local | Function execution | Garbage value |
| register | Local | Function execution | Garbage value |
| static | Local/Global | Entire program | 0 |
| extern | Global | Entire program | 0 |
Duration: 8 Lectures
After completing this module, students will be able to:
An operator is a special symbol used to perform operations on one or more operands (variables or constants). Operators allow programmers to perform calculations, compare values, assign data, and manipulate bits.
An operator is a symbol that instructs the compiler to perform a specific mathematical, logical, relational, or bitwise operation on one or more operands.
int a = 10, b = 5;
int sum = a + b;
Here,
a and b are operands.
+ is the operator.
Output:
sum = 15
C provides several categories of operators.
| Operator Type | Purpose | Example |
|---|---|---|
| Arithmetic | Mathematical calculations | + - * / % |
| Relational | Compare values | > < >= <= == != |
| Logical | Combine conditions | && || ! |
| Assignment | Assign values | = += -= *= |
| Increment/Decrement | Increase or decrease value | ++ -- |
| Conditional | Decision making | ?: |
| Bitwise | Operate on binary bits | & | ^ ~ << >> |
| Special | Special operations | sizeof, comma, pointer |
Arithmetic operators perform mathematical calculations.
| Operator | Meaning | Example |
|---|---|---|
| + | Addition | a+b |
| - | Subtraction | a-b |
| * | Multiplication | a*b |
| / | Division | a/b |
| % | Modulus | a%b |
#include<stdio.h>
int main()
{
int a=20,b=6;
printf("Addition = %d\n",a+b);
printf("Subtraction = %d\n",a-b);
printf("Multiplication = %d\n",a*b);
printf("Division = %d\n",a/b);
printf("Remainder = %d",a%b);
return 0;
}
Addition = 26
Subtraction = 14
Multiplication = 120
Division = 3
Remainder = 2
Relational operators compare two values and return either 1 (true) or 0 (false).
| Operator | Meaning |
|---|---|
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
| == | Equal to |
| != | Not equal to |
int a=10,b=20;
printf("%d",a<b);
Output
1
Logical operators are used to combine multiple conditions.
| Operator | Meaning |
|---|---|
| && | Logical AND |
| || | Logical OR |
| ! | Logical NOT |
int age=20;
if(age>=18 && age<=60)
printf("Eligible");
Output
Eligible
Assignment operators assign values to variables.
| Operator | Meaning |
|---|---|
| = | Assignment |
| += | Add and assign |
| -= | Subtract and assign |
| *= | Multiply and assign |
| /= | Divide and assign |
| %= | Modulus and assign |
int x=10;
x+=5;
Result
x=15
These operators change the value of a variable by one.
int x=5;
x++;
Output
6
int x=5;
x--;
Output
4
| Prefix | Postfix |
|---|---|
| ++x | x++ |
| Value changes first | Value changes later |
The conditional operator is a compact alternative to the if-else statement.
condition ? expression1 : expression2;
int a=20,b=10;
int max=(a>b)?a:b;
printf("%d",max);
Output
20
Bitwise operators perform operations directly on binary bits.
| Operator | Meaning |
|---|---|
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | XOR |
| ~ | NOT |
| << | Left Shift |
| >> | Right Shift |
int a=5,b=3;
printf("%d",a&b);
Output
1
Common special operators include:
| Operator | Purpose |
|---|---|
| sizeof | Finds memory size |
| , | Comma operator |
| & | Address operator |
| * | Pointer operator |
Example
printf("%d",sizeof(int));
Output (may vary by system)
4
When multiple operators appear in an expression, C follows precedence rules.
Example
10+5*2
Multiplication is performed first.
Result
20
Associativity determines the evaluation order when operators have the same precedence.
Example
20-10-5
Evaluated as
(20-10)-5 = 5
because subtraction is left to right.
if-else statements.
Operators are essential elements of the C language that allow programmers to perform calculations, compare values, evaluate conditions, manipulate bits, and assign data. Understanding the different categories of operators, along with operator precedence and associativity, helps in writing accurate and efficient C programs.
After studying this chapter, students will be able to:
An expression is a combination of operands (constants, variables, or function calls) and operators that evaluates to a single value.
Expressions are the foundation of computations in C. They are used in assignments, conditions, loops, and function calls.
An expression is a valid combination of variables, constants, operators, and function calls that produces a single value when evaluated.
int a = 10;
int b = 20;
int c = a + b;
Here,
a + b
is an expression.
Result
30
Performs mathematical calculations.
Example
x + y
a * b
Compares two values.
Example
a > b
Result
True or False
Uses logical operators.
Example
(a>b)&&(b>c)
Assigns value.
Example
x = 10
Uses the ternary operator.
Example
(a>b)?a:b
Sometimes an expression contains different data types. The compiler automatically converts smaller data types into larger compatible data types.
This process is called Type Conversion.
It is also known as Implicit Type Conversion.
int a=10;
float b=5.5;
float c=a+b;
The integer value is automatically converted into float.
Output
15.5
char
↓
int
↓
float
↓
double
Smaller data types are promoted to larger data types automatically.
Sometimes the programmer wants to convert a value into another data type manually.
This is called Type Casting.
(data_type) expression;
int a=10,b=3;
float c=(float)a/b;
printf("%f",c);
Output
3.333333
Without casting, the result would be
3
because integer division truncates the decimal part.
| Type Conversion | Type Casting |
|---|---|
| Automatic | Manual |
| Compiler performs conversion | Programmer performs conversion |
| No syntax required | Uses (data_type) |
| Safe conversion | Depends on programmer |
The scanf() function reads data from the keyboard.
scanf("format",&variable);
#include<stdio.h>
int main()
{
int age;
printf("Enter Age : ");
scanf("%d",&age);
printf("Age = %d",age);
return 0;
}
Output
Enter Age : 20
Age = 20
| Data Type | Format Specifier |
|---|---|
| int | %d |
| float | %f |
| char | %c |
| double | %lf |
| string | %s |
The printf() function displays information on the screen.
printf("format",variable);
int marks=90;
printf("Marks=%d",marks);
Output
Marks=90
Escape sequences begin with a backslash (\) and represent special characters.
| Escape Sequence | Meaning |
|---|---|
| \n | New Line |
| \t | Horizontal Tab |
| \b | Backspace |
| \r | Carriage Return |
| \ | Backslash |
| " | Double Quote |
| ' | Single Quote |
printf("Hello\nWorld");
Output
Hello
World
printf("A\tB\tC");
Output
A B C
Comments improve readability by explaining program logic. They are ignored by the compiler.
// This is a comment
/*
This is
a comment
*/
Preprocessor directives are instructions processed before compilation.
They always begin with the # symbol.
| Directive | Purpose |
|---|---|
| #include | Includes header file |
| #define | Defines constant |
| #ifdef | Conditional compilation |
| #ifndef | Conditional compilation |
| #undef | Removes macro |
#include<stdio.h>
Includes the Standard Input Output library.
#define PI 3.14159
Defines a symbolic constant.
A macro is a named fragment of code created using the #define directive. During preprocessing, every occurrence of the macro name is replaced by its definition.
Macros improve readability and reduce duplication.
#define name replacement
#define PI 3.14159
float area = PI * r * r;
#define SQUARE(x) ((x)*(x))
Usage
printf("%d",SQUARE(5));
Output
25
scanf() is used for input.
printf() is used for output.
Module 2 introduced operators, expressions, input/output functions, type conversion, type casting, comments, preprocessor directives, and macros. These concepts enable programmers to write efficient, readable, and maintainable C programs. Understanding these topics is essential before learning decision-making statements and loops in the next module.
Duration: 7 Lectures
if Statement
if-else Statement
if
else-if Ladder
switch Statement
while Loop
do-while Loop
for Loop
break Statement
continue Statement
goto Statement
After completing this module, students will be able to:
In everyday life, we make decisions based on certain conditions. For example, if it is raining, we carry an umbrella; otherwise, we do not. Similarly, in programming, a program often needs to choose between different actions depending on whether a condition is true or false.
Decision-making statements allow a program to execute specific instructions only when certain conditions are satisfied. These statements improve the flexibility and intelligence of programs.
if StatementThe if statement executes a block of code only if the specified condition is true.
if(condition)
{
// Statements
}
┌────────────┐
│ Condition? │
└─────┬──────┘
│
True ───┘
│
▼
Execute Statements
│
▼
End
#include<stdio.h>
int main()
{
int marks = 80;
if(marks >= 40)
{
printf("Pass");
}
return 0;
}
Pass
if-else StatementWhen there are two possible outcomes, the if-else statement is used.
if(condition)
{
// True block
}
else
{
// False block
}
#include<stdio.h>
int main()
{
int age = 16;
if(age >= 18)
printf("Eligible to Vote");
else
printf("Not Eligible");
return 0;
}
Not Eligible
if StatementA nested if means placing one if statement inside another.
#include<stdio.h>
int main()
{
int age = 22;
char citizen = 'Y';
if(age >= 18)
{
if(citizen == 'Y')
printf("Eligible to Vote");
}
return 0;
}
else-if LadderThe else-if ladder is used when multiple conditions need to be tested one after another.
if(condition1)
{
}
else if(condition2)
{
}
else if(condition3)
{
}
else
{
}
#include<stdio.h>
int main()
{
int marks = 82;
if(marks >= 90)
printf("Grade A+");
else if(marks >= 80)
printf("Grade A");
else if(marks >= 70)
printf("Grade B");
else if(marks >= 40)
printf("Grade C");
else
printf("Fail");
return 0;
}
Grade A
switch StatementThe switch statement is used when one variable needs to be compared against multiple fixed values.
switch(expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
#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;
}
Wednesday
if-else and switchif-else | switch |
|---|---|
| Can test ranges and complex conditions | Tests only fixed constant values |
| Suitable for relational and logical operators | Suitable for equality comparisons |
| Slower for many alternatives | Often easier to read for menu-driven programs |
if-else when conditions involve comparisons like >, <, >=, or logical operators.
switch when checking a variable against a list of constant values.
if executes a block only when a condition is true.
if-else chooses between two alternatives.
if allows one decision inside another.
else-if ladder handles multiple conditions.
switch is useful for menu-driven programs.
Decision-making statements enable a C program to choose different paths based on conditions. The if, if-else, nested if, else-if ladder, and switch statement are commonly used to implement selection logic. Choosing the appropriate statement improves program readability and efficiency.
Duration: 7 Lectures
After completing this chapter, students will be able to:
while, do-while, and for loops.
break, continue, and goto statements effectively.
In many programming situations, a group of statements needs to be executed repeatedly. Instead of writing the same statements multiple times, programmers use loops.
A loop executes a block of code repeatedly until a specified condition becomes false.
Imagine a teacher asks you to write your name 100 times. Writing it manually would be repetitive and time-consuming. A loop allows the computer to repeat the task automatically.
A loop is a control structure that repeatedly executes a block of statements as long as a specified condition is true.
There are three loop statements in C.
| Loop | Condition Checked | Minimum Execution |
|---|---|---|
| while | Before execution | 0 times |
| do-while | After execution | 1 time |
| for | Before execution | 0 times |
The while loop executes a block of statements repeatedly as long as the given condition remains true.
while(condition)
{
statements;
}
┌────────────┐
│ Condition? │
└─────┬──────┘
│True
▼
Execute Block
│
└───────────┐
│
False ▼
End
Display numbers from 1 to 5.
#include<stdio.h>
int main()
{
int i=1;
while(i<=5)
{
printf("%d ",i);
i++;
}
return 0;
}
1 2 3 4 5
| i | Condition | Output |
|---|---|---|
| 1 | True | 1 |
| 2 | True | 2 |
| 3 | True | 3 |
| 4 | True | 4 |
| 5 | True | 5 |
| 6 | False | Stop |
✔ Simple
✔ Suitable when the number of repetitions is unknown.
✔ Easy to understand.
❌ Initialization must be done separately.
❌ Increment or decrement must be written manually.
The do-while loop executes the statements first and checks the condition afterward.
Therefore, the loop executes at least once, even if the condition is initially false.
do
{
statements;
}while(condition);
Execute Block
│
▼
Condition?
│ │
True False
│ │
└──────┘
End
#include<stdio.h>
int main()
{
int i=1;
do
{
printf("%d ",i);
i++;
}while(i<=5);
return 0;
}
1 2 3 4 5
int i=10;
do
{
printf("%d",i);
}while(i<5);
Output
10
Although the condition is false, the statement executes once.
The for loop is mainly used when the number of repetitions is known in advance.
for(initialization;condition;increment)
{
statements;
}
Initialization
│
▼
Condition?
│ │
True False
│ │
▼ End
Execute Block
│
Increment
│
──────┘
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("%d ",i);
}
return 0;
}
1 2 3 4 5
✔ Compact
✔ Easy to write
✔ Suitable for counting loops
✔ Initialization, condition and update remain together.
| Feature | while | do-while | for |
|---|---|---|---|
| Condition Check | Before | After | Before |
| Executes Minimum | 0 | 1 | 0 |
| Initialization | Outside | Outside | Inside |
| Increment | Separate | Separate | Inside |
| Best Used | Unknown iterations | Menu-driven programs | Fixed iterations |
A loop inside another loop is called a nested loop.
Example
#include<stdio.h>
int main()
{
int i,j;
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("* ");
}
printf("\n");
}
return 0;
}
Output
* * *
* * *
* * *
The break statement immediately terminates the nearest loop or switch statement.
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==6)
break;
printf("%d ",i);
}
return 0;
}
Output
1 2 3 4 5
The continue statement skips the remaining statements in the current iteration and moves to the next iteration.
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
printf("%d ",i);
}
return 0;
}
Output
1 2 4 5
The goto statement transfers program control directly to a labeled statement.
goto label;
/* statements */
label:
statement;
#include<stdio.h>
int main()
{
printf("Welcome\n");
goto end;
printf("This line will not execute.\n");
end:
printf("Program End");
return 0;
}
Output
Welcome
Program End
(Prepared for WBSU BCA Semester-I NEP Students)
After completing this module, students will be able to:
A function is a self-contained block of code designed to perform a specific task. Instead of writing the same code repeatedly, we write it once inside a function and call it whenever needed.
Functions make programs modular, organized, and easier to maintain.
A function is a named block of statements that performs a specific operation and can be called whenever required during program execution.
Think of a calculator.
Each button performs a specific task.
Similarly, every function performs one specific task.
Suppose you need to calculate the area of a circle 20 times.
Without functions, you would write the same code 20 times.
With functions, you simply write:
area();
whenever required.
✅ Reduces program size
✅ Avoids code duplication
✅ Improves readability
✅ Easier debugging
✅ Easy maintenance
✅ Code reusability
✅ Supports teamwork
Every function consists of three parts.
Function Declaration
↓
Function Definition
↓
Function Call
#include<stdio.h>
void display();
int main()
{
display();
return 0;
}
void display()
{
printf("Welcome to C Programming");
}
Welcome to C Programming
void display();
Tells the compiler that a function named display() exists.
display();
Transfers program control to the function.
void display()
{
printf("Welcome to C Programming");
}
Contains the actual statements.
There are two types of functions.
These are predefined functions provided by C libraries.
Examples
| Function | Purpose |
|---|---|
| printf() | Display output |
| scanf() | Read input |
| strlen() | Find string length |
| sqrt() | Square root |
| pow() | Power calculation |
| strcpy() | Copy string |
| strcat() | Concatenate strings |
Functions created by the programmer are called user-defined functions.
Example
void welcome()
{
printf("Welcome Students");
}
A function prototype informs the compiler about
Example
int sum(int,int);
General Syntax
return_type function_name(parameters)
{
statements;
return value;
}
Example
int add(int a,int b)
{
return a+b;
}
A function call transfers control to the function.
Example
result=add(10,20);
Functions are classified into four categories.
void display()
{
printf("Hello");
}
Call
display();
void sum(int a,int b)
{
printf("%d",a+b);
}
Call
sum(10,20);
int number()
{
return 50;
}
Call
x=number();
int sum(int a,int b)
{
return a+b;
}
Call
result=sum(10,20);
In Call by Value, a copy of the actual argument is passed to the function.
Any changes made inside the function do not affect the original variable.
Example
void change(int x)
{
x=100;
}
Main
int a=10;
change(a);
printf("%d",a);
Output
10
✔ Safe
✔ Original data remains unchanged
✖ Extra memory is required
✖ Large data copying reduces efficiency
In Call by Reference, the address of the variable is passed.
The function works on the original variable.
Changes made inside the function are reflected in the calling function.
Example
void change(int *x)
{
*x=100;
}
Main
int a=10;
change(&a);
printf("%d",a);
Output
100
| Call by Value | Call by Reference |
|---|---|
| Copy is passed | Address is passed |
| Original value unchanged | Original value changes |
| Uses normal variables | Uses pointers |
| More memory | Less memory |
A function that calls itself is called a recursive function.
Example
void display()
{
printf("Hello");
display();
}
A function calls itself directly.
A()
↓
A()
Two or more functions call each other.
A()
↓
B()
↓
A()
✔ Simple code
✔ Elegant solution
✔ Useful for trees and graphs
✔ Useful for divide-and-conquer algorithms
✖ High memory usage
✖ Slower execution
✖ Risk of stack overflow
Theory: 10 Lectures
After completing this chapter, students will be able to:
An array is a collection of elements of the same data type stored in contiguous memory locations. Each element is identified by an index (subscript).
Instead of creating many separate variables, an array allows multiple values to be stored under a single name.
An array is a collection of similar data items stored in consecutive memory locations and accessed using a common name with an index number.
Suppose you want to store the marks of 100 students.
Without arrays:
int m1,m2,m3,m4,...,m100;
With an array:
int marks[100];
Arrays make programs shorter, more organized, and easier to maintain.
✔ Store multiple values using one variable.
✔ Easy data processing.
✔ Faster access through indexing.
✔ Simplifies searching and sorting.
✔ Reduces code repetition.
❌ Can store only one data type.
❌ Fixed size after declaration.
❌ Insertion and deletion are relatively expensive.
marks[5]
+-----+-----+-----+-----+-----+
| 80 | 75 | 90 | 85 | 95 |
+-----+-----+-----+-----+-----+
0 1 2 3 4
The first element always has index 0.
A one-dimensional array stores elements in a single row.
data_type array_name[size];
Example
int marks[5];
int marks[5]={80,75,90,85,95};
or
int marks[]={80,75,90,85,95};
printf("%d",marks[2]);
Output
90
#include<stdio.h>
int main()
{
int a[5]={10,20,30,40,50};
int i;
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
return 0;
}
10 20 30 40 50
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter 5 numbers:\n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("\nArray Elements:\n");
for(i=0;i<5;i++)
{
printf("%d ",a[i]);
}
return 0;
}
A two-dimensional array stores data in rows and columns, similar to a table or matrix.
data_type array_name[row][column];
Example
int marks[3][4];
int a[2][3]={
{1,2,3},
{4,5,6}
};
Column
0 1 2
Row0 10 20 30
Row1 40 50 60
#include<stdio.h>
int main()
{
int a[2][2]={{10,20},{30,40}};
int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
return 0;
}
10 20
30 40
Arrays having more than two dimensions are called multidimensional arrays.
Example
int data[2][3][4];
These are useful in scientific computing, simulations, graphics, and 3D applications.
A string is a sequence of characters terminated by the null character ('\0').
Example
char name[20];
char name[]="Computer";
Memory Representation
C o m p u t e r \0
char name[20];
scanf("%s",name);
printf("%s",name);
#include<stdio.h>
int main()
{
char name[30];
printf("Enter Name : ");
scanf("%s",name);
printf("Welcome %s",name);
return 0;
}
Enter Name : Rahul
Welcome Rahul
The string.h header file provides several built-in functions for string manipulation.
Finds the length of a string.
Example
#include<stdio.h>
#include<string.h>
int main()
{
char name[]="Computer";
printf("%d",strlen(name));
return 0;
}
Output
8
Copies one string to another.
Example
char s1[]="ABC";
char s2[20];
strcpy(s2,s1);
Concatenates two strings.
Example
char s1[]="Good";
char s2[]="Morning";
strcat(s1,s2);
Output
GoodMorning
Compares two strings.
Example
strcmp("ABC","ABC");
Output
0
A return value of:
0 → Strings are equal.
Reverses a string (available in some compilers, not part of the ISO C standard).
Example
strrev(name);
Converts a string to lowercase (compiler-specific).
Converts a string to uppercase (compiler-specific).
| Function | Purpose |
|---|---|
strlen() | Finds string length |
strcpy() | Copies a string |
strcat() | Joins two strings |
strcmp() | Compares two strings |
strrev() | Reverses a string* |
strupr() | Converts to uppercase* |
strlwr() | Converts to lowercase* |
Note: Functions marked with * are compiler-specific and are not included in the ISO C standard.
| Character Array | String |
|---|---|
| Stores individual characters | Stores a sequence of characters |
May not end with '\0' | Always ends with '\0' |
| Can represent any character data | Represents text |
<string.h> library provides functions for string manipulation.
string.h library. (Theory: 15 Lectures)
(Prepared in original language for WBSU BCA NEP Semester-I Students)
After completing this module, students will be able to:
A pointer is one of the most powerful features of the C programming language. A pointer is a variable that stores the memory address of another variable instead of storing the actual value.
Pointers allow programmers to access and manipulate memory directly, making programs more efficient and flexible.
A pointer is a variable that stores the memory address of another variable.
Pointers are useful because they:
Variable Address
a = 10 2000
Pointer p 3000
│
▼
Address 2000
Here,
data_type *pointer_name;
Examples
int *p;
float *q;
char *ch;
int a=10;
int *p;
p=&a;
Here
&a
means address of variable a.
#include<stdio.h>
int main()
{
int a=10;
int *p;
p=&a;
printf("Value = %d\n",a);
printf("Address = %p\n",&a);
printf("Pointer = %p\n",p);
return 0;
}
Value = 10
Address = 6422296
Pointer = 6422296
(Address varies from computer to computer.)
The symbol * is called the dereferencing operator.
It retrieves the value stored at the memory location pointed to by the pointer.
Example
int a=50;
int *p=&a;
printf("%d",*p);
Output
50
The symbol & is called the address operator.
Example
printf("%p",&a);
Output
Address of a
#include<stdio.h>
int main()
{
int x=100;
int *ptr=&x;
printf("%d\n",x);
printf("%d\n",*ptr);
return 0;
}
Output
100
100
Pointers can perform arithmetic operations.
Allowed operations are:
Example
int a[5]={10,20,30,40,50};
int *p=a;
p++;
Now pointer points to
20
Address
1000 → 10
1004 → 20
1008 → 30
1012 → 40
1016 → 50
Each integer occupies 4 bytes (commonly on modern systems).
The name of an array itself acts as a pointer to its first element.
Example
int a[5]={10,20,30,40,50};
printf("%d",*a);
Output
10
Example
printf("%d",*(a+2));
Output
30
Example
#include<stdio.h>
void change(int *x)
{
*x=100;
}
int main()
{
int a=10;
change(&a);
printf("%d",a);
return 0;
}
Output
100
✔ Faster execution
✔ Efficient memory usage
✔ Dynamic memory allocation
✔ Supports data structures
✔ Enables call by reference
❌ Difficult to understand
❌ Risk of memory leaks
❌ Can cause segmentation faults if misused
& returns the address of a variable.
* accesses the value stored at the pointed address.
Theory: 15 Lectures
After studying this chapter, students will be able to:
In C programming, variables of different data types often need to be stored together. For example, information about a student includes a roll number (integer), name (string), and percentage (float). Declaring separate variables for each student becomes difficult and inefficient.
A structure allows different data types to be grouped together under a single name.
A structure is a user-defined data type that groups related variables of different data types under one name.
A student's record contains:
All these details can be stored in one structure.
struct Student
{
int roll;
char name[30];
float marks;
};
struct Student s1;
The dot (.) operator is used.
Example
s1.roll=101;
strcpy(s1.name,"Rahul");
s1.marks=88.5;
#include<stdio.h>
struct Student
{
int roll;
char name[30];
float marks;
};
int main()
{
struct Student s;
s.roll=101;
strcpy(s.name,"Amit");
s.marks=92.5;
printf("%d\n",s.roll);
printf("%s\n",s.name);
printf("%.2f",s.marks);
return 0;
}
101
Amit
92.50
✅ Groups different data types.
✅ Improves program organization.
✅ Easy data management.
✅ Supports database-like records.
A structure inside another structure is called a nested structure.
Example
struct Date
{
int day;
int month;
int year;
};
struct Student
{
int roll;
struct Date dob;
};
An array can store multiple structure variables.
Example
struct Student s[50];
This can store information for 50 students.
Example
s[0].roll=101;
s[1].roll=102;
A union is also a user-defined data type similar to a structure.
The difference is that all members share the same memory location.
Only one member can hold a valid value at a time.
A union is a user-defined data type in which all members share the same memory location.
union Data
{
int i;
float f;
char name[20];
};
union Data d;
d.i=100;
| Structure | Union |
|---|---|
| Separate memory for each member | Shared memory |
| Large memory usage | Small memory usage |
| All members active simultaneously | Only one member active at a time |
| Suitable for records | Suitable for memory optimization |
✔ Saves memory
✔ Efficient for embedded systems
✔ Useful in device drivers
Normally, memory is allocated during compilation.
Sometimes the required memory size is unknown beforehand.
In such situations, memory is allocated during program execution.
This is called Dynamic Memory Allocation.
| Function | Purpose |
|---|---|
| malloc() | Allocates memory |
| calloc() | Allocates and initializes memory |
| realloc() | Changes memory size |
| free() | Releases memory |
Allocates memory but does not initialize it.
Syntax
pointer=(datatype*)malloc(size);
Example
int *p;
p=(int*)malloc(5*sizeof(int));
Allocates memory and initializes all bytes to zero.
Syntax
pointer=(datatype*)calloc(number,size);
Example
int *p;
p=(int*)calloc(5,sizeof(int));
Changes the size of previously allocated memory.
Syntax
pointer=realloc(pointer,new_size);
Example
p=realloc(p,10*sizeof(int));
Releases allocated memory.
Syntax
free(pointer);
Example
free(p);
| malloc() | calloc() |
|---|---|
| No initialization | Initializes with zero |
| One argument | Two arguments |
| Faster | Slightly slower |
A program stores data in memory temporarily.
When the program ends, the data is lost.
To store data permanently, files are used.
File handling is the process of storing, reading, and modifying data in files using C programs.
Open File
↓
Read/Write
↓
Close File
FILE *fp;
Opens a file.
Syntax
fp=fopen("student.txt","r");
| Mode | Meaning |
|---|---|
| r | Read |
| w | Write |
| a | Append |
| r+ | Read & Write |
| w+ | Read & Write (Overwrite) |
| a+ | Read & Append |
Closes the file.
Syntax
fclose(fp);
Writes formatted data into a file.
Example
fprintf(fp,"%d",100);
Reads formatted data.
Example
fscanf(fp,"%d",&x);
Writes a string.
Example
fputs("Welcome",fp);
Reads a string.
Example
fgets(name,20,fp);
EOF means End Of File.
It indicates that there is no more data available to read.
Example
while((ch=fgetc(fp))!=EOF)
✔ Permanent storage
✔ Large data storage
✔ Easy retrieval
✔ Data sharing
✔ Backup facility
malloc(), calloc(), realloc(), and free() manage dynamic memory.
fclose() after use.
Module 5 introduced advanced programming concepts in C, including pointers, structures, unions, dynamic memory allocation, and file handling. Pointers provide direct access to memory and support efficient programming. Structures organize related data, while unions optimize memory usage. Dynamic memory allocation allows flexible memory management during execution, and file handling enables permanent storage and retrieval of data. Together, these concepts help students build efficient, modular, and real-world C applications.