0% found this document useful (0 votes)
8 views74 pages

C Programing Compiled Note

The document outlines the syllabus for a Computer Concept and Programming course (CSIT 104) for first-semester B.Sc. CSIT students, focusing on C programming fundamentals and problem-solving techniques. It covers computer fundamentals, components, architecture, memory types, programming methodologies, and the C language structure, including data types, operators, and common programming errors. The course aims to equip students with essential programming skills and knowledge to effectively solve problems using C.

Uploaded by

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

C Programing Compiled Note

The document outlines the syllabus for a Computer Concept and Programming course (CSIT 104) for first-semester B.Sc. CSIT students, focusing on C programming fundamentals and problem-solving techniques. It covers computer fundamentals, components, architecture, memory types, programming methodologies, and the C language structure, including data types, operators, and common programming errors. The course aims to equip students with essential programming skills and knowledge to effectively solve problems using C.

Uploaded by

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

[Link].

CSIT – First Semester(C


PROGRAMING)
Course: Computer Concept and Programming (CSIT 104)
Nature: Theory (3 Hr) + Practical (3 Hr)
Credit Hours: 3
Full Marks: Ext(60+20) + Int(40)
Pass Marks: Ext(16+8) + Int(16)

Course Objectives
After completing this course, students will be able to:

1. Understand algorithms, fundamentals of C programming, and problem-solving


techniques.
2. Implement different programming constructs and break problems into functions.
3. Use data structures such as arrays and structures for programming solutions.
4. Define and use pointers in simple applications.
5. Understand graphics programming in simple applications.
Unit-1 Computer Fundamental and Programming Methodology

1. Introduction to Computers

A computer is an electronic device capable of performing a variety of tasks, from simple


calculations to complex problem-solving, with extremely high speed and accuracy. It is designed
to accept input, process it according to instructions, store data temporarily or permanently, and
produce output that is meaningful to the user. Computers are essential tools in modern life, used
in business, education, healthcare, engineering, entertainment, and communication.

The main characteristics of a computer include:

 Speed: Computers can process data and perform calculations much faster than humans.
 Accuracy: Computers produce precise results if the instructions are correct. Errors
usually occur due to incorrect input or programming mistakes.
 Automation: Once programmed, computers can perform tasks automatically without
human intervention.
 Storage: Computers can store vast amounts of data and retrieve it whenever needed.
 Communication: Computers can communicate with other systems and networks,
allowing for resource sharing and information transfer.

In simple terms, a computer is an intelligent machine that transforms data into information,
helping humans perform tasks efficiently. It is not only a calculating device but also a tool for
problem-solving in real-life applications.

2. Components of a Personal Computer

A personal computer (PC) is composed of several interdependent components that work together
to perform computing tasks. These include:

Input Devices: Input devices allow users to provide data and commands to the computer.
Examples include keyboards for typing, mice for selecting options, scanners for digitizing
documents, and joysticks for gaming. The quality and speed of input devices directly affect user
experience and productivity.

Output Devices: Output devices display or produce results after processing. Monitors show
visual information, printers produce hard copies of documents, and speakers provide audio
output. Output devices make information understandable and usable for humans.

Central Processing Unit (CPU): The CPU is considered the brain of the computer. It executes
instructions from programs, performs arithmetic and logical operations, and controls the
functioning of other components. The CPU consists of:
 Arithmetic Logic Unit (ALU): Handles calculations and decision-making based on
logical comparisons.
 Control Unit (CU): Directs the flow of data and instructions between CPU components,
memory, and input/output devices.

Memory and Storage Devices: Memory stores instructions and data for immediate use, while
storage provides long-term data retention. Primary memory includes RAM, which is temporary
and fast, and ROM, which is permanent. Secondary storage includes hard drives, SSDs, and
optical disks, which retain data even when the power is off.

Together, these components enable the computer to function as a complete system capable of
performing diverse tasks.

3. Computer Architecture

Computer architecture refers to the design and structure of a computer system, which determines
how hardware components interact and process data. The basic architecture of a computer
consists of three main parts: Input → Process → Output.

 Input Stage: Receives data from input devices.


 Processing Stage: The CPU executes instructions and processes data using ALU and
CU.
 .Output Stage: Produces the final results using output devices.
The CPU communicates with memory and other components through a bus system, which
consists of:

 Data Bus: Transfers data between CPU, memory, and peripherals.


 Address Bus: Specifies the memory locations where data is stored or retrieved.
 Control Bus: Sends control signals to coordinate operations of all components.
A well-designed architecture ensures efficiency, speed, and reliability in processing data and
running programs.

4. Memory Types

Memory is a critical component of a computer, responsible for storing both data and instructions.
Memory types can be divided into:

 Primary Memory: Directly accessible by the CPU.


o RAM (Random Access Memory): Volatile memory used to store data
temporarily while programs are running. It allows both reading and writing.
o ROM (Read-Only Memory): Non-volatile memory that contains permanent
instructions for booting and basic operations.
 Secondary Memory: Used for long-term storage, such as hard drives, solid-state drives
(SSD), and optical media. This memory is slower than RAM but provides large storage
capacity.
 Cache Memory: High-speed memory located between the CPU and RAM, used to store
frequently accessed data. Cache improves the overall speed of processing by reducing the
need to access slower main memory frequently.

The combination of these memory types ensures that the computer can work efficiently,
balancing speed, cost, and storage capacity.

5. Memory Hierarchy

Memory hierarchy is a structured arrangement of storage types based on speed and cost. The
hierarchy starts from the fastest but smallest memory to the slowest but largest memory:

1. Registers: Ultra-fast storage within the CPU for temporary data and instructions.
2. Cache Memory: Stores frequently used data to improve processing speed.
3. Main Memory (RAM): Stores currently running programs and data.
4. Secondary Storage: Hard disks, SSDs, and other permanent storage devices.

This hierarchical structure ensures that the most frequently needed data is available quickly,
while less critical data is stored in slower, larger, and cheaper memory.
6. Computer Peripherals

Peripherals are external devices connected to a computer to expand its capabilities. They include:

 Input Peripherals: Keyboards, mice, scanners, and microphones.


 Output Peripherals: Printers, monitors, and speakers.
 Storage Peripherals: External hard drives, USB drives, and memory cards.

Peripherals allow users to interact with the computer, improve its performance, and increase its
usability for various tasks.

7. Input and Output Devices

Input devices allow data to be entered into the computer, while output devices deliver processed
information. Some devices, like touchscreens, serve as both input and output devices. Proper use
of these devices improves efficiency and user experience.
8. Basics of Computer Networking

