📘 Computer Fundamentals and Programming with C
Module 1 : Overview of C (Part 1)
📚 Contents
✅ Introduction to Programming
✅ What is C?
✅ History of C
✅ Evolution of C
✅ Features of C
✅ Advantages of C
✅ Applications of C
🎯 Learning Objectives
After completing this lesson, students will be able to:
- Understand the concept of programming.
- Explain the importance of the C programming language.
- Describe the history and evolution of C.
- Identify the major features of C.
- Explain the applications of C in real-world computing.
1. Introduction to Programming
What is Programming?
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.
Why Do We Need Programming?
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:
- Operating Systems
- Mobile Applications
- Desktop Software
- Websites
- Games
- Banking Software
- Artificial Intelligence Applications
- Embedded Systems
💡 Remember
A computer never guesses. It only performs the instructions provided by the programmer.
2. What is C Programming?
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.
Definition
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.
📌 Characteristics of C
- General-purpose language
- Procedural programming language
- Middle-level language
- Compiled language
- Portable
- Efficient
- Structured
- Fast execution
- Rich library support
3. History of C Programming
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 Ritchie
Dennis MacAlistair Ritchie was an American computer scientist and one of the most influential pioneers in software development.
Major Contributions
- Developed the C programming language.
- Co-developed the UNIX operating system.
- Influenced the design of many modern programming languages.
- Received the ACM Turing Award in 1983 for his contributions to computer science.
🏢 Bell Laboratories
Bell Laboratories (Bell Labs) is a world-renowned research organization known for groundbreaking innovations in science and technology.
Notable inventions from Bell Labs include:
- C Programming Language
- UNIX Operating System
- Transistor
- Information Theory
- UNIX Utilities
4. Evolution of C Programming
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 |
Evolution Flow
ALGOL
↓
BCPL
↓
B Language
↓
C Language
↓
C++
↓
Java
↓
C#
5. Why Was C Developed?
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:
- Better performance
- Efficient memory management
- Support for different data types
- Structured programming
- Portability across systems
6. Features of C Programming
1. Simple
C has a straightforward syntax and a relatively small set of keywords, making it easier to learn.
2. Fast
Programs written in C execute quickly because they are compiled into machine code.
3. Portable
The same C program can often run on different operating systems with little or no modification.
4. Structured
C encourages dividing large programs into smaller functions, improving readability and maintenance.
5. Rich Library
The C Standard Library provides numerous built-in functions for input/output, mathematics, string handling, memory management, and file operations.
6. Middle-Level Language
C combines the advantages of high-level programming with the ability to perform low-level operations such as direct memory access.
7. Dynamic Memory Management
C allows memory to be allocated and released during program execution using functions like malloc(), calloc(), realloc(), and free().
7. Advantages of C
- Easy to understand
- Fast execution
- Efficient use of memory
- Portable across platforms
- Supports modular programming
- Extensive standard library
- Widely used in industry
- Ideal for learning programming fundamentals
8. Applications of C
C is used in many areas of computing, including:
- Operating Systems (e.g., UNIX, Linux)
- Embedded Systems
- Device Drivers
- Database Management Systems
- Compiler Development
- Network Programming
- Scientific and Engineering Applications
- Robotics
- Internet of Things (IoT)
- Game Development
📌 Key Points
- C is a general-purpose programming language.
- It was developed by Dennis Ritchie.
- C was created at Bell Laboratories in 1972.
- C was originally developed for the UNIX operating system.
- C remains one of the most widely taught programming languages.
📝 Summary
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.
📘 Computer Fundamentals and Programming with C
Module 1 – Part 2
Basic Structure of a C Program
🎯 Learning Objectives
After studying this chapter, you will be able to:
- Understand the structure of a C program.
- Explain the purpose of each section of a C program.
- Write and execute your first C program.
- Understand the compilation and execution process.
- Use comments correctly.
1. Introduction
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.
2. Basic Structure of a C Program
A simple C program contains the following sections:
Documentation Section
↓
Link Section
↓
Definition Section
↓
Global Declaration Section
↓
main() Function
↓
User-defined Functions
3. Components of a C Program
(a) Documentation Section
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.
(b) Link Section
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.
(c) Definition Section
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.
(d) Global Declaration Section
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.
(e) main() Function
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.
(f) User-defined Functions
These are additional functions created by the programmer to perform specific tasks.
Example
void display()
{
printf("Welcome");
}
Functions improve code reusability and modularity.
4. First C Program
#include<stdio.h>
int main()
{
printf("Hello, World!");
return 0;
}
Output
Hello, World!
5. Explanation of the Program
Line 1
#include<stdio.h>
Includes the Standard Input Output library.
Line 2
int main()
Declares the main function.
Line 3
{
Marks the beginning of the function body.
Line 4
printf("Hello, World!");
Displays the message on the screen.
Line 5
return 0;
Indicates successful completion of the program.
Line 6
}
Marks the end of the function.
6. Flow of Program Execution
Source Code
│
▼
Compiler
│
▼
Object Code
│
▼
Linker
│
▼
Executable File
│
▼
Program Output
7. Compilation Process
The execution of a C program takes place in four stages:
Step 1: Preprocessing
- Header files are included.
- Macros are expanded.
Step 2: Compilation
- Source code is converted into assembly language.
Step 3: Assembling
- Assembly code is converted into object code.
Step 4: Linking
- Library functions are linked.
- Executable file is generated.
8. Header Files
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 |
9. The printf() Function
The printf() function is used to display output.
Syntax
printf("message");
Example
printf("Programming in C");
Output
Programming in C
10. The return Statement
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.
11. Comments in C
Comments are explanatory notes written within a program to improve readability. They are ignored by the compiler.
Single-line Comment
// This is a comment
Multi-line Comment
/*
This
is
a
comment
*/
12. Rules for Writing a C Program
-
Every program must contain the
main()function. -
Every statement should end with a semicolon (
;). -
Curly braces
{}define the function body. - Keywords must be written correctly.
- C is case-sensitive.
- Header files should be included before using library functions.
13. Advantages of a Proper Program Structure
- Easy to read
- Easy to debug
- Easy to maintain
- Supports teamwork
- Reduces errors
- Improves program efficiency
📘 Computer Fundamentals and Programming with C
Module 1 – Part 3
Algorithms and Structured Programming
🎯 Learning Objectives
After studying this chapter, students will be able to:
- Define an algorithm.
- Explain the characteristics of a good algorithm.
- Write algorithms for simple problems.
- Understand the concept of structured programming.
- Explain the three basic programming constructs.
- Differentiate between an algorithm and a program.
- Appreciate the importance of structured programming in software development.
1. What is an Algorithm?
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.
Definition
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.
2. Why Do We Need an Algorithm?
Before writing a program, a programmer should first think about the solution. An algorithm provides a systematic approach for solving a problem.
Benefits
- Makes problem solving easier.
- Reduces programming errors.
- Saves development time.
- Improves program quality.
- Makes debugging simpler.
- Helps in planning program logic.
💡 Real-Life Example
Problem
Prepare a cup of tea.
Algorithm
- Start
- Take a saucepan.
- Pour water into the saucepan.
- Add tea leaves.
- Add sugar.
- Boil the mixture.
- Add milk.
- Boil again.
- Filter the tea.
- Serve.
- Stop.
This example shows that an algorithm is simply a sequence of logical steps.
3. Characteristics of a Good Algorithm
A good algorithm should have the following characteristics.
(i) Input
An algorithm should accept zero or more inputs.
Example
Input:
Two numbers
(ii) Output
It should produce at least one output.
Example
Output:
Sum of two numbers
(iii) Definiteness
Every step should be precise and unambiguous.
Correct
Read two numbers.
Incorrect
Read some values.
(iv) Finiteness
An algorithm must terminate after a finite number of steps.
(v) Effectiveness
Each step should be simple and executable.
4. Advantages of Algorithms
- Easy to understand.
- Independent of programming language.
- Helps in debugging.
- Improves logical thinking.
- Simplifies coding.
- Makes documentation easier.
5. Limitations of Algorithms
- Time-consuming for very large problems.
- Difficult to represent complex logic in simple steps.
- Cannot be executed directly by a computer.
6. Steps in Problem Solving
Problem
│
▼
Analysis
│
▼
Algorithm
│
▼
Flowchart
│
▼
Program
│
▼
Testing
│
▼
Output
7. Algorithm vs Program
| 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 |
8. Algorithm Examples
Example 1
Problem
Find the sum of two numbers.
Algorithm
- Start
- Read A and B.
- Calculate Sum = A + B.
- Display Sum.
- Stop.
Example 2
Problem
Find the largest of two numbers.
Algorithm
- Start
- Read A and B.
- If A > B, display A.
- Otherwise display B.
- Stop.
Example 3
Problem
Calculate the area of a rectangle.
Algorithm
- Start
- Read Length and Breadth.
- Area = Length × Breadth.
- Display Area.
- Stop.
9. Introduction to Structured Programming
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.
Definition
Structured programming is a programming approach in which a program is developed using well-defined control structures such as sequence, selection, and iteration.
10. Objectives of Structured Programming
- Improve readability.
- Reduce complexity.
- Simplify debugging.
- Encourage modular design.
- Improve maintainability.
11. Basic Programming Constructs
Structured programming is based on three fundamental control structures.
(i) Sequence
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);
(ii) Selection
Selection allows the program to choose one path from multiple alternatives based on a condition.
Examples
- if
- if-else
- switch
Example
if (marks >= 40)
printf("Pass");
else
printf("Fail");
(iii) Iteration
Iteration repeats a block of statements until a condition becomes false.
Examples
- while
- do-while
- for
Example
for(i = 1; i <= 5; i++)
{
printf("%d", i);
}
12. Advantages of Structured Programming
- Programs are easier to understand.
- Reduces programming errors.
- Simplifies testing.
- Easier maintenance.
- Encourages code reuse through functions.
- Improves software quality.
13. Structured vs Unstructured Programming
| 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 |
14. Applications of Structured Programming
Structured programming is widely used in:
- Banking Software
- Inventory Management Systems
- School Management Systems
- Hospital Information Systems
- Payroll Systems
- Scientific Applications
- Database Applications
📌 Key Points
- An algorithm is a sequence of logical steps for solving a problem.
- Every algorithm should have input, output, finiteness, definiteness, and effectiveness.
- Structured programming improves software quality by using clear control structures.
- The three basic programming constructs are Sequence, Selection, and Iteration.
📚 Summary
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.
📘 Computer Fundamentals and Programming with C
Module 1 – Part 4
Character Set, Tokens, Keywords, Constants, Variables, Data Types and Storage Classes
🎯 Learning Objectives
After studying this chapter, students will be able to:
- Explain the C character set.
- Define tokens and identify different types of tokens.
- Distinguish between keywords and identifiers.
- Explain constants and variables with examples.
- Describe different data types available in C.
- Understand the purpose and types of storage classes.
1. Character Set in C
Introduction
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.
Definition
A character set is the collection of letters, digits, symbols, and special characters that are recognized by the C compiler.
Categories of Character Set
(a) Alphabetic Characters
Uppercase letters
A B C ... Z
Lowercase letters
a b c ... z
(b) Numeric Digits
0 1 2 3 4 5 6 7 8 9
(c) Special Characters
+ - * / % = < > ! & | ^ ~
( ) { } [ ] ; : , . # ? _ ' " \
(d) White Space Characters
These improve readability but generally do not affect program execution.
- Space
- Tab
- New Line
- Carriage Return
Importance
The character set forms the foundation of every C program. Variables, operators, keywords, and statements are all created using these characters.
2. Tokens
Introduction
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.
Definition
A token is the smallest individual unit of a C program that carries meaning for the compiler.
Types of Tokens
| Token | Example |
|---|---|
| Keywords | int, if |
| Identifiers | total, marks |
| Constants | 10, 3.14 |
| String Literals | "Hello" |
| Operators | +, -, * |
| Special Symbols | ; , { } ( ) |
Example
int age = 20;
Tokens are:
int
age
=
20
;
3. Keywords
Introduction
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.
Definition
A keyword is a reserved word in C that has a predefined meaning and cannot be redefined by the programmer.
Common Keywords
| 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 |
4. Identifiers
An identifier is a name given by the programmer to variables, functions, arrays, or other program elements.
Valid Identifiers
total
studentName
_marks
salary2025
Invalid Identifiers
2marks
student name
float
Rules for Naming Identifiers
- Must begin with a letter or underscore.
- Cannot start with a digit.
- Cannot contain spaces.
- Cannot be a keyword.
-
C is case-sensitive (
Marksandmarksare different).
5. Constants
Introduction
A constant is a fixed value whose value remains unchanged throughout program execution.
Types of Constants
Integer Constant
10
250
-35
Floating Constant
3.14
25.75
0.001
Character Constant
'A'
'Z'
'9'
String Constant
"Computer"
"C Programming"
Symbolic Constant
#define PI 3.14159
6. Variables
Introduction
A variable is a named memory location used to store data during program execution. Unlike constants, variables can change their values whenever required.
Declaration
int age;
float salary;
char grade;
Initialization
int age = 20;
Variable Naming Rules
✔ Begin with a letter or underscore.
✔ Cannot contain spaces.
✔ Cannot use keywords.
✔ May contain digits after the first character.
7. Data Types
Introduction
A data type specifies the type of value that a variable can store and the amount of memory allocated to it.
Basic Data Types
| 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(); |
Derived Data Types
- Arrays
- Functions
- Pointers
User-defined Data Types
- Structure
- Union
- Enumeration
- typedef
8. Storage Classes
Introduction
Storage classes determine where a variable is stored, how long it exists, and where it can be accessed.
Types of Storage Classes
(a) auto
Default storage class for local variables.
auto int x;
(b) register
Requests storage in CPU registers for faster access.
register int count;
(c) static
Retains its value between function calls.
static int total;
(d) extern
Used to access global variables declared in another file.
extern int marks;
Comparison of Storage Classes
| 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 |
📘 Computer Fundamentals and Programming with C
Module 2: Operators, Expressions and Preprocessor Directives
Duration: 8 Lectures
📚 Module Contents
- Introduction to Operators
- Types of Operators
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Increment & Decrement Operators
- Conditional (Ternary) Operator
- Bitwise Operators
- Special Operators
- Operator Precedence and Associativity
- Expressions
- Type Conversion and Type Casting
- Input and Output Functions
- Comments in C
- Preprocessor Directives
- Macros
🎯 Learning Outcomes
After completing this module, students will be able to:
- Explain different types of operators in C.
- Evaluate arithmetic and logical expressions.
- Understand operator precedence and associativity.
- Use input/output functions effectively.
- Apply type conversion and type casting.
- Use preprocessor directives and macros.
1. Introduction to Operators
What is an Operator?
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.
Definition
An operator is a symbol that instructs the compiler to perform a specific mathematical, logical, relational, or bitwise operation on one or more operands.
Example
int a = 10, b = 5;
int sum = a + b;
Here,
-
aandbare operands. -
+is the operator.
Output:
sum = 15
2. Classification of Operators
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 |
3. Arithmetic Operators
Arithmetic operators perform mathematical calculations.
| Operator | Meaning | Example |
|---|---|---|
| + | Addition | a+b |
| - | Subtraction | a-b |
| * | Multiplication | a*b |
| / | Division | a/b |
| % | Modulus | a%b |
Example
#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;
}
Output
Addition = 26
Subtraction = 14
Multiplication = 120
Division = 3
Remainder = 2
4. Relational Operators
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 |
Example
int a=10,b=20;
printf("%d",a<b);
Output
1
5. Logical Operators
Logical operators are used to combine multiple conditions.
| Operator | Meaning |
|---|---|
| && | Logical AND |
| || | Logical OR |
| ! | Logical NOT |
Example
int age=20;
if(age>=18 && age<=60)
printf("Eligible");
Output
Eligible
6. Assignment Operators
Assignment operators assign values to variables.
| Operator | Meaning |
|---|---|
| = | Assignment |
| += | Add and assign |
| -= | Subtract and assign |
| *= | Multiply and assign |
| /= | Divide and assign |
| %= | Modulus and assign |
Example
int x=10;
x+=5;
Result
x=15
7. Increment and Decrement Operators
These operators change the value of a variable by one.
Increment (++)
int x=5;
x++;
Output
6
Decrement (--)
int x=5;
x--;
Output
4
Prefix vs Postfix
| Prefix | Postfix |
|---|---|
| ++x | x++ |
| Value changes first | Value changes later |
8. Conditional (Ternary) Operator
The conditional operator is a compact alternative to the if-else statement.
Syntax
condition ? expression1 : expression2;
Example
int a=20,b=10;
int max=(a>b)?a:b;
printf("%d",max);
Output
20
9. Bitwise Operators
Bitwise operators perform operations directly on binary bits.
| Operator | Meaning |
|---|---|
| & | Bitwise AND |
| | | Bitwise OR |
| ^ | XOR |
| ~ | NOT |
| << | Left Shift |
| >> | Right Shift |
Example
int a=5,b=3;
printf("%d",a&b);
Output
1
10. Special Operators
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
11. Operator Precedence
When multiple operators appear in an expression, C follows precedence rules.
Example
10+5*2
Multiplication is performed first.
Result
20
12. Associativity
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.
📌 Key Points
- Operators perform operations on operands.
- Arithmetic operators are used for calculations.
- Relational operators compare values.
- Logical operators combine conditions.
- Assignment operators store values.
- Increment and decrement operators modify values by one.
-
The conditional operator is a shorthand for simple
if-elsestatements. - Bitwise operators work on binary representations of numbers.
- Precedence and associativity determine the order of evaluation.
📝 Summary
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.
📘 Computer Fundamentals and Programming with C
Module 2 – Part 2
Expressions, Type Conversion, Input/Output, Preprocessor Directives and Macros
📚 Contents
- Expressions in C
- Types of Expressions
- Type Conversion
- Type Casting
- Input Functions
- Output Functions
- Escape Sequences
- Comments
- Preprocessor Directives
- Macros
🎯 Learning Outcomes
After studying this chapter, students will be able to:
- Understand expressions and their evaluation.
- Explain automatic type conversion.
- Perform explicit type casting.
- Use input and output functions correctly.
- Apply escape sequences in output.
- Explain preprocessor directives and macros.
1. Expressions in C
Introduction
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.
Definition
An expression is a valid combination of variables, constants, operators, and function calls that produces a single value when evaluated.
Example
int a = 10;
int b = 20;
int c = a + b;
Here,
a + b
is an expression.
Result
30
Types of Expressions
(a) Arithmetic Expression
Performs mathematical calculations.
Example
x + y
a * b
(b) Relational Expression
Compares two values.
Example
a > b
Result
True or False
(c) Logical Expression
Uses logical operators.
Example
(a>b)&&(b>c)
(d) Assignment Expression
Assigns value.
Example
x = 10
(e) Conditional Expression
Uses the ternary operator.
Example
(a>b)?a:b
2. Type Conversion
Introduction
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.
Example
int a=10;
float b=5.5;
float c=a+b;
The integer value is automatically converted into float.
Output
15.5
Rules of Automatic Type Conversion
char
↓
int
↓
float
↓
double
Smaller data types are promoted to larger data types automatically.
Advantages
- Prevents data loss.
- Makes calculations easier.
- Performed automatically by the compiler.
3. Type Casting
Introduction
Sometimes the programmer wants to convert a value into another data type manually.
This is called Type Casting.
Syntax
(data_type) expression;
Example
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 vs Type Casting
| Type Conversion | Type Casting |
|---|---|
| Automatic | Manual |
| Compiler performs conversion | Programmer performs conversion |
| No syntax required | Uses (data_type) |
| Safe conversion | Depends on programmer |
4. Input Functions
scanf()
The scanf() function reads data from the keyboard.
Syntax
scanf("format",&variable);
Example
#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
Common Format Specifiers
| Data Type | Format Specifier |
|---|---|
| int | %d |
| float | %f |
| char | %c |
| double | %lf |
| string | %s |
5. Output Functions
printf()
The printf() function displays information on the screen.
Syntax
printf("format",variable);
Example
int marks=90;
printf("Marks=%d",marks);
Output
Marks=90
Advantages
- Displays formatted output.
- Supports multiple variables.
- Supports escape sequences.
6. Escape Sequences
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 |
Example
printf("Hello\nWorld");
Output
Hello
World
Example
printf("A\tB\tC");
Output
A B C
7. Comments
Comments improve readability by explaining program logic. They are ignored by the compiler.
Single Line Comment
// This is a comment
Multi-line Comment
/*
This is
a comment
*/
Advantages
- Makes programs easier to understand.
- Helps during debugging.
- Improves documentation.
8. Preprocessor Directives
Introduction
Preprocessor directives are instructions processed before compilation.
They always begin with the # symbol.
Common Directives
| Directive | Purpose |
|---|---|
| #include | Includes header file |
| #define | Defines constant |
| #ifdef | Conditional compilation |
| #ifndef | Conditional compilation |
| #undef | Removes macro |
Example
#include<stdio.h>
Includes the Standard Input Output library.
Example
#define PI 3.14159
Defines a symbolic constant.
Advantages
- Reduces repeated code.
- Improves readability.
- Simplifies maintenance.
9. Macros
Introduction
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.
Syntax
#define name replacement
Example
#define PI 3.14159
float area = PI * r * r;
Function-like Macro
#define SQUARE(x) ((x)*(x))
Usage
printf("%d",SQUARE(5));
Output
25
Advantages of Macros
- Faster execution.
- No function call overhead.
- Easy modification.
- Improves readability.
📌 Key Points
- Expressions evaluate to a single value.
- Type conversion is automatic.
- Type casting is performed manually.
-
scanf()is used for input. -
printf()is used for output. - Escape sequences control text formatting.
- Comments improve readability.
- Preprocessor directives are executed before compilation.
- Macros simplify repetitive tasks.
📚 Module 2 Summary
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.
📘 Computer Fundamentals and Programming with C
Module 3: Decision Making and Loop Control
Duration: 7 Lectures
📚 Module Contents
- Decision Making in C
-
Simple
ifStatement -
if-elseStatement -
Nested
if -
else-ifLadder -
switchStatement - Conditional (Ternary) Operator
-
whileLoop -
do-whileLoop -
forLoop - Nested Loops
-
breakStatement -
continueStatement -
gotoStatement - Solved Programs
- University Questions
- MCQs
🎯 Learning Outcomes
After completing this module, students will be able to:
- Make decisions in C programs using conditional statements.
- Select appropriate looping statements.
- Develop efficient iterative solutions.
- Differentiate between various looping constructs.
- Control the flow of execution using jump statements.
1. Introduction to Decision Making
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.
2. The if Statement
Definition
The if statement executes a block of code only if the specified condition is true.
Syntax
if(condition)
{
// Statements
}
Flowchart
┌────────────┐
│ Condition? │
└─────┬──────┘
│
True ───┘
│
▼
Execute Statements
│
▼
End
Example
#include<stdio.h>
int main()
{
int marks = 80;
if(marks >= 40)
{
printf("Pass");
}
return 0;
}
Output
Pass
3. The if-else Statement
When there are two possible outcomes, the if-else statement is used.
Syntax
if(condition)
{
// True block
}
else
{
// False block
}
Example
#include<stdio.h>
int main()
{
int age = 16;
if(age >= 18)
printf("Eligible to Vote");
else
printf("Not Eligible");
return 0;
}
Output
Not Eligible
4. Nested if Statement
A nested if means placing one if statement inside another.
Example
#include<stdio.h>
int main()
{
int age = 22;
char citizen = 'Y';
if(age >= 18)
{
if(citizen == 'Y')
printf("Eligible to Vote");
}
return 0;
}
5. else-if Ladder
The else-if ladder is used when multiple conditions need to be tested one after another.
Syntax
if(condition1)
{
}
else if(condition2)
{
}
else if(condition3)
{
}
else
{
}
Example: Grade Calculator
#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;
}
Output
Grade A
6. switch Statement
The switch statement is used when one variable needs to be compared against multiple fixed values.
Syntax
switch(expression)
{
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
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;
}
Output
Wednesday
7. Difference Between if-else and switch
if-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 |
💡 Remember
-
Use
if-elsewhen conditions involve comparisons like>,<,>=, or logical operators. -
Use
switchwhen checking a variable against a list of constant values.
📌 Key Points
-
ifexecutes a block only when a condition is true. -
if-elsechooses between two alternatives. -
Nested
ifallows one decision inside another. -
else-ifladder handles multiple conditions. -
switchis useful for menu-driven programs.
📚 Summary
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.
📘 Computer Fundamentals and Programming with C
Module 3 – Part 2
Loop Control Statements in C
Duration: 7 Lectures
📚 Contents
- Introduction to Loops
- while Loop
- do-while Loop
- for Loop
- Nested Loops
- break Statement
- continue Statement
- goto Statement
- Comparison of Loops
- Solved Examples
🎯 Learning Outcomes
After completing this chapter, students will be able to:
- Explain the need for loops.
-
Write programs using
while,do-while, andforloops. - Understand nested loops.
-
Use
break,continue, andgotostatements effectively. - Compare different loop structures.
1. Introduction to Loop Control
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.
Real-Life Example
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.
Definition
A loop is a control structure that repeatedly executes a block of statements as long as a specified condition is true.
Advantages of Loops
- Reduces code repetition.
- Saves programming time.
- Improves readability.
- Simplifies maintenance.
- Reduces program size.
Types of Loops in C
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 |
2. while Loop
Definition
The while loop executes a block of statements repeatedly as long as the given condition remains true.
Syntax
while(condition)
{
statements;
}
Flowchart
┌────────────┐
│ Condition? │
└─────┬──────┘
│True
▼
Execute Block
│
└───────────┐
│
False ▼
End
Example 1
Display numbers from 1 to 5.
#include<stdio.h>
int main()
{
int i=1;
while(i<=5)
{
printf("%d ",i);
i++;
}
return 0;
}
Output
1 2 3 4 5
Working
| i | Condition | Output |
|---|---|---|
| 1 | True | 1 |
| 2 | True | 2 |
| 3 | True | 3 |
| 4 | True | 4 |
| 5 | True | 5 |
| 6 | False | Stop |
Advantages
✔ Simple
✔ Suitable when the number of repetitions is unknown.
✔ Easy to understand.
Limitations
❌ Initialization must be done separately.
❌ Increment or decrement must be written manually.
3. do-while Loop
Definition
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.
Syntax
do
{
statements;
}while(condition);
Flowchart
Execute Block
│
▼
Condition?
│ │
True False
│ │
└──────┘
End
Example
#include<stdio.h>
int main()
{
int i=1;
do
{
printf("%d ",i);
i++;
}while(i<=5);
return 0;
}
Output
1 2 3 4 5
Important Difference
int i=10;
do
{
printf("%d",i);
}while(i<5);
Output
10
Although the condition is false, the statement executes once.
4. for Loop
Definition
The for loop is mainly used when the number of repetitions is known in advance.
Syntax
for(initialization;condition;increment)
{
statements;
}
Flowchart
Initialization
│
▼
Condition?
│ │
True False
│ │
▼ End
Execute Block
│
Increment
│
──────┘
Example
#include<stdio.h>
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("%d ",i);
}
return 0;
}
Output
1 2 3 4 5
Advantages
✔ Compact
✔ Easy to write
✔ Suitable for counting loops
✔ Initialization, condition and update remain together.
5. Comparison of Loops
| 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 |
6. Nested Loop
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
* * *
* * *
* * *
7. break Statement
The break statement immediately terminates the nearest loop or switch statement.
Example
#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
8. continue Statement
The continue statement skips the remaining statements in the current iteration and moves to the next iteration.
Example
#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
9. goto Statement
The goto statement transfers program control directly to a labeled statement.
Syntax
goto label;
/* statements */
label:
statement;
Example
#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
Advantages of goto
- Useful in rare situations such as exiting deeply nested loops.
- Can simplify cleanup code in some low-level programs.
Disadvantages of goto
- Makes programs difficult to understand.
- Reduces readability.
- Makes debugging difficult.
- Should generally be avoided in structured programming.
📘 Computer Fundamentals and Programming with C
Module 4: Functions and Arrays
Theory: 10 Lectures
(Prepared for WBSU BCA Semester-I NEP Students)
🎯 Learning Outcomes
After completing this module, students will be able to:
- Understand the concept and importance of functions in C.
- Differentiate between library functions and user-defined functions.
- Declare, define, and call functions.
- Explain parameter passing techniques.
- Understand recursion and recursive functions.
- Create and manipulate one-dimensional and two-dimensional arrays.
- Work with character arrays (strings) and string handling functions.
📚 Module Contents
Unit-1: Functions
- Introduction to Functions
- Advantages of Functions
- Types of Functions
- Function Declaration
- Function Definition
- Function Call
- Function Prototype
- Categories of Functions
- Call by Value
- Call by Reference
- Recursive Functions
Unit-2: Arrays
- Introduction to Arrays
- One-Dimensional Array
- Two-Dimensional Array
- Multidimensional Arrays
- Character Arrays (Strings)
- String Handling Functions
PART-1
FUNCTIONS
1. Introduction to Functions
What is a Function?
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.
Definition
A function is a named block of statements that performs a specific operation and can be called whenever required during program execution.
Real-Life Analogy
Think of a calculator.
Each button performs a specific task.
- Addition button → Add numbers
- Subtraction button → Subtract numbers
- Multiplication button → Multiply numbers
Similarly, every function performs one specific task.
Why Do We Need Functions?
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.
Advantages of Functions
✅ Reduces program size
✅ Avoids code duplication
✅ Improves readability
✅ Easier debugging
✅ Easy maintenance
✅ Code reusability
✅ Supports teamwork
Structure of a Function
Every function consists of three parts.
Function Declaration
↓
Function Definition
↓
Function Call
Example
#include<stdio.h>
void display();
int main()
{
display();
return 0;
}
void display()
{
printf("Welcome to C Programming");
}
Output
Welcome to C Programming
Components of the Above Program
Function Declaration
void display();
Tells the compiler that a function named display() exists.
Function Call
display();
Transfers program control to the function.
Function Definition
void display()
{
printf("Welcome to C Programming");
}
Contains the actual statements.
Types of Functions
There are two types of functions.
1. Library 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 |
2. User-defined Functions
Functions created by the programmer are called user-defined functions.
Example
void welcome()
{
printf("Welcome Students");
}
Function Prototype
A function prototype informs the compiler about
- Function name
- Return type
- Parameters
Example
int sum(int,int);
Function Definition
General Syntax
return_type function_name(parameters)
{
statements;
return value;
}
Example
int add(int a,int b)
{
return a+b;
}
Function Call
A function call transfers control to the function.
Example
result=add(10,20);
Categories of Functions
Functions are classified into four categories.
Category 1
No Arguments and No Return Value
void display()
{
printf("Hello");
}
Call
display();
Category 2
Arguments but No Return Value
void sum(int a,int b)
{
printf("%d",a+b);
}
Call
sum(10,20);
Category 3
No Arguments but Return Value
int number()
{
return 50;
}
Call
x=number();
Category 4
Arguments and Return Value
int sum(int a,int b)
{
return a+b;
}
Call
result=sum(10,20);
Call by Value
Definition
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
Advantages
✔ Safe
✔ Original data remains unchanged
Disadvantages
✖ Extra memory is required
✖ Large data copying reduces efficiency
Call by Reference
Definition
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
Difference Between Call by Value and Call by Reference
| 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 |
Recursive Function
Introduction
A function that calls itself is called a recursive function.
Example
void display()
{
printf("Hello");
display();
}
Types of Recursion
Direct Recursion
A function calls itself directly.
A()
↓
A()
Indirect Recursion
Two or more functions call each other.
A()
↓
B()
↓
A()
Advantages of Recursion
✔ Simple code
✔ Elegant solution
✔ Useful for trees and graphs
✔ Useful for divide-and-conquer algorithms
Disadvantages
✖ High memory usage
✖ Slower execution
✖ Risk of stack overflow
Applications of Recursion
- Factorial
- Fibonacci Series
- Tower of Hanoi
- Binary Search
- Tree Traversal
- Quick Sort
- Merge Sort
📘 Computer Fundamentals and Programming with C
Module 4 – Part 2
Arrays and Strings in C
Theory: 10 Lectures
🎯 Learning Outcomes
After completing this chapter, students will be able to:
- Understand the concept of arrays.
- Declare and initialize one-dimensional and two-dimensional arrays.
- Perform operations on arrays.
- Work with character arrays (strings).
- Use built-in string handling functions.
- Develop simple programs using arrays and strings.
1. Introduction to Arrays
What is an Array?
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.
Definition
An array is a collection of similar data items stored in consecutive memory locations and accessed using a common name with an index number.
Why Do We Need Arrays?
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.
Advantages of Arrays
✔ Store multiple values using one variable.
✔ Easy data processing.
✔ Faster access through indexing.
✔ Simplifies searching and sorting.
✔ Reduces code repetition.
Limitations of Arrays
❌ Can store only one data type.
❌ Fixed size after declaration.
❌ Insertion and deletion are relatively expensive.
Memory Representation
marks[5]
+-----+-----+-----+-----+-----+
| 80 | 75 | 90 | 85 | 95 |
+-----+-----+-----+-----+-----+
0 1 2 3 4The first element always has index 0.
2. One-Dimensional Array (1D Array)
A one-dimensional array stores elements in a single row.
Declaration
data_type array_name[size];Example
int marks[5];
Initialization
int marks[5]={80,75,90,85,95};or
int marks[]={80,75,90,85,95};
Accessing Array Elements
printf("%d",marks[2]);Output
90
Program: Display Array Elements
#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;
}Output
10 20 30 40 50
3. Reading Values into an Array
#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;
}
Applications of 1D Arrays
- Store student marks
- Employee salaries
- Monthly sales
- Temperatures
- Exam scores
4. Two-Dimensional Array (2D Array)
A two-dimensional array stores data in rows and columns, similar to a table or matrix.
Declaration
data_type array_name[row][column];Example
int marks[3][4];
Initialization
int a[2][3]={
{1,2,3},
{4,5,6}
};
Memory Representation
Column
0 1 2
Row0 10 20 30
Row1 40 50 60
Program
#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;
}Output
10 20
30 40
Applications of 2D Arrays
- Matrix operations
- Student result tables
- Chess board representation
- Image processing
- Game development
5. Multidimensional Arrays
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.
6. Character Arrays (Strings)
A string is a sequence of characters terminated by the null character (
'\0').Example
char name[20];
Initialization
char name[]="Computer";Memory Representation
C o m p u t e r \0
Reading a String
char name[20];
scanf("%s",name);
Displaying a String
printf("%s",name);
Program
#include<stdio.h>
int main()
{
char name[30];
printf("Enter Name : ");
scanf("%s",name);
printf("Welcome %s",name);
return 0;
}
Output
Enter Name : Rahul
Welcome Rahul
7. String Handling Functions
The
string.hheader file provides several built-in functions for string manipulation.
(a) strlen()
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
(b) strcpy()
Copies one string to another.
Example
char s1[]="ABC";
char s2[20];
strcpy(s2,s1);
(c) strcat()
Concatenates two strings.
Example
char s1[]="Good";
char s2[]="Morning";
strcat(s1,s2);Output
GoodMorning
(d) strcmp()
Compares two strings.
Example
strcmp("ABC","ABC");Output
0A return value of:
-
0→ Strings are equal. - Positive value → First string is greater.
- Negative value → Second string is greater.
(e) strrev()
Reverses a string (available in some compilers, not part of the ISO C standard).
Example
strrev(name);
(f) strlwr()
Converts a string to lowercase (compiler-specific).
(g) strupr()
Converts a string to uppercase (compiler-specific).
Commonly Used String Functions
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.
Difference Between Character Array and String
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
Advantages of Arrays
- Easy storage of large amounts of data.
- Fast element access using indices.
- Simplifies algorithms such as sorting and searching.
- Reduces the number of variables required.
Disadvantages of Arrays
- Fixed size.
- Cannot store different data types together.
- Memory may be wasted if the declared size is larger than required.
📌 Key Points
- Arrays store elements of the same data type.
- Indexing starts from 0.
- A 1D array stores data in a single list.
- A 2D array stores data in rows and columns.
- Strings are character arrays ending with a null character.
-
The
<string.h>library provides functions for string manipulation.
📚 Module 4 Summary
This module introduced functions and arrays, two fundamental concepts in C programming. Functions help organize code into reusable units, while arrays enable efficient storage and processing of multiple values. The module also covered strings as character arrays and the use of standard string handling functions from thestring.hlibrary.
📘 Computer Fundamentals and Programming with C
Module 5: Pointers, Structures, Unions, File Handling and Dynamic Memory Allocation
(Theory: 15 Lectures)
(Prepared in original language for WBSU BCA NEP Semester-I Students)
🎯 Learning Outcomes
After completing this module, students will be able to:
- Understand pointers and their applications.
- Perform pointer arithmetic.
- Pass pointers to functions.
- Create and use structures and unions.
- Perform dynamic memory allocation.
- Read and write files using C.
- Develop modular and memory-efficient programs.
📚 Module Contents
Unit 1: Pointers
- Introduction to Pointers
- Pointer Declaration
- Pointer Initialization
- Pointer Arithmetic
- Pointer and Arrays
- Pointer to Function
- Passing Pointer to Function
Unit 2: Structures & Unions
- Structure
- Nested Structure
- Array of Structures
- Union
- Difference between Structure and Union
Unit 3: Dynamic Memory Allocation
- malloc()
- calloc()
- realloc()
- free()
Unit 4: File Handling
- File Concepts
- fopen()
- fclose()
- fprintf()
- fscanf()
- fgets()
- fputs()
- EOF
PART-1
POINTERS
1. Introduction to Pointers
What is a Pointer?
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.
Definition
A pointer is a variable that stores the memory address of another variable.
Why Do We Need Pointers?
Pointers are useful because they:
- Access memory directly.
- Reduce memory usage.
- Pass arguments efficiently to functions.
- Support dynamic memory allocation.
- Build advanced data structures such as linked lists, stacks, queues, trees, and graphs.
Memory Representation
Variable Address
a = 10 2000
Pointer p 3000
│
▼
Address 2000
Here,
- Variable a stores 10.
- Pointer p stores the address of a.
Pointer Declaration
Syntax
data_type *pointer_name;
Examples
int *p;
float *q;
char *ch;
Pointer Initialization
int a=10;
int *p;
p=&a;
Here
&a
means address of variable a.
Example Program
#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;
}
Output
Value = 10
Address = 6422296
Pointer = 6422296
(Address varies from computer to computer.)
Dereferencing Operator
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
Address Operator
The symbol & is called the address operator.
Example
printf("%p",&a);
Output
Address of a
Pointer Example
#include<stdio.h>
int main()
{
int x=100;
int *ptr=&x;
printf("%d\n",x);
printf("%d\n",*ptr);
return 0;
}
Output
100
100
Pointer Arithmetic
Pointers can perform arithmetic operations.
Allowed operations are:
- Increment (++)
- Decrement (--)
- Addition (+)
- Subtraction (-)
Example
int a[5]={10,20,30,40,50};
int *p=a;
p++;
Now pointer points to
20
Memory Representation
Address
1000 → 10
1004 → 20
1008 → 30
1012 → 40
1016 → 50
Each integer occupies 4 bytes (commonly on modern systems).
Pointer and Array
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
Passing Pointer to Function
Example
#include<stdio.h>
void change(int *x)
{
*x=100;
}
int main()
{
int a=10;
change(&a);
printf("%d",a);
return 0;
}
Output
100
Advantages of Pointers
✔ Faster execution
✔ Efficient memory usage
✔ Dynamic memory allocation
✔ Supports data structures
✔ Enables call by reference
Disadvantages
❌ Difficult to understand
❌ Risk of memory leaks
❌ Can cause segmentation faults if misused
Applications of Pointers
- Dynamic memory allocation
- File handling
- Linked lists
- Trees
- Graphs
- Function arguments
- Operating systems
- Compiler design
📌 Key Points
- A pointer stores the address of another variable.
-
&returns the address of a variable. -
*accesses the value stored at the pointed address. - Arrays and pointers are closely related.
- Pointers enable efficient memory management and advanced programming techniques.
📘 Computer Fundamentals and Programming with C
Module 5 – Part 2
Structures, Unions, Dynamic Memory Allocation and File Handling
Theory: 15 Lectures
📚 Contents
- Structure
- Nested Structure
- Array of Structures
- Union
- Difference Between Structure and Union
- Dynamic Memory Allocation
- malloc()
- calloc()
- realloc()
- free()
- File Handling
- File Opening Modes
- File Functions
- EOF
🎯 Learning Outcomes
After studying this chapter, students will be able to:
- Create and use structures and unions.
- Allocate memory dynamically.
- Read and write files in C.
- Differentiate between structures and unions.
- Develop applications using file handling.
PART-1
STRUCTURE
1. Introduction to Structure
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.
Definition
A structure is a user-defined data type that groups related variables of different data types under one name.
Real-Life Example
A student's record contains:
- Name
- Roll Number
- Age
- Percentage
All these details can be stored in one structure.
Syntax
struct Student
{
int roll;
char name[30];
float marks;
};
Creating Structure Variables
struct Student s1;
Accessing Members
The dot (.) operator is used.
Example
s1.roll=101;
strcpy(s1.name,"Rahul");
s1.marks=88.5;
Complete Program
#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;
}
Output
101
Amit
92.50
Advantages of Structures
✅ Groups different data types.
✅ Improves program organization.
✅ Easy data management.
✅ Supports database-like records.
Applications
- Student Information System
- Employee Database
- Library Management
- Hospital Management
- Banking Software
2. Nested Structure
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;
};
Applications
- Employee records
- Address management
- Date and time storage
3. Array of Structures
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;
PART-2
UNION
What is a Union?
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.
Definition
A union is a user-defined data type in which all members share the same memory location.
Syntax
union Data
{
int i;
float f;
char name[20];
};
Example
union Data d;
d.i=100;
Structure vs Union
| 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 |
Advantages of Union
✔ Saves memory
✔ Efficient for embedded systems
✔ Useful in device drivers
PART-3
Dynamic Memory Allocation
Introduction
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.
Advantages
- Memory allocated when required.
- Better memory utilization.
- Flexible programs.
- Supports dynamic data structures.
Dynamic Memory Functions
| Function | Purpose |
|---|---|
| malloc() | Allocates memory |
| calloc() | Allocates and initializes memory |
| realloc() | Changes memory size |
| free() | Releases memory |
malloc()
Allocates memory but does not initialize it.
Syntax
pointer=(datatype*)malloc(size);
Example
int *p;
p=(int*)malloc(5*sizeof(int));
calloc()
Allocates memory and initializes all bytes to zero.
Syntax
pointer=(datatype*)calloc(number,size);
Example
int *p;
p=(int*)calloc(5,sizeof(int));
realloc()
Changes the size of previously allocated memory.
Syntax
pointer=realloc(pointer,new_size);
Example
p=realloc(p,10*sizeof(int));
free()
Releases allocated memory.
Syntax
free(pointer);
Example
free(p);
Comparison
| malloc() | calloc() |
|---|---|
| No initialization | Initializes with zero |
| One argument | Two arguments |
| Faster | Slightly slower |
PART-4
File Handling
Introduction
A program stores data in memory temporarily.
When the program ends, the data is lost.
To store data permanently, files are used.
Definition
File handling is the process of storing, reading, and modifying data in files using C programs.
Steps in File Handling
Open File
↓
Read/Write
↓
Close File
File Pointer
FILE *fp;
fopen()
Opens a file.
Syntax
fp=fopen("student.txt","r");
File Modes
| Mode | Meaning |
|---|---|
| r | Read |
| w | Write |
| a | Append |
| r+ | Read & Write |
| w+ | Read & Write (Overwrite) |
| a+ | Read & Append |
fclose()
Closes the file.
Syntax
fclose(fp);
fprintf()
Writes formatted data into a file.
Example
fprintf(fp,"%d",100);
fscanf()
Reads formatted data.
Example
fscanf(fp,"%d",&x);
fputs()
Writes a string.
Example
fputs("Welcome",fp);
fgets()
Reads a string.
Example
fgets(name,20,fp);
EOF
EOF means End Of File.
It indicates that there is no more data available to read.
Example
while((ch=fgetc(fp))!=EOF)
Advantages of File Handling
✔ Permanent storage
✔ Large data storage
✔ Easy retrieval
✔ Data sharing
✔ Backup facility
Applications
- Student Database
- Banking System
- Payroll System
- Library Management
- Inventory Management
- Hospital Records
📌 Key Points
- Structures store different data types together.
- Unions share a common memory location.
- Dynamic memory is allocated during execution.
-
malloc(),calloc(),realloc(), andfree()manage dynamic memory. - File handling enables permanent storage of data.
-
Always close files using
fclose()after use.
📚 Module 5 Summary
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.
No comments:
Post a Comment