Unit 1
C
Ms Divya M
Assistant professor
Kristu jayanti deemed to be university
Unit 1: Introduction Overview of C -
Importance of C;
Basic structure of a C program.
Constants, Variables and Data types
C Tokens; Keywords and identifiers; Constants;
Variables; Data types;
Declaration and initialization of variables;
Symbolic constants.
Input and Output: Formatted Input Output function-
scanf(), printf();
Reading and writing characters
3
A computer is an electronic device that takes input (data), processes it
according to a set of instructions (program), and produces output
(information). It can also store data for future use.
Input → Process → Output → Storage
Computer
Hardware
● Definition: The physical, touchable
parts of a computer.
● Examples:
○ Input devices: Keyboard, Mouse
○ Output devices: Monitor, Printer
○ Storage devices: Hard Disk, Pen
Drive
○ Processing unit: CPU,
Motherboard
Software
● Definition: The set of instructions or
programs that tell the hardware what to
do.
● Examples:
○ System Software: Windows, Linux,
macOS
○ Application Software: MS Word,
Web Browser, Games
Operating System
An Operating System is system software that acts as a bridge between the user and
the computer hardware.
It manages hardware, software, and other resources so that they work together
smoothly.
Examples of Operating Systems:
● Windows
● macOS
● Linux
● Android
● iOS
Programming is the process of writing instructions for a computer to follow so it can perform specific
tasks.
It’s like giving step-by-step instructions to a computer in a language it understands.
Programming is done using programming languages (like C, Python, Java).
These instructions are called a program.
A computer follows these instructions exactly, without guessing.
Why Do We Need Programming?
Computers cannot think on their own. They need clear, step-by-step instructions.
Programming helps us:Do calculations,Build websites,Create mobile apps and games,Control robots
or machines,Solve real-world problems
Common Programming Languages:
C ,C++ Advanced version of C (supports OOP) ,Python,Java,JavaScript,HTML/CSS,SQL
Programming
An algorithm is a step-by-step set of
instructions to solve a problem or perform a
task.
It’s like a recipe for the computer –
telling it exactly what to do, step by step.
● Algorithms are written in simple language
(not in a programming language at first).
● They must be clear, correct, and finite
(end after a certain number of steps).
● They help in planning before writing the
actual program.
Example: Algorithm to add two numbers
1. Start
2. Read the first number (A)
3. Read the second number (B)
4. Add A and B, store in SUM
5. Display SUM
6. Stop
Algorithm = Steps
Program = Steps + Programming
Language
9
Flow chart
A flowchart is a diagram that shows the steps of a process or algorithm using symbols and
arrows.
It’s like a map of your program — it shows the flow of instructions from start to end.
Why use flowcharts?
● Easy to understand
● Helps plan before coding
● Shows the sequence and decision points clearly
Common flowchart symbols:
● Oval → Start / End
● Parallelogram → Input / Output
● Rectangle → Process (action or
calculation)
● Diamond → Decision (Yes/No)
● Arrow → Flow of steps
Flow chart
Types of Languages
Computer languages are the ways we communicate instructions to a computer. They can be classified
into three main types:
1. Machine Language
● Definition: The lowest-level language, written in binary (0s and 1s).
● Features:
○ Directly understood by the computer.
○ Very fast, but hard for humans to read or write.
● Example: 10110000 01100001
2. Assembly Language
● Definition: Uses short codes or mnemonics instead of binary.
● Features:
○ Easier than machine language but still low-level.
○ Requires an assembler to convert to machine code.
● Example: MOV A, 5
3. High-Level Language (HLL)
● Definition: Uses English-like statements, easy for humans to read and write.
● Features:
○ Portable across computers.
○ Needs a compiler or interpreter to translate into machine code.
Examples: C, Python, Java
C is called a middle-level language because it has features of both low-level (close to
hardware) and high-level (close to human language) programming languages.
Why C is considered middle-level:
1. Low-Level Features (like Assembly):
● Can directly access and manipulate hardware using pointers.
● Allows bitwise operations.
● Can write device drivers, operating systems, and embedded programs.
2. High-Level Features (like Python, Java):
● Uses English-like syntax (e.g., if, for, while).
● Supports modular programming with functions.
● Has rich libraries for input/output, math, strings, etc.
COMPILER AND
interpreter
COMPILER AND
interpreter
Compiler and Interpreter are both language translators — they convert programs written in
high-level languages into machine language so the computer can understand and execute
them.
1. Compiler
● Definition: Translates the entire program into machine code all at once before execution.
● Execution speed: Fast (because translation happens only once).
● Error handling: Shows all errors together after compiling.
● Examples: C, C++ use compilers.
2. Interpreter
● Definition: Translates the program line by line and executes it immediately.
● Execution speed: Slower (because it translates during execution).
● Error handling: Stops at the first error and shows it immediately.
● Examples: Python, JavaScript use interpreters.
COMPILER AND
interpreter
Feature Compiler Interpreter
Translation style Entire program at once One line at a time
Execution speed Faster Slower
Error display All errors at once Stops at first error
Memory usage More (stores compiled file) Less
Examples C, C++ Python, JavaScript
Steps in writing a program
1. Analyzing the Problem
2. Algorithm design / Pseudo Code
3. Flowchart
4. Coding
5. Debugging
6. Testing
7. Final output
8. Documentation
ASCII American Standard Code for Information Interchange.
It’s a character encoding standard that assigns a unique numerical value (from 0 to 127) to letters, digits,
punctuation marks, and control characters.
● Purpose: It allows computers to represent and communicate text using numbers.
● Type: 7-bit code (though stored in 8 bits in most systems, with the extra bit unused or used for extended
characters).
● Example:
○ A → 65 in decimal → 01000001 in binary
○ a → 97 in decimal → 01100001 in binary
○ Space → 32 in decimal → 00100000 in binary
Categories of ASCII characters
● Control characters (0–31): Non-printable, used for text formatting or device control (e.g., n = newline, t
= tab).
● Printable characters (32–126): Letters, digits, punctuation, and symbols.
● DEL (127): Delete character.
20
C programming language was developed 1972 by Dennis Ritchie in
bell laboratories
Its an offspring of Basic combined programming called b which
was developed by Ken Thomson
B language was interpreter based but it was very slow.
So Dennis Ritchie modified the B language and named it as C
INTRODUCTION
Dennis Ritchie
Assigning values to variables
Defining symbolic constants.
Input and Output: Input and
output statement
Reading a character
Writing characters
Formatted input and output
statement
Overview of C
Importance of C
Basic structure of a C program.
Constants, Variables and Data
types
C tokens;
Keywords and identifiers
Declaration of variables
Key Features of C:
● Simple & Efficient → Small set of keywords, fast execution.
● Procedural → Programs are organized into functions.
● Portable → Can run on different machines with little or no change.
● Low-level Access → Can directly interact with hardware (like Assembly).
● Rich Library → Built-in functions for input/output, math, strings, etc.
● Structured Language → Encourages breaking problems into smaller parts
(modular programming).
Procedural Programming
● Definition: A programming style where the
focus is on writing procedures (functions) that
operate on data.
● Approach: Step-by-step instructions telling the
computer what to do and how to do it.
● Structure: May or may not use a clear
program structure; can have goto statements,
which make the program flow jump around.
● Example Languages: C, Pascal, BASIC (early
versions).
● Drawback: Large programs can become
difficult to manage if structure is not well
maintained.
Structured Programming
● Definition: A subset of procedural
programming that emphasizes a clear, logical
structure using control structures like
sequence, selection, and iteration.
● Approach: Breaks a program into small,
manageable blocks (modules) without using
goto.
● Structure: Uses loops (for, while), decision-
making (if, switch), and functions for better
readability and maintenance.
● Example Languages: C, Ada, Python (when
used in structured way).
● Advantage: Easier to debug, test, and
maintain; encourages top-down design.
Top-Down Approach
The Top-Down Approach is a problem-solving and program design method where you start with the main problem
and break it down into smaller, more manageable sub-problems, until each one is simple enough to solve directly.
How it works:
1. Start with the overall problem (big picture).
2. Divide it into major tasks (modules).
3. Break each module into smaller sub-tasks.
4. Continue breaking down until you reach simple, clear steps that can be directly implemented in code.
Advantages:
● Easy to understand and manage.
● Encourages modular programming (each part can be developed separately).
● Easier to debug and maintain.
Disadvantages:
● May require changes in all levels if there’s a change in the higher-level design.
● Sometimes harder to estimate time for each sub-task in advance.
Compilation and execution of c program
C Source Code
● You start by writing your program in C language, usually saved with a .c extension (e.g., program1.c).
Preprocessing
● This step handles all the lines starting with #, like #include, #define, etc.
● It includes header files, expands macros, and removes comments.
● Output: C Source After Preprocessing
Compilation
● The compiler takes the preprocessed code and translates it into assembly language.
● Syntax errors are checked at this stage.
● Output: Assembly Code
Assembler
● The assembler converts the assembly code into object code (machine-readable format).
● Output: Object Code (usually .obj or .o file)
Linker
● The linker takes object code and combines it with required libraries (standard or user-defined
functions).
● All function calls (like printf, scanf) are linked with actual definitions from libraries.
● Output: Final Machine Code (Executable file)
Loader
● The loader loads the executable file into primary memory (RAM).
● It prepares the program to run by allocating memory and setting up environment.
Primary Memory (RAM)
● This is where the program gets executed.
● The CPU fetches instructions from RAM and runs the program.
Step Tool File type Description
Source
Code
Text Editor .c Written by
programmer
Preproces
sing
Compiler .i (temp) Handles macros and
includes
Compilatio
n
Compiler .s (temp) Converts to assembly
Assembly Assembler .o or .obj Converts to object
code
Linking Linker .exe Creates executable
file
Execution OS Output Runs and displays
output
Basic structure of c
programming
What is #include?
● #include is a preprocessor directive in C.
● It tells the C preprocessor to include the contents of another file (usually a header file) into the
current program before compilation starts.
● It is not a C statement; it doesn’t end with a semicolon ;
#include → A preprocessor directive (not a C statement).
What is stdio.h?
● Stands for Standard Input/Output Header.
● Contains declarations (prototypes) of commonly used I/O functions such as:
○ printf() → to display output.
○ scanf() → to take input.
○ getchar() / putchar() → to read/write single characters.
○ gets() / puts() → to read/write strings.
What is .h in C?
● .h is a file extension for header files in C.
● Header files usually contain function declarations, macros, constants, and sometimes structure
definitions.
● They are included in programs using #include
Examples of Standard Header Files in C
● stdio.h → Standard Input/Output (printf, scanf, etc.)
● string.h → String handling functions (strlen, strcpy, etc.)
● math.h → Mathematical functions (sqrt, pow, etc.)
● stdlib.h → Utility functions (malloc, free, exit, etc.)
● ctype.h → Character handling (isdigit, isalpha, etc.)
#include <stdio.h>
#include <conio.h>
int main() {
clrscr(); // Clears the screen
printf("Welcome to C
programming in Turbo C!");
getch(); // Waits for a key press
return 0;
}
clrscr(); – Clears the output screen (Turbo C feature).
getch(); – Waits for a key press so the output screen doesn't close immediately.
int main() – Correct, standard form for the main function.
Turbo C requires conio.h for clrscr() and getch().
#include <stdio.h> // 1. Preprocessor
Directive
int main() { // 2. Main Function
// 3. Variable Declaration (optional)
printf("Hello, World!"); // 4.
Statement / Function Call
return 0; // 5. Return Statement
}
What is int main() in C?
● main() is the entry point of every C program.
● Program execution always starts from the main() function.
● The keyword int before main means the function returns an integer value
to the operating system after program execution.
int → return type of main.
● return 0; usually means the program ran successfully.
● Returning a non-zero value often indicates an error.
main → name of the function. Special in C because execution starts here.
() → parentheses can have arguments (parameters).
● int main(void) → no parameters.
● int main(int argc, char *argv[]) → command-line arguments.
What is void main()?
● void means no return value.
● void main() tells the compiler that main will not return anything to the operating system.
● Some old compilers (like Turbo C/C++) allowed void main()
•Preprocessor Directives: These are commands that provide instructions to the
preprocessor. They are written at the beginning of the program and usually involve including
header files, such as #include <stdio.h> for standard input/output functions.
•Main Function: This is the entry point of a C program. Every C program must have a main()
function, which is where the execution of the program begins.
•Variable Declaration: Variables used in the program are declared inside the main function or
globally outside it, based on scope requirements.
•Statements/Expressions: The main logic of the program is written inside the main() function
using statements and expressions. Ex : { } braces,Functions etc
•Return Statement: The main() function typically ends with a return statement, which indicates
the program's termination and can return a value to the operating system, typically return 0; for
successful execution.
cOMPONENTS OF c
LANGUAGE
The four main components of C language
are:
1. The character set
2. Tokens
3. Variables
4. Data types
The C Character Set
Character set is set of valid characters that a language can recognise. A character represents any letter,
digit, or any other sign that can be used in a program.
Category Character Set
Lowercase & Uppercase Letters a-z, A to Z
Digits 0-9
Special Characters ,.;:`?!&^*-+<>()|~-$?[]()%#=@
White Spaces Tab, space, newline
TOKENS
A token is the smallest element of a program that is
meaningful to the compiler. Tokens can be classified as
follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
KEYWORDS
1. Keywords are reserved words in C that have special meaning to
the compiler.
2. They cannot be used as Identifier because they are part of the
language syntax.
3. Keywords are built-in so no need to use or include any library to use
them.
4. Keywords are having a fixed meaning and a programmer can’t
change them.
5. Keywords are Case sensitive , int is valid, but Int or INT is not considered
a keyword.
6. The C99 standard defines 32 keywords.
KEYWORDS
auto double int struct
break else long switch
case enum register
typedef
char extern return union
const float short
unsigned
continue for signed void
default goto sizeof
IDENTIFIER
A C identifier is a name used to identify a variable, function, or any other user-defined
item.
An identifier must starts with a letter A to Z or a to z or an underscore _ followed by zero or
more
An identifier Can include letters, underscores, and digits (0 to 9).
An identifier Cannot start with a digit
C does not allow punctuation characters such as @, $
Identifier cannot use , and % , C keyword within identifiers.
C is a case sensitive programming language.
CONSTANT
In C programming, const is a keyword used to declare a variable as constant, meaning its value
cannot be changed after it is initialized. It is mainly used to protect variables from being
accidentally modified, making the program safer and easier to understand. These constants can
be of various types, such as integer, floating-point, string, or character constants.
#include <stdio.h>
int main() {
// Defining constant
variable
const int a = 10;
printf("%d", a);
return 0;
}
CONSTANT
C supports two broad types of constants:
1. Primary Constants
2. Secondary Constants
Primary Constants
These are the most commonly used fixed values.
Type Example Description
Integer Constant 10, -25, 0 Whole numbers (positive or
negative)
Floating Constant 3.14, -0.99 Decimal numbers
Character Constant 'A', '5', '#' A single character in single quotes
String Constant "Hello", "123" Group of characters in double quotes
CONSTANT
Secondary Constants
These are more advanced constants.
Type Example Description
Array of constants const int marks[3] = {90, 80, 70}; List of constant
values
Pointer to constant const int *ptr = &value; Pointer that cannot modify value
Constant pointer int *const ptr = &value; Pointer address
cannot change
Enumerated constant (enum) enum days {MON, TUE, WED}; List of fixed symbolic
values
Defined constant #define PI 3.14 Value set using
preprocessor
CONSTANT - Integral literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for
hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix
can be uppercase or lowercase and can be in any order.
Examples:
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
CONSTANT - Floating Point literals
A floating-point literal has an integer part, a decimal point, a fractional part,
and an exponent part. You can represent floating point literals either in
decimal form or exponential form.
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
CONSTANT - Character literals
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., 't').
A string literal is a sequence of characters enclosed in double quotes (" ") in C.
It represents a constant string value that cannot be changed during program
execution.
A string contains characters that are similar to character literals: plain characters,
escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them
using white spaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, 
CONSTANT - String literals
VARIABLE
A variable in C is a named memory location used to store a value that can be changed during program
execution. It acts as a container for data.
Rules for using Variables
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be applied
to the variable.
The name of a variable can be composed of letters, digits, and the underscore character.
It must begin with either a letter or an underscore.
Upper and lowercase letters are distinct because C is case-sensitive.
There are following basic variable types −
int age = 25;
float temperature = 36.5;
char grade = 'A';
Assigning Values to Variables in C
Once a variable is declared, a value can be assigned to it using the assignment
operator (=). The assignment can be done either at the time of declaration or later in
the code.
Syntax: Example:
variable_name = value;
int age;
age = 25; // Assigning value after declaration
float salary = 50000.50; // Declaration and assignment together
char grade = 'A';
Declaration of Variables in C
In C, a variable must be declared before it is used. The declaration involves
specifying the data type of the variable followed by its name. Variables can be
declared individually or in groups.
int age;
float salary;
char grade;
Local Variable
● Declared inside a function or
block ({ }).
● Accessible only within that
function or block.
● Created when the function is called
and destroyed when the function
ends.
#include <stdio.h>
void demo() {
int x = 10; // local variable
printf("Local x = %dn", x);
}
int main() {
demo();
// printf("%d", x); // Error: x
not accessible here
return 0;
}
Global Variable
Declared outside all
functions (usually at the
top of the program).
Accessible by all
functions in the program.
Exists throughout the
program’s execution.
#include <stdio.h>
int g = 20; // global variable
void demo() {
printf("Global g in demo() = %dn",
g);
}
int main() {
printf("Global g in main() = %dn",
g);
demo();
return 0;
}
Static Variable in C
● A static variable is a variable that retains its value between multiple function
calls.
● It is declared using the keyword static.
● Scope depends on where it is declared:
○ Inside a function → acts like a local variable but keeps its value across calls.
○ Outside functions → works like a global variable but is accessible only within
that file.
Automatic Variable in C
● An automatic variable is the default type of local variable in C.
● Declared inside a function or block { }.
● Keyword: auto (but usually not needed, because by default variables are
automatic).
● Created when the function is called, destroyed when the function ends.
● Stored in stack memory.
● Default value → garbage (undefined) if not initialized.
External Variable in C
● An external variable is a global variable declared outside of all functions.
● Keyword: extern.
● They can be shared across multiple files in large projects.
● By default, variables declared outside functions are global and act as external variables.
● Declared outside all functions.
● Scope → accessible from any function (and even other files using extern).
● Lifetime → exists throughout the program execution.
● Default value → 0 if not initialized.
In C, a string is a sequence of characters terminated by a null character ('0'). Unlike other
languages, C does not have a built-in string type—strings are implemented as arrays of
characters.
char name[10]; // Declaration
char name[10] = "Alice"; // Initialization
char name[] = "Alice"; // Size auto-calculated (6: 5 letters + '0')
char name[] = {'A','l','i','c','e','0'}; // Same as above
Null Character ('0')
● It is used to mark the end of the string.
● Without it, C won't know where the string ends in memory.
STRING
Function Purpose Example
strlen(str) Returns length of string strlen("Hello") 5
→
strcpy(s1, s2) Copies s2 into s1 strcpy(name, "Alice");
strcat(s1, s2) Appends s2 to end of s1 strcat(greet, name);
strcmp(s1, s2) Compares two strings (returns 0 if equal) strcmp("a", "b") -1
→
strrev(s) Reverses the string (non-standard) Often supported in Turbo C
Strings are character arrays ending with '0'.
Use <string.h> for operations like copy, compare, concatenate, length.
Always manage array size carefully to avoid overflow.
STRING
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[20] = "World";
char result[40];
strcpy(result, str1); // result = "Hello"
strcat(result, " "); // result = "Hello "
strcat(result, str2); // result = "Hello World"
printf("Combined: %sn", result);
printf("Length: %lun", strlen(result));
return 0;
}
STRING
DATA TYPES
Data types in C define the type of data a variable can store, along with its size, range, and
the set of valid operations.
INT DATA TYPE
The integer datatype in C is used to store the integer numbers (any number
including positive, negative and zero without decimal part). Octal values,
hexadecimal values, and decimal values can also be stored in int data type in C.
● Range: -2,147,483,648 to 2,147,483,647
● Size: 4 bytes
● Format Specifier: %d
int main() {
int var = 22;
printf("var = %d", var);
return 0;
}
CHAR DATA TYPE
Character data type allows its variable to store only a single character.
The size of the character is 1 byte. It is the most basic data type in C. It
stores a single character and requires a single byte of memory in
almost all compilers.
● Range: (-128 to 127) or (0 to 255)
● Size: 1 byte
● Format Specifier: %c
#include <stdio.h>
int main() {
char ch = 'A';
printf("ch = %c", ch);
return 0;
}
In C programming, float data type is used to store single precision floating-point
values. These values are decimal and exponential numbers.
● Range: 1.2E-38 to 3.4E+38
● Size: 4 bytes
● Format Specifier: %f
#include <stdio.h>
int main() {
float val = 12.45;
printf("val = %f", val);
return 0;
}
FLOAT DATA TYPE
The double data type in C is used to store decimal numbers (numbers with
floating point values) with double precision. It can easily accommodate about
16 to 17 digits after or before a decimal point.
● Range: 1.7E-308 to 1.7E+308
● Size: 8 bytes
● Format Specifier: %lf
DOUBLE DATA TYPE
Size of Data Types in C
The size of the data types in C is dependent on the size of the architecture, so
we cannot define the universal size of the data types. For that, the C language
provides the sizeof() operator to check the size of the data types.
Type Description Size (on most systems) Example
int Integer values 2 or 4 bytes int age = 25;
float Single-precision decimal numbers 4 bytes float price = 45.5;
double Double-precision decimal numbers 8 bytes double pi = 3.14159;
char Single character 1 byte char grade = 'A';
Type Description Example
void Represents absence of value/return type void display();
Basic (Primitive) Data Types
Void Type
Derived Data Types
Type Description Example
Array Collection of same type elements int marks[5];
Pointer Stores address of another variable int *ptr;
Function Returns a value int sum(int a, int b);
Structure Collection of different data types struct student { int id; char name[20]; };
Union Like structure but shares memory union data { int i; float f; };
Type Description Example
enu
m
User-defined named integer constants enum days {SUN, MON, TUE};
Enumeration Data Types
Modifier Use with Description
short int Small-range integers
long int, double Large-range values
signed int, char Default, supports negative & positive
unsigned int, char Only positive values, wider positive range
Type Modifiers
}Formatted I/O functions are used to take various
inputs from the user and display multiple outputs to
the user.
}These types of I/O functions can help to display the
output to the user in different formats using the
format specifiers.
Input and Output: Formatted Input Output function
Format Specifiers in C
In C language, format specifiers are used in
input and output functions (such as printf()
and scanf() to define the type of data being
handled.
printf() function is used in a C program to display any value like float,
integer, character, string, etc on the console screen.
It is a pre-defined function that is already declared in the
stdio.h(header file).
Syntax 1:
To display any variable value.
printf(“Format Specifier”, var1, var2, …., varn);
printf()
scanf() function is used in the C program for reading or taking any
value from the keyboard by the user, these values can be of any data
type like integer, float, character, string, and many more.
This function is declared in stdio.h(header file), that’s why it is also a
pre-defined function.
In scanf() function we use &(address-of operator) which is used to
store the variable value on the memory location of that variable.
scanf(“Format Specifier”, &var1, &var2, …., &varn);
scanf()
Reading and Writing Characters
getchar() – Read a Single Character
● Reads one character from the user.
Example:
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c", ch);
(In C programming, getch() is often used at the end of a program (especially in Turbo C or old compilers like Borland C) to make
the output window stay open until the user presses a key.)
int main()
{
int character;
character = getchar();
printf("The entered character is :
%c", character);
return 0;
}
Input : f
Output : The entered character is f
getch() and getche() (from <conio.h>)
● getch() → Reads a character without displaying it on the screen.
● getche() → Reads a character and displays it immediately.
gets() and puts() (for strings – but gets() is unsafe, better to use fgets())
● gets(str) → Reads a string until newline (deprecated, use fgets() instead).
● puts(str) → Displays a string followed by a newline.
Example:
char name[20];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // safer than gets()
puts("Your name is:");
puts(name);
putchar() – Write a Single Character
● Displays one character on the screen.
Example:
char ch = 'A';
putchar(ch);
putchar() → standard C function (in <stdio.h>) → works on all compilers.
putch() → non-standard function (in <conio.h>) → works only in some old compilers like Turbo C.
int main()
{
int character;
printf("Enter any random character between a-z:
");
character = getchar();
printf("The entered character is : ");
putchar(character);
return 0;
}
Enter any random character between a-z: k
The entered character is : k
storage classes define how variables are stored, their scope (where they can be
accessed), their lifetime (how long they exist in memory), and their default initial
value.
Scope → Where the variable is accessible.
Lifetime → How long the variable exists in memory.
Default value → If no value is assigned.
Storage location → Where it is stored (CPU register or RAM).
Storage Classes
#include <stdio.h>
int main() {
auto int x = 10; // same as "int x
= 10;"
printf("%d", x);
return 0;
}
1. auto
● Default storage class for local variables inside a function.
● Exists only during function execution (local scope).
● Stored in memory (RAM).
● Default value: Garbage (uninitialized).
static
● Keeps the variable alive throughout the program, even if it is inside a function.
● Scope: Local to the function/block, but value is retained between function calls.
● Default value: 0.
#include <stdio.h>
void demo() {
static int count = 0; // initialized only once
count++;
printf("%dn", count);
}
int main() {
demo(); // prints 1
demo(); // prints 2
demo(); // prints 3
return 0;
}
1
2
3
3. extern
● Declares a variable that is defined in another file or scope.
● Used for global variables to share across multiple files.
● Default value: 0.
● extern does not allocate memory; it only declares the variable.
// file1.c
#include <stdio.h>
int num = 10; // global variable
// file2.c
#include <stdio.h>
extern int num; // refers to variable from
file1.c
int main() {
printf("%d", num);
return 0;
}
register
● Suggests the compiler to store the variable in a CPU register (for faster access).
● Scope: Local to the block/function.
● Default value: Garbage (if uninitialized).
● Cannot use & (address-of operator) on register variables.
#include <stdio.h>
int main() {
register int i;
for(i = 1; i <= 5; i++) {
printf("%d ", i);
}
return 0;
}
register is a storage class in C.
It tells the compiler:
“Try to keep this variable in the CPU register
instead of RAM, because it will be used a
lot.”
This makes accessing i faster, especially
inside loops.
You cannot take the address of a register
variable (so &i is not allowed).
1 2 3 4 5
Storage
Class
Scope Lifetime Default
Value
Storage Location
auto Local Function
execution
Garbage RAM
static Local (but value persists) /
Global
Entire
program
0 RAM
extern Global (across files) Entire
program
0 RAM
register Local Function
execution
Garbage CPU Register (if
available)
86
Thank
You!

Unit 1 : Introduction Overview of C;

  • 1.
    Unit 1 C Ms DivyaM Assistant professor Kristu jayanti deemed to be university
  • 2.
    Unit 1: IntroductionOverview of C - Importance of C; Basic structure of a C program. Constants, Variables and Data types C Tokens; Keywords and identifiers; Constants; Variables; Data types; Declaration and initialization of variables; Symbolic constants. Input and Output: Formatted Input Output function- scanf(), printf(); Reading and writing characters
  • 3.
    3 A computer isan electronic device that takes input (data), processes it according to a set of instructions (program), and produces output (information). It can also store data for future use. Input → Process → Output → Storage Computer
  • 4.
    Hardware ● Definition: Thephysical, touchable parts of a computer. ● Examples: ○ Input devices: Keyboard, Mouse ○ Output devices: Monitor, Printer ○ Storage devices: Hard Disk, Pen Drive ○ Processing unit: CPU, Motherboard
  • 5.
    Software ● Definition: Theset of instructions or programs that tell the hardware what to do. ● Examples: ○ System Software: Windows, Linux, macOS ○ Application Software: MS Word, Web Browser, Games
  • 6.
    Operating System An OperatingSystem is system software that acts as a bridge between the user and the computer hardware. It manages hardware, software, and other resources so that they work together smoothly. Examples of Operating Systems: ● Windows ● macOS ● Linux ● Android ● iOS
  • 7.
    Programming is theprocess of writing instructions for a computer to follow so it can perform specific tasks. It’s like giving step-by-step instructions to a computer in a language it understands. Programming is done using programming languages (like C, Python, Java). These instructions are called a program. A computer follows these instructions exactly, without guessing. Why Do We Need Programming? Computers cannot think on their own. They need clear, step-by-step instructions. Programming helps us:Do calculations,Build websites,Create mobile apps and games,Control robots or machines,Solve real-world problems Common Programming Languages: C ,C++ Advanced version of C (supports OOP) ,Python,Java,JavaScript,HTML/CSS,SQL Programming
  • 8.
    An algorithm isa step-by-step set of instructions to solve a problem or perform a task. It’s like a recipe for the computer – telling it exactly what to do, step by step. ● Algorithms are written in simple language (not in a programming language at first). ● They must be clear, correct, and finite (end after a certain number of steps). ● They help in planning before writing the actual program. Example: Algorithm to add two numbers 1. Start 2. Read the first number (A) 3. Read the second number (B) 4. Add A and B, store in SUM 5. Display SUM 6. Stop Algorithm = Steps Program = Steps + Programming Language
  • 9.
    9 Flow chart A flowchartis a diagram that shows the steps of a process or algorithm using symbols and arrows. It’s like a map of your program — it shows the flow of instructions from start to end. Why use flowcharts? ● Easy to understand ● Helps plan before coding ● Shows the sequence and decision points clearly Common flowchart symbols: ● Oval → Start / End ● Parallelogram → Input / Output ● Rectangle → Process (action or calculation) ● Diamond → Decision (Yes/No) ● Arrow → Flow of steps
  • 10.
  • 11.
    Types of Languages Computerlanguages are the ways we communicate instructions to a computer. They can be classified into three main types: 1. Machine Language ● Definition: The lowest-level language, written in binary (0s and 1s). ● Features: ○ Directly understood by the computer. ○ Very fast, but hard for humans to read or write. ● Example: 10110000 01100001
  • 12.
    2. Assembly Language ●Definition: Uses short codes or mnemonics instead of binary. ● Features: ○ Easier than machine language but still low-level. ○ Requires an assembler to convert to machine code. ● Example: MOV A, 5 3. High-Level Language (HLL) ● Definition: Uses English-like statements, easy for humans to read and write. ● Features: ○ Portable across computers. ○ Needs a compiler or interpreter to translate into machine code. Examples: C, Python, Java
  • 13.
    C is calleda middle-level language because it has features of both low-level (close to hardware) and high-level (close to human language) programming languages. Why C is considered middle-level: 1. Low-Level Features (like Assembly): ● Can directly access and manipulate hardware using pointers. ● Allows bitwise operations. ● Can write device drivers, operating systems, and embedded programs. 2. High-Level Features (like Python, Java): ● Uses English-like syntax (e.g., if, for, while). ● Supports modular programming with functions. ● Has rich libraries for input/output, math, strings, etc.
  • 15.
  • 16.
    COMPILER AND interpreter Compiler andInterpreter are both language translators — they convert programs written in high-level languages into machine language so the computer can understand and execute them. 1. Compiler ● Definition: Translates the entire program into machine code all at once before execution. ● Execution speed: Fast (because translation happens only once). ● Error handling: Shows all errors together after compiling. ● Examples: C, C++ use compilers. 2. Interpreter ● Definition: Translates the program line by line and executes it immediately. ● Execution speed: Slower (because it translates during execution). ● Error handling: Stops at the first error and shows it immediately. ● Examples: Python, JavaScript use interpreters.
  • 17.
    COMPILER AND interpreter Feature CompilerInterpreter Translation style Entire program at once One line at a time Execution speed Faster Slower Error display All errors at once Stops at first error Memory usage More (stores compiled file) Less Examples C, C++ Python, JavaScript
  • 18.
    Steps in writinga program 1. Analyzing the Problem 2. Algorithm design / Pseudo Code 3. Flowchart 4. Coding 5. Debugging 6. Testing 7. Final output 8. Documentation
  • 19.
    ASCII American StandardCode for Information Interchange. It’s a character encoding standard that assigns a unique numerical value (from 0 to 127) to letters, digits, punctuation marks, and control characters. ● Purpose: It allows computers to represent and communicate text using numbers. ● Type: 7-bit code (though stored in 8 bits in most systems, with the extra bit unused or used for extended characters). ● Example: ○ A → 65 in decimal → 01000001 in binary ○ a → 97 in decimal → 01100001 in binary ○ Space → 32 in decimal → 00100000 in binary Categories of ASCII characters ● Control characters (0–31): Non-printable, used for text formatting or device control (e.g., n = newline, t = tab). ● Printable characters (32–126): Letters, digits, punctuation, and symbols. ● DEL (127): Delete character.
  • 20.
    20 C programming languagewas developed 1972 by Dennis Ritchie in bell laboratories Its an offspring of Basic combined programming called b which was developed by Ken Thomson B language was interpreter based but it was very slow. So Dennis Ritchie modified the B language and named it as C INTRODUCTION
  • 21.
  • 22.
    Assigning values tovariables Defining symbolic constants. Input and Output: Input and output statement Reading a character Writing characters Formatted input and output statement Overview of C Importance of C Basic structure of a C program. Constants, Variables and Data types C tokens; Keywords and identifiers Declaration of variables
  • 23.
    Key Features ofC: ● Simple & Efficient → Small set of keywords, fast execution. ● Procedural → Programs are organized into functions. ● Portable → Can run on different machines with little or no change. ● Low-level Access → Can directly interact with hardware (like Assembly). ● Rich Library → Built-in functions for input/output, math, strings, etc. ● Structured Language → Encourages breaking problems into smaller parts (modular programming).
  • 24.
    Procedural Programming ● Definition:A programming style where the focus is on writing procedures (functions) that operate on data. ● Approach: Step-by-step instructions telling the computer what to do and how to do it. ● Structure: May or may not use a clear program structure; can have goto statements, which make the program flow jump around. ● Example Languages: C, Pascal, BASIC (early versions). ● Drawback: Large programs can become difficult to manage if structure is not well maintained. Structured Programming ● Definition: A subset of procedural programming that emphasizes a clear, logical structure using control structures like sequence, selection, and iteration. ● Approach: Breaks a program into small, manageable blocks (modules) without using goto. ● Structure: Uses loops (for, while), decision- making (if, switch), and functions for better readability and maintenance. ● Example Languages: C, Ada, Python (when used in structured way). ● Advantage: Easier to debug, test, and maintain; encourages top-down design.
  • 25.
    Top-Down Approach The Top-DownApproach is a problem-solving and program design method where you start with the main problem and break it down into smaller, more manageable sub-problems, until each one is simple enough to solve directly. How it works: 1. Start with the overall problem (big picture). 2. Divide it into major tasks (modules). 3. Break each module into smaller sub-tasks. 4. Continue breaking down until you reach simple, clear steps that can be directly implemented in code. Advantages: ● Easy to understand and manage. ● Encourages modular programming (each part can be developed separately). ● Easier to debug and maintain. Disadvantages: ● May require changes in all levels if there’s a change in the higher-level design. ● Sometimes harder to estimate time for each sub-task in advance.
  • 26.
  • 27.
    C Source Code ●You start by writing your program in C language, usually saved with a .c extension (e.g., program1.c). Preprocessing ● This step handles all the lines starting with #, like #include, #define, etc. ● It includes header files, expands macros, and removes comments. ● Output: C Source After Preprocessing Compilation ● The compiler takes the preprocessed code and translates it into assembly language. ● Syntax errors are checked at this stage. ● Output: Assembly Code Assembler ● The assembler converts the assembly code into object code (machine-readable format). ● Output: Object Code (usually .obj or .o file)
  • 28.
    Linker ● The linkertakes object code and combines it with required libraries (standard or user-defined functions). ● All function calls (like printf, scanf) are linked with actual definitions from libraries. ● Output: Final Machine Code (Executable file) Loader ● The loader loads the executable file into primary memory (RAM). ● It prepares the program to run by allocating memory and setting up environment. Primary Memory (RAM) ● This is where the program gets executed. ● The CPU fetches instructions from RAM and runs the program.
  • 29.
    Step Tool Filetype Description Source Code Text Editor .c Written by programmer Preproces sing Compiler .i (temp) Handles macros and includes Compilatio n Compiler .s (temp) Converts to assembly Assembly Assembler .o or .obj Converts to object code Linking Linker .exe Creates executable file Execution OS Output Runs and displays output
  • 30.
    Basic structure ofc programming
  • 31.
    What is #include? ●#include is a preprocessor directive in C. ● It tells the C preprocessor to include the contents of another file (usually a header file) into the current program before compilation starts. ● It is not a C statement; it doesn’t end with a semicolon ; #include → A preprocessor directive (not a C statement). What is stdio.h? ● Stands for Standard Input/Output Header. ● Contains declarations (prototypes) of commonly used I/O functions such as: ○ printf() → to display output. ○ scanf() → to take input. ○ getchar() / putchar() → to read/write single characters. ○ gets() / puts() → to read/write strings.
  • 32.
    What is .hin C? ● .h is a file extension for header files in C. ● Header files usually contain function declarations, macros, constants, and sometimes structure definitions. ● They are included in programs using #include Examples of Standard Header Files in C ● stdio.h → Standard Input/Output (printf, scanf, etc.) ● string.h → String handling functions (strlen, strcpy, etc.) ● math.h → Mathematical functions (sqrt, pow, etc.) ● stdlib.h → Utility functions (malloc, free, exit, etc.) ● ctype.h → Character handling (isdigit, isalpha, etc.)
  • 34.
    #include <stdio.h> #include <conio.h> intmain() { clrscr(); // Clears the screen printf("Welcome to C programming in Turbo C!"); getch(); // Waits for a key press return 0; } clrscr(); – Clears the output screen (Turbo C feature). getch(); – Waits for a key press so the output screen doesn't close immediately. int main() – Correct, standard form for the main function. Turbo C requires conio.h for clrscr() and getch(). #include <stdio.h> // 1. Preprocessor Directive int main() { // 2. Main Function // 3. Variable Declaration (optional) printf("Hello, World!"); // 4. Statement / Function Call return 0; // 5. Return Statement }
  • 35.
    What is intmain() in C? ● main() is the entry point of every C program. ● Program execution always starts from the main() function. ● The keyword int before main means the function returns an integer value to the operating system after program execution. int → return type of main. ● return 0; usually means the program ran successfully. ● Returning a non-zero value often indicates an error. main → name of the function. Special in C because execution starts here. () → parentheses can have arguments (parameters). ● int main(void) → no parameters. ● int main(int argc, char *argv[]) → command-line arguments.
  • 36.
    What is voidmain()? ● void means no return value. ● void main() tells the compiler that main will not return anything to the operating system. ● Some old compilers (like Turbo C/C++) allowed void main()
  • 37.
    •Preprocessor Directives: Theseare commands that provide instructions to the preprocessor. They are written at the beginning of the program and usually involve including header files, such as #include <stdio.h> for standard input/output functions. •Main Function: This is the entry point of a C program. Every C program must have a main() function, which is where the execution of the program begins. •Variable Declaration: Variables used in the program are declared inside the main function or globally outside it, based on scope requirements. •Statements/Expressions: The main logic of the program is written inside the main() function using statements and expressions. Ex : { } braces,Functions etc •Return Statement: The main() function typically ends with a return statement, which indicates the program's termination and can return a value to the operating system, typically return 0; for successful execution.
  • 38.
    cOMPONENTS OF c LANGUAGE Thefour main components of C language are: 1. The character set 2. Tokens 3. Variables 4. Data types
  • 39.
    The C CharacterSet Character set is set of valid characters that a language can recognise. A character represents any letter, digit, or any other sign that can be used in a program. Category Character Set Lowercase & Uppercase Letters a-z, A to Z Digits 0-9 Special Characters ,.;:`?!&^*-+<>()|~-$?[]()%#=@ White Spaces Tab, space, newline
  • 40.
    TOKENS A token isthe smallest element of a program that is meaningful to the compiler. Tokens can be classified as follows: 1. Keywords 2. Identifiers 3. Constants 4. Strings 5. Special Symbols 6. Operators
  • 41.
    KEYWORDS 1. Keywords arereserved words in C that have special meaning to the compiler. 2. They cannot be used as Identifier because they are part of the language syntax. 3. Keywords are built-in so no need to use or include any library to use them. 4. Keywords are having a fixed meaning and a programmer can’t change them. 5. Keywords are Case sensitive , int is valid, but Int or INT is not considered a keyword. 6. The C99 standard defines 32 keywords.
  • 42.
    KEYWORDS auto double intstruct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof
  • 43.
    IDENTIFIER A C identifieris a name used to identify a variable, function, or any other user-defined item. An identifier must starts with a letter A to Z or a to z or an underscore _ followed by zero or more An identifier Can include letters, underscores, and digits (0 to 9). An identifier Cannot start with a digit C does not allow punctuation characters such as @, $ Identifier cannot use , and % , C keyword within identifiers. C is a case sensitive programming language.
  • 44.
    CONSTANT In C programming,const is a keyword used to declare a variable as constant, meaning its value cannot be changed after it is initialized. It is mainly used to protect variables from being accidentally modified, making the program safer and easier to understand. These constants can be of various types, such as integer, floating-point, string, or character constants. #include <stdio.h> int main() { // Defining constant variable const int a = 10; printf("%d", a); return 0; }
  • 45.
    CONSTANT C supports twobroad types of constants: 1. Primary Constants 2. Secondary Constants Primary Constants These are the most commonly used fixed values. Type Example Description Integer Constant 10, -25, 0 Whole numbers (positive or negative) Floating Constant 3.14, -0.99 Decimal numbers Character Constant 'A', '5', '#' A single character in single quotes String Constant "Hello", "123" Group of characters in double quotes
  • 46.
    CONSTANT Secondary Constants These aremore advanced constants. Type Example Description Array of constants const int marks[3] = {90, 80, 70}; List of constant values Pointer to constant const int *ptr = &value; Pointer that cannot modify value Constant pointer int *const ptr = &value; Pointer address cannot change Enumerated constant (enum) enum days {MON, TUE, WED}; List of fixed symbolic values Defined constant #define PI 3.14 Value set using preprocessor
  • 47.
    CONSTANT - Integralliterals An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order. Examples: 85 /* decimal */ 0213 /* octal */ 0x4b /* hexadecimal */ 30 /* int */ 30u /* unsigned int */ 30l /* long */ 30ul /* unsigned long */
  • 48.
    CONSTANT - FloatingPoint literals A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form. 3.14159 /* Legal */ 314159E-5L /* Legal */ 510E /* Illegal: incomplete exponent */ 210f /* Illegal: no decimal or exponent */ .e55 /* Illegal: missing integer or fraction */
  • 49.
    CONSTANT - Characterliterals Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., 't').
  • 50.
    A string literalis a sequence of characters enclosed in double quotes (" ") in C. It represents a constant string value that cannot be changed during program execution. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters. You can break a long line into multiple lines using string literals and separating them using white spaces. Here are some examples of string literals. All the three forms are identical strings. "hello, dear" "hello, CONSTANT - String literals
  • 51.
    VARIABLE A variable inC is a named memory location used to store a value that can be changed during program execution. It acts as a container for data. Rules for using Variables A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive. There are following basic variable types − int age = 25; float temperature = 36.5; char grade = 'A';
  • 53.
    Assigning Values toVariables in C Once a variable is declared, a value can be assigned to it using the assignment operator (=). The assignment can be done either at the time of declaration or later in the code. Syntax: Example: variable_name = value; int age; age = 25; // Assigning value after declaration float salary = 50000.50; // Declaration and assignment together char grade = 'A';
  • 54.
    Declaration of Variablesin C In C, a variable must be declared before it is used. The declaration involves specifying the data type of the variable followed by its name. Variables can be declared individually or in groups. int age; float salary; char grade;
  • 55.
    Local Variable ● Declaredinside a function or block ({ }). ● Accessible only within that function or block. ● Created when the function is called and destroyed when the function ends. #include <stdio.h> void demo() { int x = 10; // local variable printf("Local x = %dn", x); } int main() { demo(); // printf("%d", x); // Error: x not accessible here return 0; }
  • 56.
    Global Variable Declared outsideall functions (usually at the top of the program). Accessible by all functions in the program. Exists throughout the program’s execution. #include <stdio.h> int g = 20; // global variable void demo() { printf("Global g in demo() = %dn", g); } int main() { printf("Global g in main() = %dn", g); demo(); return 0; }
  • 57.
    Static Variable inC ● A static variable is a variable that retains its value between multiple function calls. ● It is declared using the keyword static. ● Scope depends on where it is declared: ○ Inside a function → acts like a local variable but keeps its value across calls. ○ Outside functions → works like a global variable but is accessible only within that file.
  • 58.
    Automatic Variable inC ● An automatic variable is the default type of local variable in C. ● Declared inside a function or block { }. ● Keyword: auto (but usually not needed, because by default variables are automatic). ● Created when the function is called, destroyed when the function ends. ● Stored in stack memory. ● Default value → garbage (undefined) if not initialized.
  • 59.
    External Variable inC ● An external variable is a global variable declared outside of all functions. ● Keyword: extern. ● They can be shared across multiple files in large projects. ● By default, variables declared outside functions are global and act as external variables. ● Declared outside all functions. ● Scope → accessible from any function (and even other files using extern). ● Lifetime → exists throughout the program execution. ● Default value → 0 if not initialized.
  • 60.
    In C, astring is a sequence of characters terminated by a null character ('0'). Unlike other languages, C does not have a built-in string type—strings are implemented as arrays of characters. char name[10]; // Declaration char name[10] = "Alice"; // Initialization char name[] = "Alice"; // Size auto-calculated (6: 5 letters + '0') char name[] = {'A','l','i','c','e','0'}; // Same as above Null Character ('0') ● It is used to mark the end of the string. ● Without it, C won't know where the string ends in memory. STRING
  • 61.
    Function Purpose Example strlen(str)Returns length of string strlen("Hello") 5 → strcpy(s1, s2) Copies s2 into s1 strcpy(name, "Alice"); strcat(s1, s2) Appends s2 to end of s1 strcat(greet, name); strcmp(s1, s2) Compares two strings (returns 0 if equal) strcmp("a", "b") -1 → strrev(s) Reverses the string (non-standard) Often supported in Turbo C Strings are character arrays ending with '0'. Use <string.h> for operations like copy, compare, concatenate, length. Always manage array size carefully to avoid overflow. STRING
  • 62.
    #include <stdio.h> #include <string.h> intmain() { char str1[20] = "Hello"; char str2[20] = "World"; char result[40]; strcpy(result, str1); // result = "Hello" strcat(result, " "); // result = "Hello " strcat(result, str2); // result = "Hello World" printf("Combined: %sn", result); printf("Length: %lun", strlen(result)); return 0; } STRING
  • 63.
    DATA TYPES Data typesin C define the type of data a variable can store, along with its size, range, and the set of valid operations.
  • 64.
    INT DATA TYPE Theinteger datatype in C is used to store the integer numbers (any number including positive, negative and zero without decimal part). Octal values, hexadecimal values, and decimal values can also be stored in int data type in C. ● Range: -2,147,483,648 to 2,147,483,647 ● Size: 4 bytes ● Format Specifier: %d int main() { int var = 22; printf("var = %d", var); return 0; }
  • 65.
    CHAR DATA TYPE Characterdata type allows its variable to store only a single character. The size of the character is 1 byte. It is the most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers. ● Range: (-128 to 127) or (0 to 255) ● Size: 1 byte ● Format Specifier: %c #include <stdio.h> int main() { char ch = 'A'; printf("ch = %c", ch); return 0; }
  • 66.
    In C programming,float data type is used to store single precision floating-point values. These values are decimal and exponential numbers. ● Range: 1.2E-38 to 3.4E+38 ● Size: 4 bytes ● Format Specifier: %f #include <stdio.h> int main() { float val = 12.45; printf("val = %f", val); return 0; } FLOAT DATA TYPE
  • 67.
    The double datatype in C is used to store decimal numbers (numbers with floating point values) with double precision. It can easily accommodate about 16 to 17 digits after or before a decimal point. ● Range: 1.7E-308 to 1.7E+308 ● Size: 8 bytes ● Format Specifier: %lf DOUBLE DATA TYPE
  • 68.
    Size of DataTypes in C The size of the data types in C is dependent on the size of the architecture, so we cannot define the universal size of the data types. For that, the C language provides the sizeof() operator to check the size of the data types.
  • 69.
    Type Description Size(on most systems) Example int Integer values 2 or 4 bytes int age = 25; float Single-precision decimal numbers 4 bytes float price = 45.5; double Double-precision decimal numbers 8 bytes double pi = 3.14159; char Single character 1 byte char grade = 'A'; Type Description Example void Represents absence of value/return type void display(); Basic (Primitive) Data Types Void Type
  • 70.
    Derived Data Types TypeDescription Example Array Collection of same type elements int marks[5]; Pointer Stores address of another variable int *ptr; Function Returns a value int sum(int a, int b); Structure Collection of different data types struct student { int id; char name[20]; }; Union Like structure but shares memory union data { int i; float f; }; Type Description Example enu m User-defined named integer constants enum days {SUN, MON, TUE}; Enumeration Data Types
  • 71.
    Modifier Use withDescription short int Small-range integers long int, double Large-range values signed int, char Default, supports negative & positive unsigned int, char Only positive values, wider positive range Type Modifiers
  • 72.
    }Formatted I/O functionsare used to take various inputs from the user and display multiple outputs to the user. }These types of I/O functions can help to display the output to the user in different formats using the format specifiers. Input and Output: Formatted Input Output function
  • 73.
    Format Specifiers inC In C language, format specifiers are used in input and output functions (such as printf() and scanf() to define the type of data being handled.
  • 75.
    printf() function isused in a C program to display any value like float, integer, character, string, etc on the console screen. It is a pre-defined function that is already declared in the stdio.h(header file). Syntax 1: To display any variable value. printf(“Format Specifier”, var1, var2, …., varn); printf()
  • 76.
    scanf() function isused in the C program for reading or taking any value from the keyboard by the user, these values can be of any data type like integer, float, character, string, and many more. This function is declared in stdio.h(header file), that’s why it is also a pre-defined function. In scanf() function we use &(address-of operator) which is used to store the variable value on the memory location of that variable. scanf(“Format Specifier”, &var1, &var2, …., &varn); scanf()
  • 77.
    Reading and WritingCharacters getchar() – Read a Single Character ● Reads one character from the user. Example: char ch; printf("Enter a character: "); ch = getchar(); printf("You entered: %c", ch); (In C programming, getch() is often used at the end of a program (especially in Turbo C or old compilers like Borland C) to make the output window stay open until the user presses a key.) int main() { int character; character = getchar(); printf("The entered character is : %c", character); return 0; } Input : f Output : The entered character is f
  • 78.
    getch() and getche()(from <conio.h>) ● getch() → Reads a character without displaying it on the screen. ● getche() → Reads a character and displays it immediately. gets() and puts() (for strings – but gets() is unsafe, better to use fgets()) ● gets(str) → Reads a string until newline (deprecated, use fgets() instead). ● puts(str) → Displays a string followed by a newline. Example: char name[20]; printf("Enter your name: "); fgets(name, sizeof(name), stdin); // safer than gets() puts("Your name is:"); puts(name);
  • 79.
    putchar() – Writea Single Character ● Displays one character on the screen. Example: char ch = 'A'; putchar(ch); putchar() → standard C function (in <stdio.h>) → works on all compilers. putch() → non-standard function (in <conio.h>) → works only in some old compilers like Turbo C. int main() { int character; printf("Enter any random character between a-z: "); character = getchar(); printf("The entered character is : "); putchar(character); return 0; } Enter any random character between a-z: k The entered character is : k
  • 80.
    storage classes definehow variables are stored, their scope (where they can be accessed), their lifetime (how long they exist in memory), and their default initial value. Scope → Where the variable is accessible. Lifetime → How long the variable exists in memory. Default value → If no value is assigned. Storage location → Where it is stored (CPU register or RAM). Storage Classes
  • 81.
    #include <stdio.h> int main(){ auto int x = 10; // same as "int x = 10;" printf("%d", x); return 0; } 1. auto ● Default storage class for local variables inside a function. ● Exists only during function execution (local scope). ● Stored in memory (RAM). ● Default value: Garbage (uninitialized).
  • 82.
    static ● Keeps thevariable alive throughout the program, even if it is inside a function. ● Scope: Local to the function/block, but value is retained between function calls. ● Default value: 0. #include <stdio.h> void demo() { static int count = 0; // initialized only once count++; printf("%dn", count); } int main() { demo(); // prints 1 demo(); // prints 2 demo(); // prints 3 return 0; } 1 2 3
  • 83.
    3. extern ● Declaresa variable that is defined in another file or scope. ● Used for global variables to share across multiple files. ● Default value: 0. ● extern does not allocate memory; it only declares the variable. // file1.c #include <stdio.h> int num = 10; // global variable // file2.c #include <stdio.h> extern int num; // refers to variable from file1.c int main() { printf("%d", num); return 0; }
  • 84.
    register ● Suggests thecompiler to store the variable in a CPU register (for faster access). ● Scope: Local to the block/function. ● Default value: Garbage (if uninitialized). ● Cannot use & (address-of operator) on register variables. #include <stdio.h> int main() { register int i; for(i = 1; i <= 5; i++) { printf("%d ", i); } return 0; } register is a storage class in C. It tells the compiler: “Try to keep this variable in the CPU register instead of RAM, because it will be used a lot.” This makes accessing i faster, especially inside loops. You cannot take the address of a register variable (so &i is not allowed). 1 2 3 4 5
  • 85.
    Storage Class Scope Lifetime Default Value StorageLocation auto Local Function execution Garbage RAM static Local (but value persists) / Global Entire program 0 RAM extern Global (across files) Entire program 0 RAM register Local Function execution Garbage CPU Register (if available)
  • 86.