Networking connects multiple computers to share resources and information. Networks can be
classified as:

 Local Area Network (LAN): Covers a small area like a room or office.
 Metropolitan Area Network (MAN): Covers a city or town.
 Wide Area Network (WAN): Covers large geographic areas, such as countries or
continents.

The Internet is the largest WAN, connecting millions of devices globally. Networking enables
communication, resource sharing, and access to remote information, making computers more
powerful and collaborative.

9. Computer Programs

A computer program is a set of instructions that directs the computer to perform specific tasks.
Programs can be classified as:

 System Software: Manages computer hardware and provides an environment for running
applications (e.g., operating systems).
 Application Software: Allows users to perform specific tasks (e.g., word processors,
browsers, games).

Writing efficient programs is essential to ensure that the computer performs tasks accurately and
quickly.

10. Steps for Program Development

Program development involves a series of systematic steps:

1. Problem Definition: Understand the problem and determine requirements.


2. Algorithm Design: Develop a logical step-by-step procedure to solve the problem.
3. Flowchart Preparation: Represent the algorithm visually using symbols.
4. Coding: Translate the algorithm into a programming language.
5. Compilation and Execution: Convert code into machine-readable format and run it.
6. Testing and Debugging: Identify and correct errors in the program.
7. Documentation: Record the logic, steps, and usage for future reference.

11. Problem-Solving Tools


Algorithmic Thinking: Involves breaking problems into smaller, manageable steps. Algorithms
provide a clear sequence of operations to achieve a solution.

Flowchart: A visual representation of an algorithm using symbols:

 Oval: Start/End
 Rectangle: Process
 Diamond: Decision
 Arrow: Flow of steps

Pseudocode: A text-based method to describe the algorithm in human-readable form. Example:

Start

Read A, B

Sum = A + B

Print Sum

End

12. Program Control Structures

Programs use control structures to dictate the order of execution:

 Sequential Structure: Instructions execute one after another.


 Selection Structure: Decisions are made using conditions (if, if-else, switch).
 Iteration Structure: Loops allow repeated execution based on conditions (for, while, do-
while).

13. Program Methodology

Program methodology is a structured approach to writing programs that ensures clarity,


maintainability, and correctness. Common approaches include:

 Top-Down Design: Break problems into smaller modules and solve each separately.
 Bottom-Up Design: Build modules first and combine them to form the complete
program.
14. Program Models

Programs can follow different models based on their design:

 Procedural Programming: Executes instructions step by step.


 Modular Programming: Divides the program into smaller functions or modules for
better readability and debugging.

Unit 2: Overview of C Language [4 hrs]


Introduction

C is a general-purpose, high-level programming language developed by Dennis Ritchie in the


early 1970s at Bell Labs. It was designed to provide efficient access to hardware while still
offering a structured and flexible programming approach. C is widely used for system
programming, application development, embedded systems, and learning fundamental
programming concepts. One of the main strengths of C is that it allows programmers to write
both simple and complex programs, and it forms the foundation for other modern programming
languages like C++, Java, and Python.

A C program is essentially a set of instructions that tells the computer how to perform specific
tasks. These instructions are written in a standard format using the C language syntax, and they
are compiled into machine code that the computer can execute. Learning C not only helps in
developing software efficiently but also improves problem-solving skills and logical thinking.

C Character Set

The character set of C consists of the smallest building blocks used to write programs. It
includes:

1. Letters: Both uppercase (A–Z) and lowercase (a–z).


2. Digits: Numbers from 0 to 9.
3. Special Characters: Symbols such as +, -, *, /, %, =, ;, {}, (), [], etc.
4. Whitespace Characters: Spaces, tabs, and newline characters, which help separate
tokens but are not visible.

Every valid C program is composed using these characters. Understanding the character set is
essential because every identifier, keyword, or operator in C is made up of characters from this
set.

Tokens in C

Tokens are the smallest meaningful units in a C program. They form the building blocks of a
program. There are mainly five types of tokens:

1. Keywords: Reserved words with a special meaning in C, such as int, float, if, else,
return.
2. Identifiers: Names given to variables, functions, or other user-defined elements, like
age, sum, or calculate. Identifiers must start with a letter or underscore and cannot be a
keyword.
3. Constants: Fixed values that do not change during program execution, such as 10, 3.14,
or 'A'.
4. Operators: Symbols used to perform operations, such as + for addition, - for subtraction,
and * for multiplication.
5. Punctuation or Special Symbols: Symbols like ;, ,, {}, and () that separate statements
or enclose blocks of code.

Tokens must be used correctly; otherwise, the compiler will generate errors.

Identifiers and Keywords

Identifiers are user-defined names for variables, functions, and arrays. They must start with a
letter or an underscore and can contain letters, digits, or underscores. For example, totalMarks
is a valid identifier. Keywords, on the other hand, are predefined words reserved for special
purposes in C, such as for, while, int, char, etc. Keywords cannot be used as identifiers.

Constants and Variables

Constants are fixed values that cannot be changed during program execution. They can be of
different types, such as integers (10), floating-point numbers (3.14), characters ('A'), or strings
("Hello"). Constants are useful when a value must remain unchanged, like the value of pi or a
fixed tax rate.

Variables are named storage locations in memory used to hold data that can change during
program execution. For example, int age; declares a variable age of type integer. Variables
must be declared before they are used, and they can store different types of data depending on
their data type.

Data Types

Data types define the type of value a variable can store. In C, the basic data types are:

 int: Stores integer values like 10, -5, 100.


 float: Stores single-precision decimal numbers like 3.14 or -0.75.
 double: Stores double-precision decimal numbers with more accuracy than float.
 char: Stores a single character like 'A' or 'z'.

Choosing the correct data type is important because it affects the amount of memory used and
the type of operations that can be performed.

Type Conversion

Type conversion is the process of converting a value from one data type to another. It can be
implicit or explicit.

 Implicit Conversion (Type Casting): The compiler automatically converts one data type
to another, such as converting an integer to a float during arithmetic operations.
 Explicit Conversion (Type Casting): The programmer manually converts a data type
using the cast operator. For example:
 int a = 10;
 float b = (float)a; // Explicitly converting int to float

Type conversion is important to avoid errors or loss of data during calculations.

Operators and Expressions

Operators are symbols that perform specific operations on operands. Common categories
include:

 Arithmetic Operators: +, -, *, /, % for performing calculations.


 Relational Operators: ==, !=, >, <, >=, <= used for comparing values.
 Logical Operators: &&, ||, ! used for decision-making.
 Assignment Operators: =, +=, -=, *= used to assign values to variables.
 Increment/Decrement Operators: ++, -- used to increase or decrease a value by 1.

