C Programing Compiled Note
C Programing Compiled Note
Course Objectives
After completing this course, students will be able to:
1. Introduction to Computers
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.
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.
4. Memory Types
Memory is a critical component of a computer, responsible for storing both data and instructions.
Memory types can be divided into:
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:
Peripherals allow users to interact with the computer, improve its performance, and increase its
usability for various tasks.
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.
Oval: Start/End
Rectangle: Process
Diamond: Decision
Arrow: Flow of steps
Start
Read A, B
Sum = A + B
Print Sum
End
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
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:
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 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 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:
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
Operators are symbols that perform specific operations on operands. Common categories
include:
An expression is a combination of variables, constants, and operators that produces a value. For
example:
int sum = a + b * 2;
Structure of a C Program
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;.
#include <stdio.h>
int main() {
int a = 10, b = 20;
int sum = a + b;
printf("Sum = %d", sum);
return 0;
}
Programming errors can occur during coding, compilation, or execution. They are generally
categorized as:
Debugging Basics
Debugging is the process of identifying and fixing errors in a program. Common debugging
techniques include:
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.
We will study each one step by step, starting from the very basics.
Example of a condition:
age >= 18
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;
}
#include <stdio.h>
int main() {
int number = 10;
if (number > 5) {
printf("Number is greater than 5");
}
return 0;
}
number is 10
Condition: number > 5 → true
So the message is printed
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
}
#include <stdio.h>
int main() {
int 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
When there are more than two conditions, we use the else-if ladder.
How it works
if (condition1) {
}
else if (condition2) {
}
else if (condition3) {
}
else {
}
#include <stdio.h>
int main() {
int marks;
return 0;
}
Important rule
Order matters.
If marks >= 50 was written first, higher grades would never execute.
The switch statement is used when we compare one variable with many fixed values.
Syntax
switch (expression) {
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
#include <stdio.h>
int main() {
int 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;
}
2. Looping Statements
Loops are used when we want to repeat the same code many times.
Syntax
while (condition) {
statements;
}
#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
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
Syntax
Example
#include <stdio.h>
int main() {
int i;
return 0;
}
Why for loop is popular
Clean
Compact
Easy to read
3. Branching Statements
Branching statements change the normal flow of loops.
Example
#include <stdio.h>
int main() {
int i;
return 0;
}
Output
1 2 3 4
Example
#include <stdio.h>
int main() {
int i;
return 0;
}
Output
1 2 4 5
Example
#include <stdio.h>
int main() {
int i = 1;
start:
printf("%d\n", i);
i++;
if (i <= 5)
goto start;
return 0;
}
Wrong condition
if (a = 5) // wrong
if (a == 5) // correct
Missing braces
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.
To declare a one-dimensional array, we specify the data type, array name, and size.
int marks[5];
printf("%d", marks[2]);
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];
return 0;
}
This program takes 5 marks from the user and prints them.
Arrays are often used for tasks like finding sum, average, maximum, and minimum values.
#include <stdio.h>
int main() {
int i, sum = 0;
int arr[5] = {10, 20, 30, 40, 50};
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.
Accessing Elements
printf("%d", matrix[1][2]);
This prints 6.
return 0;
}
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";
Printing a String
printf("%s", name);
int main() {
char name[20] = "CSIT";
int i = 0;
while(name[i] != '\0') {
printf("%c\n", name[i]);
i++;
}
return 0;
}
strlen()
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Nepal";
printf("%d", strlen(name));
return 0;
}
strcpy()
strcat()
strcmp()
if(strcmp(a, b) == 0) {
printf("Strings are equal");
}
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.
A function declaration tells the compiler about the function name, return type, and parameters
before it is used.
Example:
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.
Function Call
int main() {
int result;
result = add(10, 20); // function call
printf("Sum = %d", result);
return 0;
}
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");
}
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;
}
This function takes input but does not return any value.
#include <stdio.h>
int main() {
printSum(5, 7);
return 0;
}
#include <stdio.h>
int getNumber() {
return 100;
}
int main() {
int x;
x = getNumber();
printf("%d", x);
return 0;
}
#include <stdio.h>
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.
#include <stdio.h>
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.
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;
}
int main() {
int a[5] = {1, 2, 3, 4, 5};
display(a, 5);
return 0;
}
Preprocessor Directives
Preprocessor directives are commands that are processed before compilation. They begin with #.
#include
#include <stdio.h>
#define
#define PI 3.14
int main() {
printf("%d", SQUARE(5));
return 0;
}
#undef
#undef PI
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()
int main() {
printf("%.2f", sqrt(25));
return 0;
}
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.
Example:
int a = 10;
Here, a stores the value 10, but it also has a memory address like 0x61ff08 (address will differ).
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;
return 0;
}
Here:
Dereferencing a Pointer
Dereferencing means accessing the value stored at the address a pointer is pointing to.
int a = 5;
int *p = &a;
*p = 20;
printf("%d", a); // prints 20
Example:
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.
Increment (p++)
Decrement (p--)
Addition (p + n)
Subtraction (p - n)
Comparison (==, <, >)
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr;
int i;
return 0;
}
while(*p != '\0') {
printf("%c", *p);
p++;
}
int main() {
char *str = "CSIT";
printf("%s", str);
return 0;
}
int main() {
int a = 10;
change(a);
printf("%d", a); // still 10
}
int main() {
int a = 10;
change(&a);
printf("%d", a); // now 50
return 0;
}
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:
Example Program
#include <stdio.h>
int main() {
int a = 5;
int *p = &a;
int **pp = &p;
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;
int main() {
int a = 10;
void *p;
p = &a;
return 0;
}
malloc()
int *p;
p = (int *)malloc(5 * sizeof(int));
calloc()
int *p;
p = (int *)calloc(5, sizeof(int));
int main() {
int n, i;
int *arr;
free(arr);
return 0;
}
free()
free(ptr);
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.
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.
Now memory is allocated for s1. The memory size will be the sum of memory required by all its
members (plus padding).
[Link] = 1;
[Link] = 85.5;
For character arrays inside structures, we cannot assign strings directly using =. We must use
string functions.
strcpy([Link], "Prachit");
struct Student {
int roll;
char name[30];
float marks;
};
int main() {
struct Student s1;
[Link] = 10;
strcpy([Link], "CSIT Student");
[Link] = 78.25;
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.
The values are assigned in the order of structure members. If the order is wrong, incorrect values
will be stored.
Array of Structures
An array of structures stores multiple structure variables in continuous memory locations.
struct Student {
int roll;
float marks;
};
int main() {
struct Student s[3];
int i;
return 0;
}
This is commonly used in real applications like databases and record systems.
struct Student {
int roll;
struct Date dob;
};
When a structure is passed by value, a copy of the structure is created. Changes inside the
function do not affect the original structure.
When accessing structure members using a pointer, the arrow operator is used.
s->roll
(*s).roll
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 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.
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;
p->i = 20;
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;
fp = fopen("[Link]", "w");
This means:
fclose(fp);
int main() {
FILE *fp;
fp = fopen("[Link]", "w");
fclose(fp);
return 0;
}
int main() {
FILE *fp;
char ch;
fp = fopen("[Link]", "r");
fclose(fp);
return 0;
}
Here:
int main() {
FILE *fp;
char line[100];
fp = fopen("[Link]", "r");
fclose(fp);
return 0;
}
if(fp == NULL) {
printf("File cannot be opened");
return 0;
}
Faster
Smaller
Used for structures
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;
}
struct Student {
int roll;
float marks;
};
int main() {
FILE *fp;
struct Student s;
fp = fopen("[Link]", "rb");
fread(&s, sizeof(s), 1, fp);
fclose(fp);
return 0;
}
Human readable
Slower
Uses fprintf, fscanf
Binary file:
Not readable
Faster
Uses fwrite, fread
fprintf(stdout, "Hello");
fscanf(stdin, "%d", &x);
return 0;
}
fp = fopen(argv[1], "r");
if(fp == NULL) {
printf("File not found");
return 0;
}
fclose(fp);
return 0;
}
program [Link]
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.
lines
circles
rectangles
colors
shapes
designs
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>
screen resolution
colors
drawing functions
screen width
screen height
number of colors
Common modes:
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;
getch();
closegraph();
return 0;
}
Explanation:
Example:
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
getch();
closegraph();
return 0;
}
Drawing a Line
Function Used
line(x1, y1, x2, y2);
Complete Program
#include <graphics.h>
#include <conio.h>
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
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, "");
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, "");
getch();
closegraph();
return 0;
}
Drawing an Ellipse
ellipse(x, y, start_angle, end_angle, x_radius, y_radius);
Example:
BLACK
WHITE
RED
GREEN
BLUE
YELLOW
CYAN
MAGENTA
Example
setcolor(RED);
circle(200, 200, 60);
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
getch();
closegraph();
return 0;
}
Explanation:
Example
outtextxy(100, 50, "Hello Graphics");
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);
getch();
closegraph();
return 0;
}
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.