Programming in C Unit-1 BCA Semester I
1
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Unit-I: Problem solving with a Computer
Problem Solving:
Problem solving is the process of identifying a problem, analyzing it, developing an algorithm,
and then implementing it as a computer program.
Before solving a problem, we must understand it clearly. This includes knowing:
• Input: What is needed to solve the problem.
• Process: The steps to be followed to solve it.
• Output: The final result we get after solving the problem.
Example: Making a Cup of Tea
• Input: Water, milk, sugar, and tea leaves (or tea bag).
• Process: Boil water and milk → Add tea leaves and sugar → Boil for a few minutes →
Filter the tea.
• Output: A cup of hot tea.
Steps in Problem Solving:
There are 4 basic steps involved in problem solving
1. Analyze the Problem: Understand what the problem is and what is required to solve it.
2. Develop an Algorithm: Write the step-by-step procedure to solve the problem.
3. Coding: Convert the algorithm into a program using a programming language.
4. Testing and Debugging: Check the program for errors and correct them to get the correct
output.
Computer Program: A computer program is a set of instructions written in a programming
language that tells the computer how to perform a specific task.
Programming: Programming is the process of writing, testing, and debugging instructions
(code) to create a computer program.
Programming in C Unit-1 BCA Semester I
2
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Algorithm:
An algorithm is a step-by-step procedure or set of rules to solve a specific problem.
Characteristics of a Good Algorithm:
• Finiteness: It must terminate after a finite number of steps.
• Definiteness: Each step should be clear and have only one meaning.
• Input: It should accept zero or more inputs from the user.
• Output: It must produce at least one output.
• Effectiveness: Each step should be simple and practical to perform.
Representation of Algorithm
An algorithm can be represented in two ways: 1) Flowchart 2) Pseudo Code
Flowchart:
A flowchart is a diagram that represents the steps of an algorithm using symbols and arrows to
show the flow of control.
Programming in C Unit-1 BCA Semester I
3
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Pseudo Code:
Pseudo code is a simple way of writing the steps of an algorithm using plain English-like
statements, without following the syntax of any programming language.
Examples:
1. Area of a Circle
i) Algorithm
1.Start
2.Read the radius (R)
3.Calculate Area ← 3.14 × R × R
4.Display Area
5.Stop
iiii) Flowchart
Programming in C Unit-1 BCA Semester I
4
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
iii)Pseudocode
Start
Read the value of radius (R)
Set Area = 3.14 * R * R
Display the value of Area
Stop
2. Find the Largest of Three Numbers
i) Algorithm
1.Start
2.Read three numbers A, B, C
3.If A > B
If A > C
Largest ← A
Else
Largest ← C
4.Else
If B > C
Largest ← B
Else
Largest ← C
5.Display Largest
6.Stop
Programming in C Unit-1 BCA Semester I
5
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
ii) Flowchart
3. Sum of N Numbers
i) Algorithm
1.Start
2.Read N (total count of numbers)
3.Initialize SUM ← 0, I ← 1
4.Repeat while I ≤ N
Read number
SUM ← SUM + number
I ← I + 1
5.Display SUM
6.Stop
Programming in C Unit-1 BCA Semester I
6
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
ii) Flowchart
Types Programming Languages:
Programming languages are broadly classified into two main types:
1. Structured/Procedural Programming (POPs):
• In this approach, the program is divided into small parts called functions or procedures.
• It follows a top-down approach, where the problem is broken into smaller sub-problems
and solved step by step.
• The focus is on the sequence of actions or operations to be performed.
• Example: C language.
Programming in C Unit-1 BCA Semester I
7
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
2. Object-Oriented Programming (OOPs):
• This approach is based on real-world objects that contain both data (attributes) and
functions (methods).
• It follows a bottom-up approach, where individual objects are created first and then
combined to form a complete program.
• The focus is on data rather than procedures, supporting modularity, reusability, and
data security.
• Example: C++, Java, Python.
Overview of C
• C is a general-purpose, structured (procedural) programming language developed by
Dennis Ritchie (known as the Father of C) in 1972 at Bell Laboratories (USA) and was
implemented for the first time in minicomputer DEC PDP-11(Digital Equipment
Corporation-Programmed Data Processor).
Dennis Ritchie DEC PDP-11
• It is widely used for developing system software, operating systems, and applications
due to its efficiency, portability, and flexibility.
• C evolved from two previous programming languages BCPL (Basic Combined
Programming Language) and B Language
• Denise Ritchie used the concepts of BCPL and B to develop C and added data typing and
some other powerful features.
Programming in C Unit-1 BCA Semester I
8
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
History of C Programming Language
• The history of the C programming language began in the 1950s with the development of
earlier high-level languages.
• In 1960s Dennis Ritchie was working at AT&T Bell Labs to develop an operating
system (OS) at those times all the systems used assembly language which required pages
of codes for even simple tasks.
• The UNIX OS was originally developed by Dennis Ritchie and Ken Thompson using
Assembly Language. Later, when the system was upgraded from PDP-7 to PDP-11, the
B language (developed by Thompson) was found incompatible.
• To overcome this, Dennis Ritchie developed a new high-level language called C, which
was the improved successor of B.
Programming in C Unit-1 BCA Semester I
9
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Before C, several programming languages were developed that influenced its creation:
1. ALGOL (Algorithmic Language) – Developed in 1960 by an International Committee,
ALGOL introduced the concept of structured programming, which strongly influenced
the design of C and many later languages.
2. BCPL (Basic Combined Programming Language) – Developed in 1967 by Martin
Richards, BCPL was mainly used for writing system software and served as the
foundation for the B language.
3. B Language – Developed in 1970 by Ken Thompson at Bell Laboratories, B was derived
from BCPL and used in the early development of the UNIX operating system.
4. Traditional C (1972) – Developed by Dennis Ritchie at AT&T Bell Laboratories
(USA), C was designed as an improved and efficient successor to B. It was used to rewrite
the UNIX operating system, making it portable and powerful.
5. K&R C (1978) – In 1978, Brian Kernighan and Dennis Ritchie published the famous
book “The C Programming Language”, often called K&R C, which helped popularize
and standardize C globally.
Later, several standardized versions of C were introduced:
6. ANSI C (C89) – Standardized in 1989 by the American National Standards Institute
(ANSI) to ensure consistency across compilers.
7. ANSI/ISO C (C90) – Approved internationally in 1990 by the International
Organization for Standardization (ISO) as the global standard version of C.
8. C99 (1999) – Introduced new features like inline functions, variable-length arrays, and
long long int data type.
9. C11 (2011) – Added multithreading support, atomic operations, and library
enhancements.
10. C17 (2018) – A bug-fix and stability update of C11 for improved compiler consistency.
11. C23 (2024) – The latest version that modernizes C with new features while maintaining
backward compatibility.
Today, C remains one of the most widely used programming languages and forms the
foundation for many modern languages such as C++, Java, and Python.
Programming in C Unit-1 BCA Semester I
10
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Features of C:
C is a powerful, structured, and general-purpose programming language developed by
Dennis Ritchie in 1972. It is widely used for system programming and application
development due to its simplicity, efficiency, and portability.
1. Simple and Easy to Learn: C has only 32 keywords and clear syntax, making it easy to
understand and use.
2. Structured Language: Programs in C are divided into functions, improving readability
and maintenance.
3. Fast and Efficient: C programs execute quickly due to low-level memory access and
optimized code.
4. Portable: C programs can run on different computer systems with little or no modification.
5. Middle-Level Language: C combines features of both high-level (user-friendly) and low-
level (hardware-level) languages.
6. Rich Library: It provides many built-in functions for input/output, math, and string
handling.
7. Memory Management: C allows direct memory access using pointers and supports
dynamic memory allocation.
8. Recursion: Functions in C can call themselves, useful for solving repetitive problems.
9. Extensible: New functions and features can be easily added to a C program.
10. Widely Used: C is used in system software, operating systems, embedded systems, and
application development.
Programming in C Unit-1 BCA Semester I
11
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Structure of a C Program
A C program has a defined structure divided into several sections. Each section plays a specific
role in program execution. The general structure is as follows:
1. Documentation Section:
Contains comments describing the program’s name, author, date, and purpose. Written using // for
single-line or /*...*/ for multi-line comments.
2. Link Section (Preprocessor Directives):
The Link Section is used to link the program with necessary library files that provide predefined
functions for input, output, and other operations.
Preprocessor Directives are instructions that begin with the symbol #, such as #include or
#define, and are processed by the compiler before the actual compilation starts.
Programming in C Unit-1 BCA Semester I
12
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Header files (#include <stdio.h>) give access to predefined library functions such as printf() and
scanf(), while macros are used to define constants or short reusable code.
3. Global Declaration Section:
Declares global variables, constants, and function prototypes accessible by all functions in the
program.
4. main() Function Section:
The entry point of every C program; contains local variables, input/output statements, Calls to
user-defined or library functions.. Every statement in C ends with a semicolon (;).
5. User-Defined Function Section:
Contains functions created by the programmer for specific tasks, improving modularity and
reusability. Executable statements inside functions also end with semicolons.
Programming in C Unit-1 BCA Semester I
13
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Creating and Executing a C Program
The process of developing and running a C program involves several stages that convert human-
readable source code into machine-executable form
1.Writing / Editing:
The first step is writing the C program using any text editor like Notepad, VS Code, or an IDE
such as Turbo C or Code::Blocks. The written program is called the source code, which is
human-readable. The program is saved with the .c extension (e.g., hello.c).
Programming in C Unit-1 BCA Semester I
14
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
2. Preprocessing:
Before compilation, the preprocessor processes all lines beginning with #, such as #include and
#define. It removes comments, expands macros, and includes header files. This generates an
intermediate file with the extension. i (e.g., hello.i).
3. Compilation:
The compiler checks the preprocessed code for syntax errors and converts it into assembly-level
instructions. It generates a file with the .s extension (e.g., hello.s).
4. Assembly:
The assembler translates the assembly code into machine language (binary form).The output of
this stage is an object file with the extension .obj or .o (e.g., hello.obj).
5. Linking:
The linker combines the object file with necessary library files (like stdio.h) that contain
predefined function definitions. It resolves external references and creates an executable file with
the extension .exe (e.g., hello.exe).
6. Execution:
Finally, the operating system loads the executable file into memory and runs it using the CPU and
other hardware components. This produces the final output on the screen.
Example Flow: hello.c → hello.i → hello.s → hello.obj →Linker →hello.exe → Output
Programming in C Unit-1 BCA Semester I
15
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
C Character Set
• The C character set is the collection of all valid characters, including Alphabets/letters,
digits, symbols, and spaces, that can be used to write a C program.
• It is based on the ASCII (American Standard Code for Information Interchange)
character encoding, which defines 128 (7-bit) or 256 (8-bit) characters.
• These characters are used to form identifiers, keywords, constants, operators, and
symbols in a C program.
Character Types in C:
There are four main types of characters used in C:
1. Alphabets/letters
• Alphabets include both uppercase (A–Z) and lowercase (a–z) English letters.
• Alphabets are mainly used to form identifiers, variable names, function names, and
keywords.
Example:
int TotalMarks;
char grade = 'A';
Here, TotalMarks and grade are identifiers made using alphabets.
Programming in C Unit-1 BCA Semester I
16
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
2. Digits
• Digits are the numeric characters from 0 to 9.
• They are used to represent numbers and constants in programs.
Example:
int rollNo = 25;
sum = 10 + 5;
Here, the digits 25, 10, and 5 are numeric constants used in variable initialization and arithmetic
operations.
3. Special Symbols
• Special symbols are characters that have a specific meaning or purpose in C.
• They are used in expressions, control structures, operators, and program delimiters.
• Examples include: +, -, *, /, =, #, {}, [], (), ;, ,, @, etc.
Example:
float avg = (a + b) / 2.0;
printf("Done!");
Here, (), +, /, ;, and " " are special symbols used for grouping, arithmetic, termination, and output
formatting.
4. White Spaces
• Whitespace characters in C are blank spaces (' '), tab ('t'), and newline ('n').
• They are used to separate tokens and improve readability of the code.
Example:
int a = 10; // spaces used between tokens
printf("Hellon"); // n adds a new line after printing
Programming in C Unit-1 BCA Semester I
17
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
C Tokens
• Token are the smallest individual element of a program that has a specific meaning to
the compiler.
• During compilation, the compiler breaks the source code into these meaningful units
called tokens.
• Just like a sentence is made up of words, a C program is made up of tokens. Tokens in
C are building blocks which means a program can’t be created without tokens.
Types of Tokens in C
C language consists of the following types of tokens:
1. Keywords in C
• Keywords are pre-defined or reserved words in C that have special meanings and
predefined purposes.
• C supports total of 32 keywords, these are case-sensitive and written in lower cases, their
meaning and functionality are already known to the compiler.
• They cannot be used as variable or function names.
Examples:
int, float, if, else, while, for, return, switch, break, void, etc.
Tokens
1.Keywords
int, float, if, else, while, for
2.Identifiers
sum, totalMarks, Student_Name
3.Constants
78, -53, 0.5, -54, 'A', "BCA"
4.Variables
Programming in C Unit-1 BCA Semester I
18
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
3. Identifiers in C
Identifiers are user-defined names used to identify variables, functions, arrays, or
structures.
Rules for Identifiers:
1. An identifier can contain letters (A–Z, a–z), digits (0–9), and underscores (_).
2. The first character must be a letter or underscore, not a digit.
3. Identifiers are case-sensitive (e.g., Total and total are different).
4. Keywords (like int, for, return) cannot be used as identifiers.
5. There should be no spaces or special symbols (like @, #, -) in identifiers.
6. The length of an identifier should be reasonable and meaningful.
Examples:
Valid Identifiers:
sum, totalMarks, Student_Name, _average, count1
Invalid Identifiers:
1number (starts with a digit)
total marks (contains a space)
float (keyword)
@value (special character not allowed)
3. Constants in C
• Constants are identifiers whose values do not change during the execution of a program,
they are also called literals in C.
• Constants are often used to represent fixed values like π (pi) or physical quantities such
as the charge of an electron.
Programming in C Unit-1 BCA Semester I
19
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Declaring Constants:
(a) Using const keyword:
const float pi = 3.14159;
Here, pi cannot be changed later in the program.
(b) Using #define Preprocessor Directive:
#define PI 3.14159
#define SERVICE_TAX 0.12
The compiler replaces each occurrence of PI with 3.14159 before
compilation.
Rules for #define:
1. Constant names are usually written in capital letters.
2. No space between # and define.
3. Space must be present between define, name, and value.
4. It does not end with a semicolon.
Types of Constants in C:
i) Integer Constants:
• These are whole numbers without any fractional part.
• Keyword const int is used declare the integer constants
Example:
const int marks = 100; // Decimal
const int code = 012; // Octal (starts with 0)
const int hexValue = 0x7F; // Hexadecimal (starts with x)
Programming in C Unit-1 BCA Semester I
20
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
ii)Floating Point Constants:
• These represent real numbers with fractional parts or exponential forms.
• Keyword const float is used declare the floating constants
• By default, floating constants are of type double.
• To make them float, add suffix F or f.
Example:
const float pi = 3.14F;
const float num=-0.05;
const double rate = 1.2E-3; // 1.2x10-3
= 0.0012
const double rate = 1.2E3; // 1.2x103
=1200
iii)Character Constants:
• A single character enclosed in single quotes (‘ ’).
• Examples: 'A', '5', '@'
• These are stored as ASCII values internally.
• Keyword const char is used declare the character constants
Example:
const char grade = 'A';
const char num='5';
iv) String Constants:
• A sequence/array of characters enclosed in double quotes (“ ”).
• Each string ends with a null character (‘0’) automatically.
• Keyword const char[] is used declare the character constants
Example:
const char str [] = "School";
Length of "India" is 7 (6 characters + 1 null).
Programming in C Unit-1 BCA Semester I
21
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
4. Variables in C
• A variable in C is a named memory location used to store data that can change during
program execution.
• It acts as a container for values like numbers, characters, or strings.
Variable Declaration Syntax:
In C, we can declare variables two ways
i)data_type variable_name; // Declaration only (no value assigned)
int age; // Declaration only
float salary; // Declaration only
char grade; // Declaration only
ii)data_type variable_name = value; // Declaration with initialization
int age = 25; // Declares and initializes 'age' with 25
float salary = 5000.50; // Declares and initializes 'salary' with 5000.50
char grade = 'A'; // Declares and initializes 'grade' with 'A
Types of Variables in C:
In C, variables are classified based on where and how they are declared, which affects their
scope, lifetime, and visibility.
• Scope: The part of the program where a variable can be accessed.
• Lifetime: The duration for which a variable exists in memory.
• Visibility: Where the variable name is recognized by the compiler.
The 4 types of variables in C are Local, Global, Static, and External.
Programming in C Unit-1 BCA Semester I
22
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
a) Local Variables
• Declared inside a function or block.
• Can be used only within that block or function.
• Created when the function starts and destroyed when it ends.
Example:
#include<stdio.h>
int main ()
{
int a = 5; // Local variable
printf("%d", a);
}
Output: 5
Scope: Inside the function
Lifetime: Function execution time
Visibility: Not visible outside the function
b) Global Variables
• Declared outside all functions.
• Can be accessed by all functions in the same program.
• Retain their value throughout the program execution.
Example:
#include <stdio.h>
int count = 0; // Global variable
void increment()
{
count++;
}
int main()
{
increment();
printf("%d", count);
return 0;
}
Programming in C Unit-1 BCA Semester I
23
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Output: 1
Scope: Entire program
Lifetime: Till program ends
Visibility: Visible to all functions after declaration
c) Static Variables
• Declared using the keyword static.
• Retains its value between multiple function calls.
• Has local scope but global lifetime.
Example:
#include <stdio.h>
void demo()
{
static int x = 0; // Static variable
x++;
printf("%d ", x);
}
int main()
{
demo();
demo();
demo();
return 0;
}
Output: 1 2 3
Scope: Local to the function
Lifetime: Till program ends
Visibility: Not visible outside the function
Programming in C Unit-1 BCA Semester I
24
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
d) External Variables
• Declared using the keyword extern to use variables defined in another file.
• Allows sharing of global variables across multiple files in large programs.
Example (Two files):
File1.c
int score = 90;
File2.c
#include <stdio.h>
extern int score; // External variable
int main()
{
printf("%d", score);
return 0;
}
Output: 90
Scope: Entire program (across files)
Lifetime: Till program ends
Visibility: Visible in other files using extern
Type Declared Where Scope Lifetime Keyword
Local Inside function/block Within that block Function execution —
Global Outside all functions Entire program Program end —
Static Inside function with static Function Program end static
External In another file with extern Across files Program end extern
In simple terms:
Local = Temporary inside function
Global = Accessible everywhere
Static = Remembers value
External = Shared across files
Programming in C Unit-1 BCA Semester I
25
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Data Types in C programming
• In C programming, a data type defines the type of data a variable can hold.
• It tells the compiler how much memory to allocate and what kind of operations can be
performed on the data.
• They are platform-dependent (e.g., size may vary depending on compiler/architecture).
• C data types are mainly divided into three categories:
I. Primitive Data Types (Basic/Built-in/Predefined)
Primary data types are basic data types supported by the C compiler to store integers, floats, and
characters. They include: void, int, char, float, and double.
a) void
The void data type represents an empty data type. It means “no value” or “nothing.”
• Keyword: The void keyword is used when a function does not return any value.
• Size: 0 bytes – It does not occupy any memory.
• Value Range: Not applicable (no value is stored).
Example Declaration:
void display(); //Used for functions that do not return a value.
Programming in C Unit-1 BCA Semester I
26
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
b) Integer (int)
The int data type is used to store Integer numbers (both positive and negative) without decimals.
• Keyword: The int keyword is used to declare integer variables.
• Size: It occupies 2/4bytes (16/32bits) of memory depending on the compiler.
• Value Range:
For 16-bit → –2¹⁵ to 2¹⁵–1 = –32,768 to 32,767=~±32K
For 32-bit → –2³¹ to 2³¹–1 = –2,147,483,648 to 2,147,483,647=~±2.1×109 (Billion)
• Format Specifier: %d is used for integer values.
Example Declaration:
int age = 25;
int temp= -10;
c) Character (char)
The char data type is used to store a single character or small integer value represented by
ASCII codes.
• Keyword: The char keyword is used to declare character variables.
• Size: It occupies 1 byte (8 bits) of memory.
• Value Range: –2⁷ to 2⁷–1 = –128 to 127 = ~±128
• Format Specifier: %c is used for character values.
Example Declaration:
char grade = 'A';
char symbol = '#';
d) Float (float)
The float data type is used to store decimal (fractional) numbers with single precision.
• Keyword: The float keyword is used to declare floating-point variables.
• Size: It occupies 4 bytes (32 bits) of memory.
Programming in C Unit-1 BCA Semester I
27
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
• Value Range: Approximately ±3.4 × 10³⁸
• Format Specifier: %f is used for float values.
Example Declaration:
float pi = 3.14f;
float marks = 87.56;
e) Double (double)
The double data type is used to store decimal (fractional) numbers with double precision and
higher accuracy.
• Keyword: The double keyword is used to declare double-precision floating variables.
• Size: It occupies 8 bytes (64 bits) of memory.
• Value Range: Approximately ±1.7 × 10³⁰⁸
• Format Specifier: %lf is used for double values.
Example Declaration:
double salary = 9999.99;
double distance = 12345.6789;
II. Derived/Secondary Data Types
In C programming, Derived Data Types are those that are built upon the primary (basic) data
types. These include:
Signed and Unsigned
• Signed means the variable can hold both positive and negative values.
• Unsigned means the variable can hold only non-negative values (0 and above).
Programming in C Unit-1 BCA Semester I
28
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
By default, most integer types in C are signed unless explicitly declared as unsigned.
Data Type Keyword Size
(Bytes/Bits)
- Value Range Description Example
Signed
Character
signed char
1 byte
(8 bits)
%d / %c
–2⁷ to 2⁷–1
→ –128 to 127
Stores small signed
character/ASCII
values
signed char a = -10;
Unsigned
Character
unsigned
char
1 byte
(8 bits)
%u / %c
0 to 2⁸–1
→ 0 to 255
Stores only positive
character/ASCII
values
unsigned char b = 250;
Signed
Short
Integer
signed short /
short
2 bytes
(16 bits)
%d
215
to 215
–1
→32,768 to 32,767
(~±32K)
Small signed integers short s = -32768;
Unsigned
Short
Integer
unsigned
short
2 bytes
(16 bits)
%u
0 to 216
–1
→0 to 65,535 (~65K)
Small positive
integers
unsigned short us = 65535;
Signed
Integer
signed int /
int
4 bytes
(32-bits)
%d
2³¹ to 2³¹–1
→ (~±2.1×109
(Billion))
Default signed integer int i = -1000;
Unsigned
Integer
unsigned int
4 bytes
(32-bits)
%u
0 to 232
–1
→0 to 4.2 ×109
(Billion)
Large positive
integers
unsigned int ui = 100000;
Signed
Long
Integer
signed long /
long
4 bytes
(32-bits)
%ld
2³¹ to 2³¹–1
→ (~±2.1×109
(Billion))
Large signed integers long l = -9999999;
Unsigned
Long
Integer
unsigned
long
4 bytes
(32-bits)
%lu
0 to 232
–1
→0 to 4.2 ×109
(Billion)
Large unsigned
integers
unsigned long ul =
5000000;
Long
Double
long double
16 bytes
(128-bits)
(x64, GCC)
%Lf /
%Le
±3.4×10−4932
to
±1.1×104932
1 sign + 15 exponent +
112 fraction.
Extended
precision(quadruple)f
loating numbers
long double pi =
3.141592653589L;
III. User Defined Data Type (UDDT)
• UDDT in C are custom data types created by the programmer to represent complex or
grouped information.
• They allow us to design meaningful data structures beyond basic types like int or char,
making programs clearer and easier to manage.
1. Array
An array is a collection of similar data items stored in continuous memory locations, accessed
using a single name and index.
Size of array = number of elements × size of each element
Programming in C Unit-1 BCA Semester I
29
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example:
int a[5] → 5 × 4 = 20 bytes
Example with Size
#include <stdio.h>
int main()
{
int a[4] = {1, 2, 3, 4}; // Integer array of 4 elements
char b[6] = {'A', 'B', 'C', 'D', 'E', 'F'}; // Character array of 6 characters
float c[3] = {1.1, 2.2, 3.3}; // Float array of 3 floating-point values
printf("Size of int array = %lu bytesn", sizeof(a));
printf("Size of char array = %lu bytesn", sizeof(b));
printf("Size of float array = %lu bytesn", sizeof(c));
return 0;
}
Output:
int = 4 bytes → 4 × 4 = 16 bytes
char = 1 byte → 6 × 1 = 6 bytes
float = 4 bytes → 3 × 4 = 12 bytes
2. Structure
A structure is a user-defined data type used to group different types of data under a single name.
Size of structure = sum of sizes of all members + extra bytes (padding may be added)
Example:
int + float + char → 4 + 4 + 1 = 9
Computer adjusts → 12 bytes
Programming in C Unit-1 BCA Semester I
30
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example with Size
#include <stdio.h>
struct Student
{
int id;
float marks;
char grade;
};
int main()
{
struct Student s1;
printf("Size of structure = %lu bytesn", sizeof(s1));
return 0;
}
Output:
Structure contains:
• int → 4 bytes
• float → 4 bytes
• char → 1 byte + padding (3 bytes for alignment)
Total size = 12 bytes
Padding is the extra empty bytes added so each data type starts at a memory address that is a
multiple of its size (like 2, 4, or 8 bytes) for faster CPU access.
3.Union
A union is a user-defined data type where different members share the same memory location,
and only one member can hold a value at a time.
Size of union = size of the largest member
Programming in C Unit-1 BCA Semester I
31
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Example:
int (4 bytes), float (4 bytes), char (1 byte)
Largest = 4 bytes
Example with Size
#include <stdio.h>
union Data
{
int x;
int a[5];
char b[10];
};
int main()
{
union Data d1;
printf("Size of union = %lu bytesn", sizeof(d1));
return 0;
}
Output:
Members in the union:
• int x → 4 bytes
• int a[5] → 5 × 4 = 20 bytes
• char b[10] → 10 × 1 = 10 bytes
Largest member = int a[5] = 20 bytes
Programming in C Unit-1 BCA Semester I
32
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Symbolic Constants
• Symbolic constants are named constants used in a C program to make code more
readable, maintainable, and meaningful.
• They are created using the #define preprocessor directive, and the compiler replaces these
names with their actual values during compilation.
Syntax:
#define CONSTANT_NAME value
Features of Symbolic Constants
1. No data type: They do not have a specific data type; they are handled through simple text
substitution.
2. Defined using #define: Created before compilation using the preprocessor.
3. Global scope: Once defined, they can be used anywhere in the file after their definition.
4. Improves readability: Replaces confusing numbers with meaningful names.
5. Easy to update: Changing the value in one place updates it throughout the program.
Example:
#include <stdio.h>
#define PI 3.14159
#define MAX 100
#define MESSAGE "Welcome to C programming"
int main() {
float radius = 5.0;
float area = PI * radius * radius;
printf("Area of circle: %.2fn", area);
printf("Max value allowed: %dn", MAX);
printf("%sn", MESSAGE);
return 0;
}
Programming in C Unit-1 BCA Semester I
33
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Output:
Advantages of Symbolic Constants
1. Symbolic constants make the program easier to read
(Example: PI is easier to understand than typing 3.14159 everywhere.)
2. They allow us to change a value in one place only
(Example: Change #define MAX 100 to 200 once, and the whole program updates.)
3. They remove repeated numbers in the code
(Example: Use LIMIT instead of writing 50 many times.)
4. They reduce typing mistakes and errors
(Example: Typing 9.81 many times can cause mistakes; using GRAVITY avoids errors.)
5. They make the program easy to update and maintain
(Example: If the tax rate changes, update #define TAX 0.05 once instead of changing
everywhere.)
Header Files
• A header file in C is a file with a .h extension that contains function declarations, macro
definitions, constants, and other shared information.
• It is included in a program using the #include directive to reuse code and avoid rewriting
common functions.
Programming in C Unit-1 BCA Semester I
34
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
Types of Header Files
1. System Header Files
• System header files are the files provided by the C compiler, containing predefined
functions and libraries.
• They are included in a program using angle brackets < >.
Example: #include <stdio.h>
2. User-defined Header Files
• User-defined header files are created by programmers to store their own functions, macros,
or definitions for reuse.
• They are included in a program using double quotes " ".
Example: #include "BCA.h"
Syntax:
#include <header_name.h> // For system-defined header files
#include "header_name.h" // For user-defined header files
Common System Header Files in C
Header
File
Introduction 5 Common Functions
stdio.h Standard Input/Output header; used for
reading input and printing output.
printf(), scanf(), getchar(), putchar(), gets()
conio.h Console I/O header (mostly Turbo C); used
for screen handling and character
input/output.
clrscr(), getch(), getche(), textcolor(),
cprintf()
math.h Provides mathematical functions like power,
root, trigonometry, and logarithm.
sqrt(), pow(), sin(), cos(),
log(),fmax(),fmin()
string.h Used for string handling and manipulation. strlen(), strcpy(), strcat(), strcmp(), strrev()
ctype.h Character handling and conversion
functions.
isalpha(), isdigit(), islower(), isupper(),
toupper(),tolower()
Programming in C Unit-1 BCA Semester I
35
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
1) Standard Input/Output Header (stdio.h)
stdio.h is the standard input/output header file in C. It provides functions to read input from the
user and display output on the screen.
Common stdio.h Functions:
Function Purpose Example Input / Output
printf() Displays formatted output on
the screen
printf("Hello, World!n"); Output: Hello, World!
scanf() Reads formatted input from
the user
int num;
scanf("%d", &num);
Input: 25 → num = 25
getchar() Reads a single character from
the keyboard
char ch = getchar(); Input: A → ch = A
putchar() Prints a single character on
the screen
putchar('B'); Output: B
gets()/fgets() Reads an entire line of text
from the user (use fgets() for
safety)
char str[20];
fgets(str, sizeof(str),
stdin);
Input: Hello → str =
"Hellon"
2.Console Input/Output header file (conio.h)
conio.h is a console input/output header file, mainly used in Turbo C. It provides functions for
screen handling and reading/writing characters from/to console.
Common conio.h Functions:
Function Purpose Example Input / Output
clrscr() Clears the console screen clrscr(); Clears the screen (no visible
output)
getch() Reads a single character
without displaying it
char ch = getch(); Input: A → ch = A (not
displayed)
getche() Reads a single character and
displays it
char ch = getche(); Input: B → ch = B (displayed)
textcolor() Changes the color of console
text
textcolor(4); Changes text color to red
(depends on compiler)
cprintf() Prints formatted output on
console
cprintf("Hello C
World");
Output: Hello C World
Programming in C Unit-1 BCA Semester I
36
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
3. Mathematical header file (math.h)
math.h provides standard mathematical functions for calculations like square root, power,
trigonometry, logarithms, and comparisons.
Common functions in math.h:
Function Purpose Example Output /
Result
sqrt() Returns the square root of a number double result = sqrt(16); result = 4.0
pow() Returns a number raised to a power double result = pow(2, 3); result = 8.0
sin() Returns the sine of an angle (in
radians)
double s = sin(3.14/2); s ≈ 1.0
cos() Returns the cosine of an angle (in
radians)
double c = cos(0); c = 1.0
log() Returns the natural logarithm (base e)
of a number
double l = log(2.718); l ≈ 1.0
fmax() Returns the maximum of two numbers double m = fmax(5.5, 3.2); m = 5.5
fmin() Returns the minimum of two numbers double n = fmin(5.5, 3.2); n = 3.2
4. String header file (string.h)
• The string.h header file in C contains functions used for manipulating and handling
strings (which are arrays of characters terminated by a null character '0').
• It includes operations such as finding the length of a string, copying one string to another,
comparing strings, and concatenating strings.
Common Functions in string.h
Function Purpose Example Input / Output
strlen() Returns the length of a string int len = strlen("Hello"); len = 5
strcpy() Copies one string into another char dest[10];
strcpy(dest, "Hi");
dest = "Hi"
strcat() Concatenates (joins) two strings char str1[20] = "Hello";
strcat(str1, " World");
str1 = "Hello
World"
strcmp() Compares two strings int res1 = strcmp("abc", "abc");
int res2= strcmp("abc", "ABC");
res1 = 0 (equal)
res2 = 1 (not equal)
strrev() Reverses the characters of a
string (non-standard)
char str[] = "Hello";
strrev(str); str = "olleH"
Programming in C Unit-1 BCA Semester I
37
Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432
📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca
5. Character header file (ctype.h)
• The ctype.h header file in C provides functions for testing and manipulating individual
characters.
• It helps to check whether a character is a letter, digit, space, etc., and also convert
characters between uppercase and lowercase.
Common Functions in ctype.h
Function Purpose Example Input / Output
(True/False / Result)
isalpha() Checks whether a character
is an alphabet
int res1 = isalpha('A');
int res2 = isalpha('1');
res1 = 1 (true),
res2 = 0 (false)
isdigit() Checks whether a character
is a digit
int res1 = isdigit('9');
int res2 = isdigit('a');
res1 = 1 (true),
res2 = 0 (false)
islower() Checks whether a character
is lowercase
int res1 = islower('a');
int res2 = islower('Z');
res1 = 1 (true),
res2 = 0 (false)
isupper() Checks whether a character
is uppercase
int res1 = isupper('Z');
int res2 = isupper('b');
res1 = 1 (true),
res2 = 0 (false)
toupper() Converts a lowercase
character to uppercase
char ch1 = toupper('b'); ch1 = 'B'
tolower() Converts an uppercase
character to lowercase
char ch2 = tolower('B'); Ch2 = 'b',
*** ** ***

C UNIT-I :Unit-I: Problem solving with a Computer

  • 1.
    Programming in CUnit-1 BCA Semester I 1 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Unit-I: Problem solving with a Computer Problem Solving: Problem solving is the process of identifying a problem, analyzing it, developing an algorithm, and then implementing it as a computer program. Before solving a problem, we must understand it clearly. This includes knowing: • Input: What is needed to solve the problem. • Process: The steps to be followed to solve it. • Output: The final result we get after solving the problem. Example: Making a Cup of Tea • Input: Water, milk, sugar, and tea leaves (or tea bag). • Process: Boil water and milk → Add tea leaves and sugar → Boil for a few minutes → Filter the tea. • Output: A cup of hot tea. Steps in Problem Solving: There are 4 basic steps involved in problem solving 1. Analyze the Problem: Understand what the problem is and what is required to solve it. 2. Develop an Algorithm: Write the step-by-step procedure to solve the problem. 3. Coding: Convert the algorithm into a program using a programming language. 4. Testing and Debugging: Check the program for errors and correct them to get the correct output. Computer Program: A computer program is a set of instructions written in a programming language that tells the computer how to perform a specific task. Programming: Programming is the process of writing, testing, and debugging instructions (code) to create a computer program.
  • 2.
    Programming in CUnit-1 BCA Semester I 2 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Algorithm: An algorithm is a step-by-step procedure or set of rules to solve a specific problem. Characteristics of a Good Algorithm: • Finiteness: It must terminate after a finite number of steps. • Definiteness: Each step should be clear and have only one meaning. • Input: It should accept zero or more inputs from the user. • Output: It must produce at least one output. • Effectiveness: Each step should be simple and practical to perform. Representation of Algorithm An algorithm can be represented in two ways: 1) Flowchart 2) Pseudo Code Flowchart: A flowchart is a diagram that represents the steps of an algorithm using symbols and arrows to show the flow of control.
  • 3.
    Programming in CUnit-1 BCA Semester I 3 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Pseudo Code: Pseudo code is a simple way of writing the steps of an algorithm using plain English-like statements, without following the syntax of any programming language. Examples: 1. Area of a Circle i) Algorithm 1.Start 2.Read the radius (R) 3.Calculate Area ← 3.14 × R × R 4.Display Area 5.Stop iiii) Flowchart
  • 4.
    Programming in CUnit-1 BCA Semester I 4 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca iii)Pseudocode Start Read the value of radius (R) Set Area = 3.14 * R * R Display the value of Area Stop 2. Find the Largest of Three Numbers i) Algorithm 1.Start 2.Read three numbers A, B, C 3.If A > B If A > C Largest ← A Else Largest ← C 4.Else If B > C Largest ← B Else Largest ← C 5.Display Largest 6.Stop
  • 5.
    Programming in CUnit-1 BCA Semester I 5 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca ii) Flowchart 3. Sum of N Numbers i) Algorithm 1.Start 2.Read N (total count of numbers) 3.Initialize SUM ← 0, I ← 1 4.Repeat while I ≤ N Read number SUM ← SUM + number I ← I + 1 5.Display SUM 6.Stop
  • 6.
    Programming in CUnit-1 BCA Semester I 6 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca ii) Flowchart Types Programming Languages: Programming languages are broadly classified into two main types: 1. Structured/Procedural Programming (POPs): • In this approach, the program is divided into small parts called functions or procedures. • It follows a top-down approach, where the problem is broken into smaller sub-problems and solved step by step. • The focus is on the sequence of actions or operations to be performed. • Example: C language.
  • 7.
    Programming in CUnit-1 BCA Semester I 7 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 2. Object-Oriented Programming (OOPs): • This approach is based on real-world objects that contain both data (attributes) and functions (methods). • It follows a bottom-up approach, where individual objects are created first and then combined to form a complete program. • The focus is on data rather than procedures, supporting modularity, reusability, and data security. • Example: C++, Java, Python. Overview of C • C is a general-purpose, structured (procedural) programming language developed by Dennis Ritchie (known as the Father of C) in 1972 at Bell Laboratories (USA) and was implemented for the first time in minicomputer DEC PDP-11(Digital Equipment Corporation-Programmed Data Processor). Dennis Ritchie DEC PDP-11 • It is widely used for developing system software, operating systems, and applications due to its efficiency, portability, and flexibility. • C evolved from two previous programming languages BCPL (Basic Combined Programming Language) and B Language • Denise Ritchie used the concepts of BCPL and B to develop C and added data typing and some other powerful features.
  • 8.
    Programming in CUnit-1 BCA Semester I 8 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca History of C Programming Language • The history of the C programming language began in the 1950s with the development of earlier high-level languages. • In 1960s Dennis Ritchie was working at AT&T Bell Labs to develop an operating system (OS) at those times all the systems used assembly language which required pages of codes for even simple tasks. • The UNIX OS was originally developed by Dennis Ritchie and Ken Thompson using Assembly Language. Later, when the system was upgraded from PDP-7 to PDP-11, the B language (developed by Thompson) was found incompatible. • To overcome this, Dennis Ritchie developed a new high-level language called C, which was the improved successor of B.
  • 9.
    Programming in CUnit-1 BCA Semester I 9 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Before C, several programming languages were developed that influenced its creation: 1. ALGOL (Algorithmic Language) – Developed in 1960 by an International Committee, ALGOL introduced the concept of structured programming, which strongly influenced the design of C and many later languages. 2. BCPL (Basic Combined Programming Language) – Developed in 1967 by Martin Richards, BCPL was mainly used for writing system software and served as the foundation for the B language. 3. B Language – Developed in 1970 by Ken Thompson at Bell Laboratories, B was derived from BCPL and used in the early development of the UNIX operating system. 4. Traditional C (1972) – Developed by Dennis Ritchie at AT&T Bell Laboratories (USA), C was designed as an improved and efficient successor to B. It was used to rewrite the UNIX operating system, making it portable and powerful. 5. K&R C (1978) – In 1978, Brian Kernighan and Dennis Ritchie published the famous book “The C Programming Language”, often called K&R C, which helped popularize and standardize C globally. Later, several standardized versions of C were introduced: 6. ANSI C (C89) – Standardized in 1989 by the American National Standards Institute (ANSI) to ensure consistency across compilers. 7. ANSI/ISO C (C90) – Approved internationally in 1990 by the International Organization for Standardization (ISO) as the global standard version of C. 8. C99 (1999) – Introduced new features like inline functions, variable-length arrays, and long long int data type. 9. C11 (2011) – Added multithreading support, atomic operations, and library enhancements. 10. C17 (2018) – A bug-fix and stability update of C11 for improved compiler consistency. 11. C23 (2024) – The latest version that modernizes C with new features while maintaining backward compatibility. Today, C remains one of the most widely used programming languages and forms the foundation for many modern languages such as C++, Java, and Python.
  • 10.
    Programming in CUnit-1 BCA Semester I 10 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Features of C: C is a powerful, structured, and general-purpose programming language developed by Dennis Ritchie in 1972. It is widely used for system programming and application development due to its simplicity, efficiency, and portability. 1. Simple and Easy to Learn: C has only 32 keywords and clear syntax, making it easy to understand and use. 2. Structured Language: Programs in C are divided into functions, improving readability and maintenance. 3. Fast and Efficient: C programs execute quickly due to low-level memory access and optimized code. 4. Portable: C programs can run on different computer systems with little or no modification. 5. Middle-Level Language: C combines features of both high-level (user-friendly) and low- level (hardware-level) languages. 6. Rich Library: It provides many built-in functions for input/output, math, and string handling. 7. Memory Management: C allows direct memory access using pointers and supports dynamic memory allocation. 8. Recursion: Functions in C can call themselves, useful for solving repetitive problems. 9. Extensible: New functions and features can be easily added to a C program. 10. Widely Used: C is used in system software, operating systems, embedded systems, and application development.
  • 11.
    Programming in CUnit-1 BCA Semester I 11 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Structure of a C Program A C program has a defined structure divided into several sections. Each section plays a specific role in program execution. The general structure is as follows: 1. Documentation Section: Contains comments describing the program’s name, author, date, and purpose. Written using // for single-line or /*...*/ for multi-line comments. 2. Link Section (Preprocessor Directives): The Link Section is used to link the program with necessary library files that provide predefined functions for input, output, and other operations. Preprocessor Directives are instructions that begin with the symbol #, such as #include or #define, and are processed by the compiler before the actual compilation starts.
  • 12.
    Programming in CUnit-1 BCA Semester I 12 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Header files (#include <stdio.h>) give access to predefined library functions such as printf() and scanf(), while macros are used to define constants or short reusable code. 3. Global Declaration Section: Declares global variables, constants, and function prototypes accessible by all functions in the program. 4. main() Function Section: The entry point of every C program; contains local variables, input/output statements, Calls to user-defined or library functions.. Every statement in C ends with a semicolon (;). 5. User-Defined Function Section: Contains functions created by the programmer for specific tasks, improving modularity and reusability. Executable statements inside functions also end with semicolons.
  • 13.
    Programming in CUnit-1 BCA Semester I 13 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Creating and Executing a C Program The process of developing and running a C program involves several stages that convert human- readable source code into machine-executable form 1.Writing / Editing: The first step is writing the C program using any text editor like Notepad, VS Code, or an IDE such as Turbo C or Code::Blocks. The written program is called the source code, which is human-readable. The program is saved with the .c extension (e.g., hello.c).
  • 14.
    Programming in CUnit-1 BCA Semester I 14 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 2. Preprocessing: Before compilation, the preprocessor processes all lines beginning with #, such as #include and #define. It removes comments, expands macros, and includes header files. This generates an intermediate file with the extension. i (e.g., hello.i). 3. Compilation: The compiler checks the preprocessed code for syntax errors and converts it into assembly-level instructions. It generates a file with the .s extension (e.g., hello.s). 4. Assembly: The assembler translates the assembly code into machine language (binary form).The output of this stage is an object file with the extension .obj or .o (e.g., hello.obj). 5. Linking: The linker combines the object file with necessary library files (like stdio.h) that contain predefined function definitions. It resolves external references and creates an executable file with the extension .exe (e.g., hello.exe). 6. Execution: Finally, the operating system loads the executable file into memory and runs it using the CPU and other hardware components. This produces the final output on the screen. Example Flow: hello.c → hello.i → hello.s → hello.obj →Linker →hello.exe → Output
  • 15.
    Programming in CUnit-1 BCA Semester I 15 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca C Character Set • The C character set is the collection of all valid characters, including Alphabets/letters, digits, symbols, and spaces, that can be used to write a C program. • It is based on the ASCII (American Standard Code for Information Interchange) character encoding, which defines 128 (7-bit) or 256 (8-bit) characters. • These characters are used to form identifiers, keywords, constants, operators, and symbols in a C program. Character Types in C: There are four main types of characters used in C: 1. Alphabets/letters • Alphabets include both uppercase (A–Z) and lowercase (a–z) English letters. • Alphabets are mainly used to form identifiers, variable names, function names, and keywords. Example: int TotalMarks; char grade = 'A'; Here, TotalMarks and grade are identifiers made using alphabets.
  • 16.
    Programming in CUnit-1 BCA Semester I 16 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 2. Digits • Digits are the numeric characters from 0 to 9. • They are used to represent numbers and constants in programs. Example: int rollNo = 25; sum = 10 + 5; Here, the digits 25, 10, and 5 are numeric constants used in variable initialization and arithmetic operations. 3. Special Symbols • Special symbols are characters that have a specific meaning or purpose in C. • They are used in expressions, control structures, operators, and program delimiters. • Examples include: +, -, *, /, =, #, {}, [], (), ;, ,, @, etc. Example: float avg = (a + b) / 2.0; printf("Done!"); Here, (), +, /, ;, and " " are special symbols used for grouping, arithmetic, termination, and output formatting. 4. White Spaces • Whitespace characters in C are blank spaces (' '), tab ('t'), and newline ('n'). • They are used to separate tokens and improve readability of the code. Example: int a = 10; // spaces used between tokens printf("Hellon"); // n adds a new line after printing
  • 17.
    Programming in CUnit-1 BCA Semester I 17 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca C Tokens • Token are the smallest individual element of a program that has a specific meaning to the compiler. • During compilation, the compiler breaks the source code into these meaningful units called tokens. • Just like a sentence is made up of words, a C program is made up of tokens. Tokens in C are building blocks which means a program can’t be created without tokens. Types of Tokens in C C language consists of the following types of tokens: 1. Keywords in C • Keywords are pre-defined or reserved words in C that have special meanings and predefined purposes. • C supports total of 32 keywords, these are case-sensitive and written in lower cases, their meaning and functionality are already known to the compiler. • They cannot be used as variable or function names. Examples: int, float, if, else, while, for, return, switch, break, void, etc. Tokens 1.Keywords int, float, if, else, while, for 2.Identifiers sum, totalMarks, Student_Name 3.Constants 78, -53, 0.5, -54, 'A', "BCA" 4.Variables
  • 18.
    Programming in CUnit-1 BCA Semester I 18 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 3. Identifiers in C Identifiers are user-defined names used to identify variables, functions, arrays, or structures. Rules for Identifiers: 1. An identifier can contain letters (A–Z, a–z), digits (0–9), and underscores (_). 2. The first character must be a letter or underscore, not a digit. 3. Identifiers are case-sensitive (e.g., Total and total are different). 4. Keywords (like int, for, return) cannot be used as identifiers. 5. There should be no spaces or special symbols (like @, #, -) in identifiers. 6. The length of an identifier should be reasonable and meaningful. Examples: Valid Identifiers: sum, totalMarks, Student_Name, _average, count1 Invalid Identifiers: 1number (starts with a digit) total marks (contains a space) float (keyword) @value (special character not allowed) 3. Constants in C • Constants are identifiers whose values do not change during the execution of a program, they are also called literals in C. • Constants are often used to represent fixed values like π (pi) or physical quantities such as the charge of an electron.
  • 19.
    Programming in CUnit-1 BCA Semester I 19 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Declaring Constants: (a) Using const keyword: const float pi = 3.14159; Here, pi cannot be changed later in the program. (b) Using #define Preprocessor Directive: #define PI 3.14159 #define SERVICE_TAX 0.12 The compiler replaces each occurrence of PI with 3.14159 before compilation. Rules for #define: 1. Constant names are usually written in capital letters. 2. No space between # and define. 3. Space must be present between define, name, and value. 4. It does not end with a semicolon. Types of Constants in C: i) Integer Constants: • These are whole numbers without any fractional part. • Keyword const int is used declare the integer constants Example: const int marks = 100; // Decimal const int code = 012; // Octal (starts with 0) const int hexValue = 0x7F; // Hexadecimal (starts with x)
  • 20.
    Programming in CUnit-1 BCA Semester I 20 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca ii)Floating Point Constants: • These represent real numbers with fractional parts or exponential forms. • Keyword const float is used declare the floating constants • By default, floating constants are of type double. • To make them float, add suffix F or f. Example: const float pi = 3.14F; const float num=-0.05; const double rate = 1.2E-3; // 1.2x10-3 = 0.0012 const double rate = 1.2E3; // 1.2x103 =1200 iii)Character Constants: • A single character enclosed in single quotes (‘ ’). • Examples: 'A', '5', '@' • These are stored as ASCII values internally. • Keyword const char is used declare the character constants Example: const char grade = 'A'; const char num='5'; iv) String Constants: • A sequence/array of characters enclosed in double quotes (“ ”). • Each string ends with a null character (‘0’) automatically. • Keyword const char[] is used declare the character constants Example: const char str [] = "School"; Length of "India" is 7 (6 characters + 1 null).
  • 21.
    Programming in CUnit-1 BCA Semester I 21 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 4. Variables in C • A variable in C is a named memory location used to store data that can change during program execution. • It acts as a container for values like numbers, characters, or strings. Variable Declaration Syntax: In C, we can declare variables two ways i)data_type variable_name; // Declaration only (no value assigned) int age; // Declaration only float salary; // Declaration only char grade; // Declaration only ii)data_type variable_name = value; // Declaration with initialization int age = 25; // Declares and initializes 'age' with 25 float salary = 5000.50; // Declares and initializes 'salary' with 5000.50 char grade = 'A'; // Declares and initializes 'grade' with 'A Types of Variables in C: In C, variables are classified based on where and how they are declared, which affects their scope, lifetime, and visibility. • Scope: The part of the program where a variable can be accessed. • Lifetime: The duration for which a variable exists in memory. • Visibility: Where the variable name is recognized by the compiler. The 4 types of variables in C are Local, Global, Static, and External.
  • 22.
    Programming in CUnit-1 BCA Semester I 22 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca a) Local Variables • Declared inside a function or block. • Can be used only within that block or function. • Created when the function starts and destroyed when it ends. Example: #include<stdio.h> int main () { int a = 5; // Local variable printf("%d", a); } Output: 5 Scope: Inside the function Lifetime: Function execution time Visibility: Not visible outside the function b) Global Variables • Declared outside all functions. • Can be accessed by all functions in the same program. • Retain their value throughout the program execution. Example: #include <stdio.h> int count = 0; // Global variable void increment() { count++; } int main() { increment(); printf("%d", count); return 0; }
  • 23.
    Programming in CUnit-1 BCA Semester I 23 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Output: 1 Scope: Entire program Lifetime: Till program ends Visibility: Visible to all functions after declaration c) Static Variables • Declared using the keyword static. • Retains its value between multiple function calls. • Has local scope but global lifetime. Example: #include <stdio.h> void demo() { static int x = 0; // Static variable x++; printf("%d ", x); } int main() { demo(); demo(); demo(); return 0; } Output: 1 2 3 Scope: Local to the function Lifetime: Till program ends Visibility: Not visible outside the function
  • 24.
    Programming in CUnit-1 BCA Semester I 24 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca d) External Variables • Declared using the keyword extern to use variables defined in another file. • Allows sharing of global variables across multiple files in large programs. Example (Two files): File1.c int score = 90; File2.c #include <stdio.h> extern int score; // External variable int main() { printf("%d", score); return 0; } Output: 90 Scope: Entire program (across files) Lifetime: Till program ends Visibility: Visible in other files using extern Type Declared Where Scope Lifetime Keyword Local Inside function/block Within that block Function execution — Global Outside all functions Entire program Program end — Static Inside function with static Function Program end static External In another file with extern Across files Program end extern In simple terms: Local = Temporary inside function Global = Accessible everywhere Static = Remembers value External = Shared across files
  • 25.
    Programming in CUnit-1 BCA Semester I 25 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Data Types in C programming • In C programming, a data type defines the type of data a variable can hold. • It tells the compiler how much memory to allocate and what kind of operations can be performed on the data. • They are platform-dependent (e.g., size may vary depending on compiler/architecture). • C data types are mainly divided into three categories: I. Primitive Data Types (Basic/Built-in/Predefined) Primary data types are basic data types supported by the C compiler to store integers, floats, and characters. They include: void, int, char, float, and double. a) void The void data type represents an empty data type. It means “no value” or “nothing.” • Keyword: The void keyword is used when a function does not return any value. • Size: 0 bytes – It does not occupy any memory. • Value Range: Not applicable (no value is stored). Example Declaration: void display(); //Used for functions that do not return a value.
  • 26.
    Programming in CUnit-1 BCA Semester I 26 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca b) Integer (int) The int data type is used to store Integer numbers (both positive and negative) without decimals. • Keyword: The int keyword is used to declare integer variables. • Size: It occupies 2/4bytes (16/32bits) of memory depending on the compiler. • Value Range: For 16-bit → –2¹⁵ to 2¹⁵–1 = –32,768 to 32,767=~±32K For 32-bit → –2³¹ to 2³¹–1 = –2,147,483,648 to 2,147,483,647=~±2.1×109 (Billion) • Format Specifier: %d is used for integer values. Example Declaration: int age = 25; int temp= -10; c) Character (char) The char data type is used to store a single character or small integer value represented by ASCII codes. • Keyword: The char keyword is used to declare character variables. • Size: It occupies 1 byte (8 bits) of memory. • Value Range: –2⁷ to 2⁷–1 = –128 to 127 = ~±128 • Format Specifier: %c is used for character values. Example Declaration: char grade = 'A'; char symbol = '#'; d) Float (float) The float data type is used to store decimal (fractional) numbers with single precision. • Keyword: The float keyword is used to declare floating-point variables. • Size: It occupies 4 bytes (32 bits) of memory.
  • 27.
    Programming in CUnit-1 BCA Semester I 27 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca • Value Range: Approximately ±3.4 × 10³⁸ • Format Specifier: %f is used for float values. Example Declaration: float pi = 3.14f; float marks = 87.56; e) Double (double) The double data type is used to store decimal (fractional) numbers with double precision and higher accuracy. • Keyword: The double keyword is used to declare double-precision floating variables. • Size: It occupies 8 bytes (64 bits) of memory. • Value Range: Approximately ±1.7 × 10³⁰⁸ • Format Specifier: %lf is used for double values. Example Declaration: double salary = 9999.99; double distance = 12345.6789; II. Derived/Secondary Data Types In C programming, Derived Data Types are those that are built upon the primary (basic) data types. These include: Signed and Unsigned • Signed means the variable can hold both positive and negative values. • Unsigned means the variable can hold only non-negative values (0 and above).
  • 28.
    Programming in CUnit-1 BCA Semester I 28 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca By default, most integer types in C are signed unless explicitly declared as unsigned. Data Type Keyword Size (Bytes/Bits) - Value Range Description Example Signed Character signed char 1 byte (8 bits) %d / %c –2⁷ to 2⁷–1 → –128 to 127 Stores small signed character/ASCII values signed char a = -10; Unsigned Character unsigned char 1 byte (8 bits) %u / %c 0 to 2⁸–1 → 0 to 255 Stores only positive character/ASCII values unsigned char b = 250; Signed Short Integer signed short / short 2 bytes (16 bits) %d 215 to 215 –1 →32,768 to 32,767 (~±32K) Small signed integers short s = -32768; Unsigned Short Integer unsigned short 2 bytes (16 bits) %u 0 to 216 –1 →0 to 65,535 (~65K) Small positive integers unsigned short us = 65535; Signed Integer signed int / int 4 bytes (32-bits) %d 2³¹ to 2³¹–1 → (~±2.1×109 (Billion)) Default signed integer int i = -1000; Unsigned Integer unsigned int 4 bytes (32-bits) %u 0 to 232 –1 →0 to 4.2 ×109 (Billion) Large positive integers unsigned int ui = 100000; Signed Long Integer signed long / long 4 bytes (32-bits) %ld 2³¹ to 2³¹–1 → (~±2.1×109 (Billion)) Large signed integers long l = -9999999; Unsigned Long Integer unsigned long 4 bytes (32-bits) %lu 0 to 232 –1 →0 to 4.2 ×109 (Billion) Large unsigned integers unsigned long ul = 5000000; Long Double long double 16 bytes (128-bits) (x64, GCC) %Lf / %Le ±3.4×10−4932 to ±1.1×104932 1 sign + 15 exponent + 112 fraction. Extended precision(quadruple)f loating numbers long double pi = 3.141592653589L; III. User Defined Data Type (UDDT) • UDDT in C are custom data types created by the programmer to represent complex or grouped information. • They allow us to design meaningful data structures beyond basic types like int or char, making programs clearer and easier to manage. 1. Array An array is a collection of similar data items stored in continuous memory locations, accessed using a single name and index. Size of array = number of elements × size of each element
  • 29.
    Programming in CUnit-1 BCA Semester I 29 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example: int a[5] → 5 × 4 = 20 bytes Example with Size #include <stdio.h> int main() { int a[4] = {1, 2, 3, 4}; // Integer array of 4 elements char b[6] = {'A', 'B', 'C', 'D', 'E', 'F'}; // Character array of 6 characters float c[3] = {1.1, 2.2, 3.3}; // Float array of 3 floating-point values printf("Size of int array = %lu bytesn", sizeof(a)); printf("Size of char array = %lu bytesn", sizeof(b)); printf("Size of float array = %lu bytesn", sizeof(c)); return 0; } Output: int = 4 bytes → 4 × 4 = 16 bytes char = 1 byte → 6 × 1 = 6 bytes float = 4 bytes → 3 × 4 = 12 bytes 2. Structure A structure is a user-defined data type used to group different types of data under a single name. Size of structure = sum of sizes of all members + extra bytes (padding may be added) Example: int + float + char → 4 + 4 + 1 = 9 Computer adjusts → 12 bytes
  • 30.
    Programming in CUnit-1 BCA Semester I 30 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example with Size #include <stdio.h> struct Student { int id; float marks; char grade; }; int main() { struct Student s1; printf("Size of structure = %lu bytesn", sizeof(s1)); return 0; } Output: Structure contains: • int → 4 bytes • float → 4 bytes • char → 1 byte + padding (3 bytes for alignment) Total size = 12 bytes Padding is the extra empty bytes added so each data type starts at a memory address that is a multiple of its size (like 2, 4, or 8 bytes) for faster CPU access. 3.Union A union is a user-defined data type where different members share the same memory location, and only one member can hold a value at a time. Size of union = size of the largest member
  • 31.
    Programming in CUnit-1 BCA Semester I 31 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Example: int (4 bytes), float (4 bytes), char (1 byte) Largest = 4 bytes Example with Size #include <stdio.h> union Data { int x; int a[5]; char b[10]; }; int main() { union Data d1; printf("Size of union = %lu bytesn", sizeof(d1)); return 0; } Output: Members in the union: • int x → 4 bytes • int a[5] → 5 × 4 = 20 bytes • char b[10] → 10 × 1 = 10 bytes Largest member = int a[5] = 20 bytes
  • 32.
    Programming in CUnit-1 BCA Semester I 32 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Symbolic Constants • Symbolic constants are named constants used in a C program to make code more readable, maintainable, and meaningful. • They are created using the #define preprocessor directive, and the compiler replaces these names with their actual values during compilation. Syntax: #define CONSTANT_NAME value Features of Symbolic Constants 1. No data type: They do not have a specific data type; they are handled through simple text substitution. 2. Defined using #define: Created before compilation using the preprocessor. 3. Global scope: Once defined, they can be used anywhere in the file after their definition. 4. Improves readability: Replaces confusing numbers with meaningful names. 5. Easy to update: Changing the value in one place updates it throughout the program. Example: #include <stdio.h> #define PI 3.14159 #define MAX 100 #define MESSAGE "Welcome to C programming" int main() { float radius = 5.0; float area = PI * radius * radius; printf("Area of circle: %.2fn", area); printf("Max value allowed: %dn", MAX); printf("%sn", MESSAGE); return 0; }
  • 33.
    Programming in CUnit-1 BCA Semester I 33 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Output: Advantages of Symbolic Constants 1. Symbolic constants make the program easier to read (Example: PI is easier to understand than typing 3.14159 everywhere.) 2. They allow us to change a value in one place only (Example: Change #define MAX 100 to 200 once, and the whole program updates.) 3. They remove repeated numbers in the code (Example: Use LIMIT instead of writing 50 many times.) 4. They reduce typing mistakes and errors (Example: Typing 9.81 many times can cause mistakes; using GRAVITY avoids errors.) 5. They make the program easy to update and maintain (Example: If the tax rate changes, update #define TAX 0.05 once instead of changing everywhere.) Header Files • A header file in C is a file with a .h extension that contains function declarations, macro definitions, constants, and other shared information. • It is included in a program using the #include directive to reuse code and avoid rewriting common functions.
  • 34.
    Programming in CUnit-1 BCA Semester I 34 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca Types of Header Files 1. System Header Files • System header files are the files provided by the C compiler, containing predefined functions and libraries. • They are included in a program using angle brackets < >. Example: #include <stdio.h> 2. User-defined Header Files • User-defined header files are created by programmers to store their own functions, macros, or definitions for reuse. • They are included in a program using double quotes " ". Example: #include "BCA.h" Syntax: #include <header_name.h> // For system-defined header files #include "header_name.h" // For user-defined header files Common System Header Files in C Header File Introduction 5 Common Functions stdio.h Standard Input/Output header; used for reading input and printing output. printf(), scanf(), getchar(), putchar(), gets() conio.h Console I/O header (mostly Turbo C); used for screen handling and character input/output. clrscr(), getch(), getche(), textcolor(), cprintf() math.h Provides mathematical functions like power, root, trigonometry, and logarithm. sqrt(), pow(), sin(), cos(), log(),fmax(),fmin() string.h Used for string handling and manipulation. strlen(), strcpy(), strcat(), strcmp(), strrev() ctype.h Character handling and conversion functions. isalpha(), isdigit(), islower(), isupper(), toupper(),tolower()
  • 35.
    Programming in CUnit-1 BCA Semester I 35 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 1) Standard Input/Output Header (stdio.h) stdio.h is the standard input/output header file in C. It provides functions to read input from the user and display output on the screen. Common stdio.h Functions: Function Purpose Example Input / Output printf() Displays formatted output on the screen printf("Hello, World!n"); Output: Hello, World! scanf() Reads formatted input from the user int num; scanf("%d", &num); Input: 25 → num = 25 getchar() Reads a single character from the keyboard char ch = getchar(); Input: A → ch = A putchar() Prints a single character on the screen putchar('B'); Output: B gets()/fgets() Reads an entire line of text from the user (use fgets() for safety) char str[20]; fgets(str, sizeof(str), stdin); Input: Hello → str = "Hellon" 2.Console Input/Output header file (conio.h) conio.h is a console input/output header file, mainly used in Turbo C. It provides functions for screen handling and reading/writing characters from/to console. Common conio.h Functions: Function Purpose Example Input / Output clrscr() Clears the console screen clrscr(); Clears the screen (no visible output) getch() Reads a single character without displaying it char ch = getch(); Input: A → ch = A (not displayed) getche() Reads a single character and displays it char ch = getche(); Input: B → ch = B (displayed) textcolor() Changes the color of console text textcolor(4); Changes text color to red (depends on compiler) cprintf() Prints formatted output on console cprintf("Hello C World"); Output: Hello C World
  • 36.
    Programming in CUnit-1 BCA Semester I 36 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 3. Mathematical header file (math.h) math.h provides standard mathematical functions for calculations like square root, power, trigonometry, logarithms, and comparisons. Common functions in math.h: Function Purpose Example Output / Result sqrt() Returns the square root of a number double result = sqrt(16); result = 4.0 pow() Returns a number raised to a power double result = pow(2, 3); result = 8.0 sin() Returns the sine of an angle (in radians) double s = sin(3.14/2); s ≈ 1.0 cos() Returns the cosine of an angle (in radians) double c = cos(0); c = 1.0 log() Returns the natural logarithm (base e) of a number double l = log(2.718); l ≈ 1.0 fmax() Returns the maximum of two numbers double m = fmax(5.5, 3.2); m = 5.5 fmin() Returns the minimum of two numbers double n = fmin(5.5, 3.2); n = 3.2 4. String header file (string.h) • The string.h header file in C contains functions used for manipulating and handling strings (which are arrays of characters terminated by a null character '0'). • It includes operations such as finding the length of a string, copying one string to another, comparing strings, and concatenating strings. Common Functions in string.h Function Purpose Example Input / Output strlen() Returns the length of a string int len = strlen("Hello"); len = 5 strcpy() Copies one string into another char dest[10]; strcpy(dest, "Hi"); dest = "Hi" strcat() Concatenates (joins) two strings char str1[20] = "Hello"; strcat(str1, " World"); str1 = "Hello World" strcmp() Compares two strings int res1 = strcmp("abc", "abc"); int res2= strcmp("abc", "ABC"); res1 = 0 (equal) res2 = 1 (not equal) strrev() Reverses the characters of a string (non-standard) char str[] = "Hello"; strrev(str); str = "olleH"
  • 37.
    Programming in CUnit-1 BCA Semester I 37 Notes by Dr. Chandrakantha T S, Vagdevi College of BCA, Melinakuruvalli, Thirthahalli-577 432 📚 For more notes and resources, visit: https://sites.google.com/view/chandrakanthats/bca 5. Character header file (ctype.h) • The ctype.h header file in C provides functions for testing and manipulating individual characters. • It helps to check whether a character is a letter, digit, space, etc., and also convert characters between uppercase and lowercase. Common Functions in ctype.h Function Purpose Example Input / Output (True/False / Result) isalpha() Checks whether a character is an alphabet int res1 = isalpha('A'); int res2 = isalpha('1'); res1 = 1 (true), res2 = 0 (false) isdigit() Checks whether a character is a digit int res1 = isdigit('9'); int res2 = isdigit('a'); res1 = 1 (true), res2 = 0 (false) islower() Checks whether a character is lowercase int res1 = islower('a'); int res2 = islower('Z'); res1 = 1 (true), res2 = 0 (false) isupper() Checks whether a character is uppercase int res1 = isupper('Z'); int res2 = isupper('b'); res1 = 1 (true), res2 = 0 (false) toupper() Converts a lowercase character to uppercase char ch1 = toupper('b'); ch1 = 'B' tolower() Converts an uppercase character to lowercase char ch2 = tolower('B'); Ch2 = 'b', *** ** ***