An expression is a combination of variables, constants, and operators that produces a value. For
example:

int sum = a + b * 2;

Here, a + b * 2 is an expression that calculates a value and assigns it to sum.

Structure of a C Program

A typical C program has a specific structure:

1. Header Files: Include predefined libraries like #include <stdio.h> for input/output
operations.
2. Main Function: The starting point of every C program, written as int main() { … }.
3. Declarations: Define variables before using them.
4. Statements: Instructions that perform tasks.
5. Return Statement: Ends the main function and returns a value to the operating system,
usually return 0;.

Example of a simple C program:

#include <stdio.h>

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

Managing Input and Output Operations

C provides standard functions to read input and display output:

 Input: scanf() is used to take input from the user.


Example: scanf("%d", &age); reads an integer and stores it in age.
 Output: printf() is used to display messages or results.
Example: printf("Age = %d", age); displays the value of age.
Format specifiers like %d for integers, %f for floats, and %c for characters are used to tell C the
type of data being handled.

Common Errors in Programming

Programming errors can occur during coding, compilation, or execution. They are generally
categorized as:

1. Syntax Errors: Mistakes in writing code, such as missing semicolons or incorrect


spelling of keywords.
2. Logical Errors: The program runs but produces incorrect results due to flawed logic.
3. Runtime Errors: Errors that occur while the program is running, such as dividing by
zero or accessing invalid memory.

Debugging Basics

Debugging is the process of identifying and fixing errors in a program. Common debugging
techniques include:

 Code Review: Carefully checking the code line by line.


 Using Print Statements: Displaying variable values at different points to trace errors.
 Compiler Warnings: Paying attention to warnings and messages provided by the
compiler.
 Step-by-Step Execution: Using debugging tools to run programs one step at a time.

Effective debugging ensures that programs work correctly and efficiently.


Unit 3: Control Structures [6 hrs]
Introduction to Control Structures
In C programming, a program normally runs line by line from top to bottom. This is called
sequential execution. But real programs cannot work only in a straight line. Sometimes a
program must decide something, sometimes it must repeat an action many times, and sometimes
it must stop or skip part of the code.

Control structures are used to control how, when, and how many times a block of code runs.
Without control structures, programming would be useless for solving real problems.

C provides three main categories of control structures:

1. Decision making statements


2. Looping statements
3. Branching statements

We will study each one step by step, starting from the very basics.

1. Decision Making Statements


Decision making means the program chooses one path based on a condition.
A condition is an expression that gives either true (1) or false (0).

Example of a condition:

age >= 18

If the condition is true, one block runs.


If false, another block runs or nothing happens.

1.1 if Statement (Single Condition)

The if statement is the simplest decision-making statement.

What it does
It checks a condition.
If the condition is true, it executes the code inside { }.
If the condition is false, it skips that code.

Syntax

if (condition) {
statements;
}

Very simple example

#include <stdio.h>

int main() {
int number = 10;

if (number > 5) {
printf("Number is greater than 5");
}

return 0;
}

Explanation step by step

 number is 10
 Condition: number > 5 → true
 So the message is printed

If number was 3, nothing would print.

Common beginner mistake


if (number > 5)
printf("Greater");
printf("Done");

❌ Wrong thinking: both lines are inside if


✅ Reality: only first line is inside if

Correct version:

if (number > 5) {
printf("Greater");
printf("Done");
}
1.2 if–else Statement (Two Choices)

The if–else statement is used when the program must choose between two options.

Syntax

if (condition) {
// runs if condition is true
} else {
// runs if condition is false
}

Example: Even or Odd

#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (num % 2 == 0) {
printf("Number is Even");
} else {
printf("Number is Odd");
}

return 0;
}

Explanation

 % gives remainder
 If remainder is 0 → even
 Otherwise → odd

1.3 else-if Ladder (Multiple Conditions)

When there are more than two conditions, we use the else-if ladder.

How it works

 Conditions are checked from top to bottom


 As soon as one condition is true, others are skipped
Syntax

if (condition1) {
}
else if (condition2) {
}
else if (condition3) {
}
else {
}

Example: Grade system

#include <stdio.h>

int main() {
int marks;

printf("Enter marks: ");


scanf("%d", &marks);

if (marks >= 80) {


printf("Grade A");
} else if (marks >= 60) {
printf("Grade B");
} else if (marks >= 50) {
printf("Grade C");
} else {
printf("Fail");
}

return 0;
}

Important rule
Order matters.
If marks >= 50 was written first, higher grades would never execute.

1.4 switch Statement

The switch statement is used when we compare one variable with many fixed values.

It works only with int and char types.

Syntax

switch (expression) {
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}

Example: Menu program

#include <stdio.h>

int main() {
int choice;

printf("1. Tea\n2. Coffee\n3. Water\n");


printf("Enter choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("You selected Tea");
break;
case 2:
printf("You selected Coffee");
break;
case 3:
printf("You selected Water");
break;
default:
printf("Invalid choice");
}

return 0;
}

Why break is important

Without break, execution continues to the next case.


This is called fall-through, which often causes bugs.

2. Looping Statements
Loops are used when we want to repeat the same code many times.

Example: printing numbers from 1 to 100.

Without loop → impossible


With loop → easy
2.1 while Loop (Entry-controlled loop)

The condition is checked before the loop runs.

Syntax

while (condition) {
statements;
}

Example: Print numbers 1 to 5

#include <stdio.h>

int main() {
int i = 1;

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

return 0;
}

Execution flow

1. Check condition
2. Run body
3. Update variable
4. Repeat

Infinite loop example


while (i <= 5) {
printf("%d\n", i);
}

❌ i++ missing → condition always true

2.2 do–while Loop (Exit-controlled loop)

The body executes at least once, even if the condition is false.


Syntax

do {
statements;
} while (condition);

Example

#include <stdio.h>

int main() {
int i = 10;

do {
printf("%d\n", i);
i++;
} while (i < 5);

return 0;
}

Output

10

Even though condition is false, it runs once.

2.3 for Loop (Most used loop)

Used when the number of iterations is known.

Syntax

for (initialization; condition; update) {


statements;
}

Example

#include <stdio.h>

int main() {
int i;

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


printf("%d\n", i);
}

return 0;
}
Why for loop is popular

 Clean
 Compact
 Easy to read

3. Branching Statements
Branching statements change the normal flow of loops.

3.1 break Statement

Stops the loop or switch immediately.

Example

#include <stdio.h>

int main() {
int i;

for (i = 1; i <= 10; i++) {


if (i == 5) {
break;
}
printf("%d\n", i);
}

return 0;
}

Output

1 2 3 4

3.2 continue Statement

Skips the current iteration and moves to next.

Example

#include <stdio.h>

int main() {
int i;

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


if (i == 3) {
continue;
}
printf("%d\n", i);
}

return 0;
}

Output

1 2 4 5

3.3 goto Statement

Jumps to a labeled statement.

Example

#include <stdio.h>

int main() {
int i = 1;

start:
printf("%d\n", i);
i++;

if (i <= 5)
goto start;

return 0;
}

⚠️ Warning: Avoid goto in real programs. It makes code hard to understand.

4. Common Pitfalls (Very Important for Exams)


Infinite loops

 Condition never becomes false


 Loop variable not updated

Wrong condition
if (a = 5) // wrong
if (a == 5) // correct

Missing braces

Causes logical errors, not syntax errors.

Misusing break and continue

Can skip important logic.


Unit 4: Arrays and Strings (C Language)
Introduction to Arrays
In C programming, an array is a collection of elements of the same data type stored in continuous
memory locations. Instead of creating many separate variables to store similar data, arrays allow
us to store multiple values using a single variable name. For example, if we want to store marks
of 50 students, creating 50 different variables is not practical. An array helps us store all values
together and access them easily using an index.

Each element in an array is identified by an index number. In C, array indexing always starts
from zero. This means the first element is at index 0, the second at index 1, and so on. The size
of an array must be specified at the time of declaration, and it cannot be changed later during
program execution.

Types of Arrays
Arrays in C are mainly classified based on dimensions. The most common types are one-
dimensional arrays and multidimensional arrays. A one-dimensional array stores data in a linear
form, while multidimensional arrays store data in table or matrix form, such as rows and
columns.

One-Dimensional Array
A one-dimensional array is the simplest form of array. It stores a list of elements in a single row.

Declaration of One-Dimensional Array

To declare a one-dimensional array, we specify the data type, array name, and size.

int marks[5];

This means the array marks can store 5 integer values.

Initializing One-Dimensional Array

We can initialize an array at the time of declaration.


int marks[5] = {60, 70, 80, 75, 90};

Here, marks[0] is 60, marks[1] is 70, and so on.

Accessing Array Elements

Array elements are accessed using index numbers.

printf("%d", marks[2]);

This prints 80.

Input and Output Using Loop

Arrays are usually used with loops because loops make it easy to process all elements.

#include <stdio.h>

int main() {
int i;
int marks[5];

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


printf("Enter marks: ");
scanf("%d", &marks[i]);
}

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


printf("Marks = %d\n", marks[i]);
}

return 0;
}

This program takes 5 marks from the user and prints them.

Common Operations on Arrays

Arrays are often used for tasks like finding sum, average, maximum, and minimum values.

Example: Finding the sum of array elements.

#include <stdio.h>
int main() {
int i, sum = 0;
int arr[5] = {10, 20, 30, 40, 50};

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


sum = sum + arr[i];
}

printf("Sum = %d", sum);

return 0;
}

Multidimensional Arrays
A multidimensional array is an array of arrays. The most commonly used multidimensional array
is a two-dimensional array, which is similar to a table with rows and columns.

Two-Dimensional Array Declaration


int matrix[2][3];

This creates a matrix with 2 rows and 3 columns.

Initializing Two-Dimensional Array


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

Accessing Elements
printf("%d", matrix[1][2]);

This prints 6.

Input and Output of 2D Array


#include <stdio.h>
int main() {
int i, j;
int mat[2][2];

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


for(j = 0; j < 2; j++) {
printf("Enter value: ");
scanf("%d", &mat[i][j]);
}
}

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


for(j = 0; j < 2; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}

return 0;
}

Use of Multidimensional Arrays

They are commonly used in matrix operations, tables, marks of students in multiple subjects, and
image processing.

Strings in C
In C, a string is not a separate data type. A string is stored as an array of characters. The end of a
string is marked by a special character called the null character '\0'.

Declaring a String
char name[20];

This can store a string of maximum 19 characters plus one null character.

Initializing a String
char name[] = "Prachit";

C automatically adds the null character at the end.


Taking String Input
scanf("%s", name);

This reads a single word (no spaces).

To read a full sentence:

fgets(name, 20, stdin);

Printing a String
printf("%s", name);

String as Character Array Example


#include <stdio.h>

int main() {
char name[20] = "CSIT";

int i = 0;
while(name[i] != '\0') {
printf("%c\n", name[i]);
i++;
}

return 0;
}

String Handling Functions


C provides built-in functions in <string.h> to work with strings.

strlen()

Used to find the length of a string.

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

int main() {
char name[] = "Nepal";
printf("%d", strlen(name));
return 0;
}

strcpy()

Used to copy one string to another.

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


strcpy(a, b);

strcat()

Used to join two strings.

char a[20] = "Hello ";


char b[] = "World";
strcat(a, b);
printf("%s", a);

strcmp()

Used to compare two strings.

if(strcmp(a, b) == 0) {
printf("Strings are equal");
}

Common Mistakes with Arrays and Strings


Many beginners forget that array index starts from zero. Accessing an index outside the array
size can cause runtime errors. In strings, forgetting the null character or using wrong input
methods often leads to unexpected output. Always ensure array size is sufficient and input is
handled carefully.

Conclusion
Arrays and strings are core concepts in C programming. Arrays help store and process multiple
values efficiently, while strings allow us to handle text data. Understanding how arrays work in
memory, how to use loops with arrays, and how string functions operate is very important for
solving real-world programming problems.
Unit 5: Functions
Introduction to Functions
In C programming, a function is a block of code that performs a specific task. Instead of writing
the same code again and again, we place that code inside a function and reuse it whenever
needed. Functions help make programs easier to understand, easier to debug, and easier to
maintain. A program without functions becomes long, confusing, and hard to manage, especially
when the program grows bigger.

Every C program has at least one function, which is the main() function. Execution of a C
program always starts from the main() function. Other functions are called from main() or from
other functions.

Why Functions Are Needed


Functions divide a large problem into smaller problems. This idea is called modular
programming. Each function handles one task, such as calculating sum, checking even or odd, or
printing output. This makes programs cleaner and more organized. Functions also reduce code
duplication and make testing easier.

User Defined Functions


User defined functions are functions written by the programmer. These are not built-in functions
like printf() or scanf(). A user defined function has three main parts: function declaration,
function definition, and function call.

Function Declaration (Prototype)

A function declaration tells the compiler about the function name, return type, and parameters
before it is used.

Example:

int add(int a, int b);

This tells the compiler that a function named add exists and it returns an integer.
Function Definition

The function definition contains the actual code that runs when the function is called.

int add(int a, int b) {


int sum;
sum = a + b;
return sum;
}

Function Call

A function call is used to execute the function.

result = add(5, 3);

Complete Example of User Defined Function


#include <stdio.h>

int add(int a, int b); // declaration

int main() {
int result;
result = add(10, 20); // function call
printf("Sum = %d", result);
return 0;
}

int add(int a, int b) { // definition


return a + b;
}

Return Statement
The return statement sends a value back to the calling function. It also ends the execution of the
function. A function can return only one value, but that value can be of any data type.

Example:

int square(int x) {
return x * x;
}
If a function does not return any value, it uses the void return type.

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

Types of Functions Based on Return Type and Arguments


Functions in C can be classified into four main types.

1. Function with No Arguments and No Return Value

This type of function neither takes input nor returns output. It performs a task independently.

#include <stdio.h>

void greet() {
printf("Welcome to CSIT");
}

int main() {
greet();
return 0;
}

2. Function with Arguments and No Return Value

This function takes input but does not return any value.

#include <stdio.h>

void printSum(int a, int b) {


printf("Sum = %d", a + b);
}

int main() {
printSum(5, 7);
return 0;
}

3. Function with No Arguments but Return Value

This function does not take input but returns a value.

#include <stdio.h>
int getNumber() {
return 100;
}

int main() {
int x;
x = getNumber();
printf("%d", x);
return 0;
}

4. Function with Arguments and Return Value

This is the most commonly used type of function.

#include <stdio.h>

int multiply(int a, int b) {


return a * b;
}

int main() {
int result;
result = multiply(4, 5);
printf("Result = %d", result);
return 0;
}

Inline Functions
An inline function is a function where the compiler replaces the function call with the actual
code of the function to save execution time. Inline functions are mainly used for small functions.

In C, inline functions are defined using the inline keyword.

#include <stdio.h>

inline int square(int x) {


return x * x;
}

int main() {
printf("%d", square(5));
return 0;
}

Inline functions reduce function call overhead but increase program size if used too much.
Recursion
Recursion is a process where a function calls itself. A recursive function must have a base
condition to stop calling itself, otherwise it will run infinitely and cause stack overflow.

Example: Factorial Using Recursion


#include <stdio.h>

int factorial(int n) {
if(n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int num = 5;
printf("Factorial = %d", factorial(num));
return 0;
}

Here, factorial() keeps calling itself until n becomes 0.

Example: Fibonacci Using Recursion


int fib(int n) {
if(n == 0)
return 0;
if(n == 1)
return 1;
return fib(n - 1) + fib(n - 2);
}

Arrays and Functions


Arrays can be passed to functions to process large amounts of data efficiently. When an array is
passed to a function, only the base address is passed.

Passing One-Dimensional Array to Function


#include <stdio.h>

void display(int arr[], int size) {


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

int main() {
int a[5] = {1, 2, 3, 4, 5};
display(a, 5);
return 0;
}

Finding Sum of Array Using Function


int sumArray(int arr[], int size) {
int i, sum = 0;
for(i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}

Preprocessor Directives
Preprocessor directives are commands that are processed before compilation. They begin with #.

#include

Used to include header files.

#include <stdio.h>

#define

Used to define constants or macros.

#define PI 3.14

Example Using #define


#include <stdio.h>
#define SQUARE(x) x*x

int main() {
printf("%d", SQUARE(5));
return 0;
}

#undef

Used to remove a macro definition.

#undef PI

Standard Library Functions


Standard library functions are built-in functions provided by C libraries.

Some commonly used libraries and functions include:

 stdio.h for input and output functions like printf() and scanf()
 math.h for mathematical functions like sqrt(), pow()
 string.h for string functions like strlen(), strcpy()
 stdlib.h for functions like malloc(), free(), exit()

Example Using math.h


#include <stdio.h>
#include <math.h>

int main() {
printf("%.2f", sqrt(25));
return 0;
}

Common Mistakes in Functions


Beginners often forget to declare functions before using them. Using wrong return types, missing
return statements, and infinite recursion are also common errors. Always ensure function
parameters and return types match correctly.
Conclusion
Functions are the backbone of structured programming in
C. They make programs modular, reusable, and easy to
debug. Understanding user defined functions, recursion,
array passing, and preprocessor directives is essential for
writing efficient and professional C programs.
Unit 6: Pointers (C Language)
Introduction to Pointers
In C programming, a pointer is a special type of variable that stores the memory address of
another variable instead of storing a normal value. Normally, when we create a variable, it stores
data. But a pointer stores where that data is stored in memory. Pointers give C its power and
flexibility, but they also confuse beginners because they deal directly with memory.

Understanding pointers is very important because they are used in arrays, strings, functions,
dynamic memory allocation, and advanced data structures. Without pointers, many powerful
features of C are not possible.

Memory and Address Concept (Very Basic)


Every variable stored in memory has an address. This address is a unique location in RAM.

Example:

int a = 10;

Here, a stores the value 10, but it also has a memory address like 0x61ff08 (address will differ).

To access the address of a variable, we use the address-of operator &.

printf("%p", &a);

Pointer Declaration
A pointer is declared using the * symbol.

int *p;

This means p is a pointer variable that can store the address of an integer variable.

Important point:
*p means value at the address stored in p.

Initializing Pointers
A pointer should always be initialized before use. Initializing means assigning it the address of a
variable.
#include <stdio.h>

int main() {
int a = 10;
int *p;

p = &a;

printf("Value of a = %d\n", a);


printf("Address of a = %p\n", &a);
printf("Value stored in p = %p\n", p);
printf("Value at address p = %d\n", *p);

return 0;
}

Here:

 p stores the address of a


 *p gives the value of a

Dereferencing a Pointer
Dereferencing means accessing the value stored at the address a pointer is pointing to.

int a = 5;
int *p = &a;

printf("%d", *p); // prints 5

Changing value using pointer:

*p = 20;
printf("%d", a); // prints 20

This shows that pointers can directly modify variables.

Arithmetic Operations with Pointers


Pointer arithmetic means performing operations like increment and decrement on pointers.
Pointer arithmetic depends on the data type size.

Example:

int arr[3] = {10, 20, 30};


int *p = arr;

printf("%d\n", *p); // 10
p++;
printf("%d\n", *p); // 20

When p++ is done, the pointer moves to the next integer location, not just the next byte.

Allowed pointer operations:

 Increment (p++)
 Decrement (p--)
 Addition (p + n)
 Subtraction (p - n)
 Comparison (==, <, >)

Pointers and Arrays


Arrays and pointers are closely related in C. The array name itself acts as a pointer to the first
element.

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


int *p = arr;

Here, p points to arr[0].

Accessing array using pointer:

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
int i;

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


printf("%d ", *(p + i));
}

return 0;
}

Pointers and Strings


Strings in C are arrays of characters, and pointers are often used to handle strings.
Example:

char name[] = "Nepal";


char *p = name;

while(*p != '\0') {
printf("%c", *p);
p++;
}

String Pointer Example


#include <stdio.h>

int main() {
char *str = "CSIT";

printf("%s", str);
return 0;
}

Here, str points to the first character of the string.

Pointers and Functions


Pointers are used with functions to pass data by reference. This allows functions to modify
original values.

Call by Value (No Pointer)


void change(int x) {
x = 50;
}

int main() {
int a = 10;
change(a);
printf("%d", a); // still 10
}

Call by Reference (Using Pointer)


#include <stdio.h>
void change(int *x) {
*x = 50;
}

int main() {
int a = 10;
change(&a);
printf("%d", a); // now 50
return 0;
}

Passing Array to Function Using Pointer


void display(int *arr, int size) {
int i;
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}

Pointer to a Pointer
A pointer to a pointer stores the address of another pointer.

int a = 10;
int *p = &a;
int **pp = &p;

Accessing value:

printf("%d", **pp); // prints 10

Example Program
#include <stdio.h>

int main() {
int a = 5;
int *p = &a;
int **pp = &p;

printf("a = %d\n", a);


printf("*p = %d\n", *p);
printf("**pp = %d\n", **pp);

return 0;
}
Void Pointer
A void pointer is a generic pointer that can point to any data type. It is declared using void *.

void *ptr;

Void pointers cannot be dereferenced directly. They must be typecast first.

Example of Void Pointer


#include <stdio.h>

int main() {
int a = 10;
void *p;

p = &a;

printf("%d", *(int *)p);

return 0;
}

Dynamic Memory Allocation


Dynamic memory allocation allows memory to be allocated during program execution. It is
useful when the size of data is not known in advance.

Dynamic memory functions are defined in stdlib.h.

malloc()

Allocates memory without initializing it.

int *p;
p = (int *)malloc(5 * sizeof(int));

calloc()

Allocates memory and initializes it to zero.

int *p;
p = (int *)calloc(5, sizeof(int));

Using malloc Example


#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i;
int *arr;

printf("Enter number of elements: ");


scanf("%d", &n);

arr = (int *)malloc(n * sizeof(int));

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


arr[i] = i + 1;
}

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


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

free(arr);
return 0;
}

free()

Used to release dynamically allocated memory.

free(ptr);

Always free memory to avoid memory leaks.

Common Mistakes with Pointers


Beginners often use uninitialized pointers, which leads to runtime errors. Forgetting to free
allocated memory causes memory leaks. Incorrect pointer arithmetic and wrong type casting are
also common problems. Always initialize pointers and use them carefully.

Conclusion
Pointers are one of the most powerful and important features of C programming. They allow
direct memory access, efficient array handling, function communication, and dynamic memory
management. Although pointers may feel difficult at first, practicing simple examples step by
step makes them easy and logical.
Unit 7: Structures and Unions (C Language)
Introduction to Structures and Unions
In real life, data does not exist in isolation. For example, a student is not represented by only a
number or only a name. A student has a roll number, name, age, marks, address, and many other
properties. In C, basic data types like int, float, and char can store only one value at a time.
Arrays help store multiple values, but they can store only values of the same data type. This
creates a problem when we want to store related data of different types together.

Structures and unions solve this problem. They allow us to combine different data types into a
single unit. This makes programs more meaningful, organized, and closer to real-world
representation.

A structure stores all its members separately in memory, so all values exist at the same time. A
union shares the same memory among its members, so only one value is meaningful at a time.
Both are user-defined data types.

Understanding Structure Concept from Zero


Before writing code, it is important to understand what a structure really is. A structure is like a
blueprint or template. It defines what type of data a variable will contain, but it does not allocate
memory by itself. Memory is allocated only when a structure variable is created.

Think of a structure as a form. The form has fields like name, age, and marks. Filling the form
means creating a structure variable.

Structure Declaration
A structure is declared using the struct keyword. Inside the structure, we declare variables
called members.

struct Student {
int roll;
char name[30];
float marks;
};

This code does not create any variable. It only defines a new data type named struct Student.
Creating Structure Variables
Once a structure is defined, we can create variables of that type.

struct Student s1;

Now memory is allocated for s1. The memory size will be the sum of memory required by all its
members (plus padding).

Accessing Structure Members


Structure members are accessed using the dot operator ( .).

[Link] = 1;
[Link] = 85.5;

For character arrays inside structures, we cannot assign strings directly using =. We must use
string functions.

strcpy([Link], "Prachit");

Complete Example with Explanation


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

struct Student {
int roll;
char name[30];
float marks;
};

int main() {
struct Student s1;

[Link] = 10;
strcpy([Link], "CSIT Student");
[Link] = 78.25;

printf("Roll Number: %d\n", [Link]);


printf("Name: %s\n", [Link]);
printf("Marks: %.2f\n", [Link]);

return 0;
}
Here, all three members exist in memory at the same time. This is the key feature of structures.

Initialization of a Structure
Structures can also be initialized at the time of declaration.

struct Student s2 = {20, "Nepal", 90.5};

The values are assigned in the order of structure members. If the order is wrong, incorrect values
will be stored.

Why Array of Structures Is Needed


If we want to store data of multiple students, creating separate variables like s1, s2, s3 is not
practical. This is where arrays of structures are used.

Array of Structures
An array of structures stores multiple structure variables in continuous memory locations.

struct Student students[3];

Each element of this array is a complete Student structure.

Example: Input and Output Using Array of Structures


#include <stdio.h>

struct Student {
int roll;
float marks;
};

int main() {
struct Student s[3];
int i;

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


printf("Enter roll and marks: ");
scanf("%d %f", &s[i].roll, &s[i].marks);
}

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


printf("Roll: %d Marks: %.2f\n", s[i].roll, s[i].marks);
}

return 0;
}

This is commonly used in real applications like databases and record systems.

Nested Structures (Structure Inside Structure)


Sometimes a structure member itself is another structure. This is called a nested structure. This is
useful when data has a logical hierarchy.

Example: Date Inside Student


struct Date {
int day;
int month;
int year;
};

struct Student {
int roll;
struct Date dob;
};

Here, dob is a structure inside another structure.

Accessing Nested Structure Members


[Link] = 1;
[Link] = 17;
[Link] = 11;
[Link] = 2006;

Structure and Functions (Very Important Concept)


Structures are often passed to functions for processing.
Passing Structure by Value

When a structure is passed by value, a copy of the structure is created. Changes inside the
function do not affect the original structure.

void display(struct Student s) {


[Link] = 100;
}

This wastes memory for large structures.

Passing Structure by Reference

Passing structure by reference means passing its address using a pointer.

void display(struct Student *s) {


s->marks = 100;
}

This modifies the original structure and is more efficient.

Arrow Operator (->)

When accessing structure members using a pointer, the arrow operator is used.

s->roll

This is the same as:

(*s).roll

Unions: Concept from Basics


A union is similar to a structure, but its members share the same memory location. This means
only one member can hold a valid value at a time.

Union Declaration
union Data {
int i;
float f;
char c;
};

The size of the union will be equal to the size of its largest member.

Union Example with Explanation


#include <stdio.h>

union Data {
int i;
float f;
};

int main() {
union Data d;

d.i = 10;
printf("i = %d\n", d.i);

d.f = 3.14;
printf("f = %.2f\n", d.f);

return 0;
}

When f is assigned, the value of i is destroyed. This is the main difference between union and
structure.

Why Unions Are Used


Unions are used when memory optimization is required and when only one value is needed at a
time. They are used in low-level programming, compilers, and hardware-related programs.

Pointer to Structure
A pointer to structure stores the address of a structure variable.

struct Student s;
struct Student *p = &s;
Accessing members:

p->roll = 5;

Pointer to Union
Pointers can also point to union variables.

union Data d;
union Data *p = &d;

Access using arrow operator:

p->i = 20;

Memory Comparison: Structure vs Union


In a structure, each member has its own memory, so total memory is the sum of all members. In
a union, memory is shared, so total memory is equal to the largest member. This is a very
common exam question.

Real-Life Example to Understand Difference


Structure is like a bag with separate compartments. Union is like a single box where only one
item fits at a time.

Common Mistakes Students Make


Many students forget to include <string.h> when using strcpy. Others misuse the arrow
operator or confuse structure and union memory behavior. Another common mistake is trying to
access multiple union members at the same time.

Conclusion
Structures and unions are fundamental concepts in C that help represent complex data efficiently.
Structures focus on clarity and usability, while unions focus on memory efficiency.
Understanding arrays of structures, nested structures, and pointers with structures is essential for
advanced C programming and for understanding how real software systems manage data.
Unit 8: File Handling in C
Why File Handling Is Needed (From Absolute Basics)
When a C program runs, all variables are stored in RAM. RAM is temporary memory. This
means when the program ends or the computer shuts down, all data is lost. For example, if you
write a program to enter student marks and print them, once the program stops, the marks
disappear.

In real life, we want data to stay even after the program finishes. We want to save marks,
records, usernames, results, and reports permanently. This permanent storage is done using files.

A file is a collection of data stored on disk with a name. File handling in C allows programs to
create files, write data into files, read data from files, update data, and delete files.
Basic Idea of How File Handling Works
C does not directly talk to the disk. Instead, it uses a special pointer called a file pointer.
This file pointer connects the program to a file.

FILE *fp;

FILE is a structure defined in stdio.h.


fp is used to control the file.

Opening a File (Most Important Step)


Before reading or writing, a file must be opened using fopen().

fp = fopen("[Link]", "w");

This means:

 "[Link]" is the file name


 "w" means write mode

If the file does not exist, it is created.


If it exists, its old content is erased.

File Opening Modes (Explained Simply)


"r" → read only (file must exist)
"w" → write only (creates new file)
"a" → append (adds data at end)
"r+" → read and write
"w+" → write and read (erase old data)
"rb" → read binary file
"wb" → write binary file

Closing a File (Very Important)


After finishing work, the file must be closed.

fclose(fp);

If you don’t close the file:


 Data may not be saved
 Memory leak can happen

Writing Data to a Text File (Very Easy Start)


Example 1: Write Simple Text
#include <stdio.h>

int main() {
FILE *fp;

fp = fopen("[Link]", "w");

fprintf(fp, "Hello World");


fprintf(fp, "\nWelcome to File Handling");

fclose(fp);
return 0;
}

This creates [Link] and writes text into it.

Reading Data from a Text File (Character by Character)


Example 2: Read File Using fgetc()
#include <stdio.h>

int main() {
FILE *fp;
char ch;

fp = fopen("[Link]", "r");

while((ch = fgetc(fp)) != EOF) {


printf("%c", ch);
}

fclose(fp);
return 0;
}

Here:

 fgetc() reads one character


 EOF means end of file

Reading a File Line by Line


Example 3: Using fgets()
#include <stdio.h>

int main() {
FILE *fp;
char line[100];

fp = fopen("[Link]", "r");

while(fgets(line, 100, fp) != NULL) {


printf("%s", line);
}

fclose(fp);
return 0;
}

This is safer and faster for text files.

Appending Data to a File


Append mode does not delete old data.

Example 4: Append Text


fp = fopen("[Link]", "a");
fprintf(fp, "\nThis is appended text");
fclose(fp);

File Error Handling (Must Know)


Sometimes files do not exist or cannot be opened.

Correct Way to Open File


fp = fopen("[Link]", "r");

if(fp == NULL) {
printf("File cannot be opened");
return 0;
}

If fp == NULL, file opening failed.

Binary Files (Why and When)


Text files store data as readable characters. Binary files store data exactly as it is in memory.
Binary files are:

 Faster
 Smaller
 Used for structures

Writing Structure to Binary File


Example 5: Save Student Record
#include <stdio.h>

struct Student {
int roll;
float marks;
};

int main() {
FILE *fp;
struct Student s;

[Link] = 1;
[Link] = 85.5;

fp = fopen("[Link]", "wb");
fwrite(&s, sizeof(s), 1, fp);

fclose(fp);
return 0;
}

Reading Structure from Binary File


Example 6: Read Student Record
#include <stdio.h>

struct Student {
int roll;
float marks;
};

int main() {
FILE *fp;
struct Student s;

fp = fopen("[Link]", "rb");
fread(&s, sizeof(s), 1, fp);

printf("Roll: %d\n", [Link]);


printf("Marks: %.2f\n", [Link]);

fclose(fp);
return 0;
}

Difference Between Text and Binary Files (Simple)


Text file:

 Human readable
 Slower
 Uses fprintf, fscanf

Binary file:

 Not readable
 Faster
 Uses fwrite, fread

File Access Methods


Sequential Access

Data is read from start to end.

while(fscanf(fp, "%d", &x) != EOF)

Random Access (Using fseek)


fseek(fp, 0, SEEK_SET); // beginning
fseek(fp, 0, SEEK_END); // end

Standard Input and Output as Files


Keyboard and screen are also treated as files.

fprintf(stdout, "Hello");
fscanf(stdin, "%d", &x);

Command Line Arguments (From Zero)


Command line arguments allow input during program execution.

int main(int argc, char *argv[])

 argc → number of arguments


 argv → argument values

Example 7: Print Command Line Arguments


#include <stdio.h>

int main(int argc, char *argv[]) {


int i;

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


printf("%s\n", argv[i]);
}

return 0;
}

Using Command Line Argument for File Name


Example 8: Read File Name from Command Line
#include <stdio.h>

int main(int argc, char *argv[]) {


FILE *fp;
char ch;

fp = fopen(argv[1], "r");
if(fp == NULL) {
printf("File not found");
return 0;
}

while((ch = fgetc(fp)) != EOF) {


printf("%c", ch);
}

fclose(fp);
return 0;
}

Run like this:

program [Link]

Deleting and Renaming Files


remove("[Link]");
rename("[Link]", "[Link]");

Common Beginner Mistakes


 Forgetting to close file
 Not checking fp == NULL
 Mixing text and binary functions
 Using wrong file mode
 Writing without flushing buffer

Final Understanding
File handling makes C programs practical and real-world usable. Without files, programs are
temporary. With files, programs can store data permanently, share data, and work like databases.
Text files are simple and readable, while binary files are fast and efficient. Command line
arguments add flexibility and automation.
Introduction to Graphics in C
What Is Graphics in C (From Absolute Zero)
Normally, C programs work in text mode. You see output using printf() and input using
scanf(). This means everything appears as text on a black screen.

Graphics means working in visual mode, where we draw:

 lines
 circles
 rectangles
 colors
 shapes
 designs

Instead of printing text, we draw directly on the screen using pixels.

A pixel is the smallest dot on the screen. Many pixels together form shapes and images.

Graphics Library in C
C uses a graphics library called BGI (Borland Graphics Interface).
The header file used is:

#include <graphics.h>

This library allows us to control:

 screen resolution
 colors
 drawing functions

Basic Requirement Before Using Graphics


To use graphics, three things are required:
1. Graphics header file
2. Graphics driver
3. Graphics mode initialization

Without initializing graphics mode, nothing will be drawn.

Graphics Modes (What Does Mode Mean?)


A graphics mode defines:

 screen width
 screen height
 number of colors

Common modes:

 low resolution, fewer colors


 high resolution, more colors

In simple terms, mode tells the computer how to display graphics.

You don’t usually choose mode manually. C provides automatic detection.

Initializing Graphics Mode (MOST IMPORTANT STEP)


Before drawing anything, we must initialize graphics using initgraph().

Basic Syntax
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

Explanation:

 gd → graphics driver
 gm → graphics mode
 DETECT → auto detect best mode
 "" → path to driver (empty for modern setups)
First Graphics Program (Very Basic)
This program just opens a graphics screen.

#include <graphics.h>
#include <conio.h>

int main() {
int gd = DETECT, gm;

initgraph(&gd, &gm, "");

getch();
closegraph();
return 0;
}

Explanation:

 initgraph() opens graphics screen


 getch() waits for key press
 closegraph() closes graphics mode

If you don’t use getch(), the screen closes immediately.

Coordinate System in Graphics


Graphics screen uses X and Y coordinates.

 Top-left corner is (0, 0)


 X increases to the right
 Y increases downward

Example:

 (100, 100) means 100 pixels right, 100 pixels down

Drawing a Point (Pixel)


Function Used
putpixel(x, y, color);
Example: Draw a Single Pixel
#include <graphics.h>
#include <conio.h>

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

putpixel(100, 100, WHITE);

getch();
closegraph();
return 0;
}

Drawing a Line
Function Used
line(x1, y1, x2, y2);

Example: Draw a Line


line(50, 50, 200, 50);

This draws a horizontal line.

Complete Program
#include <graphics.h>
#include <conio.h>

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

line(50, 50, 200, 50);

getch();
closegraph();
return 0;
}

Drawing a Rectangle
Function Used
rectangle(left, top, right, bottom);

Example
rectangle(100, 100, 300, 200);

Complete Program
#include <graphics.h>
#include <conio.h>

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

rectangle(100, 100, 300, 200);

getch();
closegraph();
return 0;
}

Drawing a Circle
Function Used
circle(x, y, radius);

Example
circle(200, 200, 50);

Complete Program
#include <graphics.h>
#include <conio.h>

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

circle(200, 200, 50);

getch();
closegraph();
return 0;
}
Drawing an Ellipse
ellipse(x, y, start_angle, end_angle, x_radius, y_radius);

Example:

ellipse(250, 200, 0, 360, 100, 50);

Working with Colors


Graphics provides predefined colors like:

 BLACK
 WHITE
 RED
 GREEN
 BLUE
 YELLOW
 CYAN
 MAGENTA

Changing Drawing Color


Function Used
setcolor(color);

Example
setcolor(RED);
circle(200, 200, 60);

Filling Shapes with Color


Functions Used
setfillstyle(pattern, color);
floodfill(x, y, border_color);

Example: Filled Rectangle


#include <graphics.h>
#include <conio.h>

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

rectangle(100, 100, 300, 200);


setfillstyle(SOLID_FILL, BLUE);
floodfill(150, 150, WHITE);

getch();
closegraph();
return 0;
}

Explanation:

 SOLID_FILL fills completely


 floodfill() fills inside boundary

Clearing the Screen


cleardevice();

This removes all drawings.

Writing Text in Graphics Mode


Function Used
outtextxy(x, y, "Text");

Example
outtextxy(100, 50, "Hello Graphics");

Complete Mini Example (Shapes + Colors + Text)


#include <graphics.h>
#include <conio.h>

int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");

setcolor(RED);
circle(200, 200, 60);

setcolor(GREEN);
rectangle(100, 300, 300, 400);

setfillstyle(SOLID_FILL, YELLOW);
floodfill(150, 350, GREEN);

outtextxy(150, 100, "Graphics in C");

getch();
closegraph();
return 0;
}

Common Beginner Mistakes in Graphics


 Forgetting initgraph()
 Not using getch()
 Wrong coordinates
 Not closing graphics mode
 Filling without boundary

Real-Life Use of Graphics in C


 Simple games
 Visual simulations
 Drawing tools
 Educational software
 Animations (basic)

Final Understanding
Graphics in C allows programs to go beyond text and create visual output. Everything is drawn
using pixels and coordinates. Before drawing anything, graphics mode must be initialized.
Shapes like lines, circles, and rectangles are created using simple functions, and colors make
visuals more attractive. With practice, complex designs and animations can be built.

You might also like