Module1
Module1
Dr. R N Shetty
Founder
1928 - forever
VISION
To be a global leader in imparting Cyber Security education, research
& development and empowering young minds to safeguard the digital
world.
Mission
1. Empower students with Cyber Security essentials through hands-on facilities
and a strong ethical foundation.
2. Facilitate collaborative learning environment, teamwork, and global
certifications for real-time challenges.
3. Drive innovation in Cyber Security through state-of-the-art research,
fostering a culture of exploration throughhigher learning and
entrepreneurship.
4. Promote students to possess qualities of interpersonal, interdisciplinary,
leadership, and societal responsibilities.
DISCUSSION
AGENDA
01 Syllabus
03 Prerequisites
04 Introduction
Textbooks:
1. Computer fundamentals and programming in c, “Reema Thareja”, Oxford University, Second edition,
2017.
Reference Books:
E. Balaguruswamy, Programming in ANSI C, 7th Edition, Tata McGraw-Hill. 2. Brian W. Kernighan and Dennis
M. Ritchie, The ‘C’ Programming Language, Prentice Hall of India.
INTRODUCTION
Computer is an advanced electronic device that takes raw data as an input from the user and
processes it under the control of a set of instructions (called program), produces a result
(output), and saves it for future use.
Advantages :
Size reduced The very fast
Disadvantages :
They over heated quickly
Maintenance problems
GENERATIONS OF COMPUTERS
Notebook: -
These computers are as powerful as desktop but size of these computers
are comparatively smaller than laptop and desktop. They weigh 2 to 3 kg.
They are more costly than laptop.
COMPUTER CLASSIFICATION
Palmtop (Hand held): -
They are also called as personal Digital Assistant (PDA). These computers are
small in size. They can be held in hands. It is capable of doing word
processing, spreadsheets and hand writing recognition, GAME
playing, faxing and paging. These computers are not as powerful as desktop computers.
Wearable computer: -
The size of this computer is very small so that it can be worn on the
body. It has smaller processing power. It is used in the field of
medicine. For example pace maker to correct the heart beats.
COMPUTER CLASSIFICATION
Workstation:
A powerful, single-user computer. A workstation is like a personal computer, but it has a more
powerful microprocessor and a higher-quality monitor.
Workstations are more powerful
and higher in performance than
desktop computers, especially
with respect to CPU and
Graphics, memory capacity and
multitasking capability.
COMPUTER CLASSIFICATION
Minicomputer
A class of multi-user Computer that lies between the largest Multi-user systems (mainframe computer) and
the smallest Microcomputers or personal computers.
Mainframe computers are used to run
commercial applications and other large-
scale computing purposes.
It is also used in banking and insurance
businesses.
For example millions of records , each day.
COMPUTER CLASSIFICATION
Mainframe
Mainframe computers can support hundreds or thousands of users, handling massive amounts of
input, output, and storage.
Mainframe computers are used in large
organizations where many users need
access to shared data and programs.
Mainframes are also used as e-commerce
servers, handling transactions over the
Internet.
COMPUTER CLASSIFICATION
Super computer
Computer which are designed for scientific job like whether forecasting and artificial intelligence etc. They
are fastest and expensive. A super computer contains a number of CPU which operate in parallel to make
it faster. It also known as grand father computer.
Application – whether forecasting, weapons research and development.
DATA / INFORMATION
#include <stdio.h>
int main()
{
char ch; // variable declaration
printf("Enter a character");
scanf("%c", &ch); // user input
printf("\n The ascii value of the ch variable is : %d", ch);
return 0;
}
38
UNITS OF DATA
⮚The data represented can be grouped or measured using following units:
Units of Data
➢Bit = 0 or 1
➢Nibble = 4 bits
➢Byte = 8 bits
➢Kilobyte = 1024 bytes
➢Megabyte = 1024 Kilobytes
➢Gigabytes = 1024 Megabytes
➢Terabytes = 1024 Gigabytes
BITS, BYTES AND WORDS
What is a bit?
Bit is short for 'binary digit.' It's a single digit in a binary number, and it can be either 1 or 0.
What is a byte?
A byte is 8 bits. That's the definition. With 8 bits you can store any number between 0 and 255,
since there are 256 different combinations of 1 and 0 to choose from.
What is a word?
You often hear about 32-bit or 64-bit computer architectures. A word is basically the number of
bits a particular computer's CPU can deal with in one go. It varies depending on the computer
architecture you're using.
Convert 80GB into bytes.
1GB = 1024MB
80 GB = 80 * 1024 MB
80 GB = 80 * 1024 * 1024KB
80 GB = 80 * 1024 * 1024 * 1024 bytes
80 GB = 85,899,345,920 bytes
• What is a word?
A word is a unit of information.
Word is usually an even multiple of bytes such as 2/4/8/16 bytes etc. depending on word length of
computer.
example: for 16-bit machine ,1 word = 16-bits = 2 bytes.
for 32-bit machine, 1 word =32 bits = 4 bytes
for 64 bit machine, 1 word = 64 bits = 8 bytes
Understanding Computer
Memory Types
Computer memory is essential. It stores and retrieves information. This impacts
speed and multitasking. Overall system performance is affected. Memory is
categorized by access, volatility, and function.
by likkitha Renukappa
Random Access Memory (RAM)
Definition Example
Volatile memory allows any-order data access. DDR5 RAM (up to 8400 MHz).
Function Fact
Primary memory for running programs. RAM speed affects loading times.
Types
Definition
Uses hard drive as RAM
Drawbacks
extension. Slower due to disk access.
2 3
1 4
Function
Used in SSDs, USB drives, memory cards.
Types
NAND and NOR flash options.
NVMe SSDs have speeds up to 7000 MB/s. SSDs replaced HDDs for speed.
Memory Hierarchy
Arranges memory by speed, cost, and capacity. CPU checks levels for data.
Future Trends in Computer
Memory
3D ReRAM
XPoint High speed, low power.
HBM
Stacked DRAM.
Hardware Software
General Purpose
Application Specific
What's Inside Your Computer?
Demystifying the hardware that makes your computer tick. From basic input/output
to processing power and storage. This is an overview of essential computer
components.
by likkitha Renukappa
The CPU: The Brains
Instructions Clock Speed Manufacturers
The CPU executes instructions and Clock speed and cores impact performance. Intel and AMD dominate the CPU market.
performs calculations. performance.
3 Ideal Amounts
Choose RAM based on your needs: 8GB, 16GB, or 32GB+.
Storage: Where Data Lives
Central Hub
Connects all computer components.
Chipset
Determines compatibility and features.
Expansion Slots
PCIe slots for graphics cards.
1 Dedicated
2 Integrated
Key Metrics
3
VRAM, clock speed are important.
Examples: NVIDIA GeForce RTX 4080 and AMD Radeon RX 7900 XTX.
PSU: Keeping the Lights On
Wattage
AC to DC
1 Choose the right PSU for your system.
Converts AC power to DC. 2 system.
Modular 4 Efficiency
Cable management considerations.
3 80+ Bronze, Silver, Gold, and more.
Putting It All Together
Data Flow Compatibility
Input -> CPU -> RAM -> Component compatibility matters.
Storage/Output. matters.
Upgrading
Consider the benefits of upgrading.
Hardware Software
Software Hardware
Application
System Software Software
Hardware Software
Computer consists of
INPUT DEVICES
An input device is any hardware device that sends data to a computer, allowing you to interact with and
control it.
The most commonly used or primary input devices on a computer are the keyboard and mouse. However,
there are other devices that input data into a computer.
Types of input devices
INPUT DEVICES
CENTRAL PROCESSING UNIT
CPU Components
The CPU is comprised of three main parts
ALU(Arithmetic Logic Unit)
Control Unit(CU)
Registers: Stores the data that is to be executed next.
Memory unit stores the data, instructions, intermediate results and output, temporarily,
during the processing of data.
This memory is also called the main memory or primary memory of the computer.
Another kind of storage unit is also referred to as the secondary memory of the
computer.
The data, the programs and the output are stored permanently in the storage unit of
the computer. Magnetic disks, optical disks and magnetic tapes are examples of
secondary memory.
MEMORY
Primary Memory
RAM:
Random Access Memory: is a memory scheme within the computer system responsible for storing data on
a temporary basis, so that it can be promptly accessed by the processor as and when needed.
It is volatile in nature, which means that data will be erased once supply to the storage device is turned
off.
RAM stores data randomly and the processor accesses these data randomly from the RAM storage.
ROM:
ROM (Read Only Memory): ROM is a permanent form of storage. ROM stays active regardless of
whether power supply to it is turned on or off.
ROM devices do not allow data stored on them to be modified.
MEMORY
Secondary Memory
Stores data and programs permanently its retained after the power is turned off. It is a
non-volatile memory.
It provides back-up storage for data and instructions. Hard disk drive, floppy drive and
optical disk drives are some examples of storage devices.
The data and instructions that are currently not being used by CPU, but may be required
later for processing, are stored in secondary memory.
Secondary memory has a high storage capacity than the primary memory.
Secondary memory is also cheaper than the primary memory.
It takes longer time to access the data and instructions stored in secondary memory than
in primary memory.
MEMORY
Main Examples
1.Hard Disk
2.Optical Disk
3.Flash memory
Hard Disk
Also called as Disk drive or HDD
stores and provides relatively quick access to large amounts of data.
Stores data on an electromagnetically charged surface or set of surfaces.
Optical Disk & Flash
An optical disc drive(ODD) is a disk drive that use laser light to store data.
There are three main types of optical media: CD, DVD, and Blu-ray disc
MEMORY
Flash Disk
A storage module made of flash memory chips.
A Flash disks have no mechanical platters or access arms, but the term "disk" is used because
the data are accessed as if they were on a hard drive. The disk storage structure is emulated.
Floppy diskette
Represented by a small rectangular plastic case containing a thin magnetic disk.
They offer the capacity of 1.2 MB to 1.44MB.
OUTPUT DEVICES
Output device receives information from the CPU and presents it to the user in the desired form.
The processed data, stored in the memory of the computer is sent to the output unit, which then converts it
into a form that can be understood by the user.
The output is usually produced in one of the two ways – on the display device, or on paper (hard copy).
Monitor:
Monitor is an output device that resembles the television screen.
It may use a Cathode Ray Tube (CRT) to display information. The monitor is associated with a keyboard
for manual input of characters and displays the information as it is keyed in.
It also displays the program or application output. Like the television, monitors are also available in
different sizes.
OUTPUT DEVICES
Printer
Printer is a device that outputs text and graphics information obtained from the computer and prints it on to a
paper.
Printers are available in the market in a variety of size, speed, sophistication, and cost.
Dot matrix printer:
A dot matrix printer prints characters and images of all types as a pattern of dots.
It has a print head (or hammer) that consists of pins representing the character or image.
The print head runs back and forth, or in an up and down motion, on the page and prints by striking an ink-soaked
cloth ribbon against the paper, much like the print mechanism on a typewriter.
Line printer
Line printer is a high speed impact printer in which one typed line is printed at a time.
The speed of a line printer usually varies from 600 to 1200 lines-per-minute or approximately 10 to 20 pages per
minute.
OUTPUT DEVICES
INKJET PRINTERS
In inkjet printers, the print head has several tiny nozzles, also called jets.
As the paper moves past the print head, the nozzles spray ink onto it, forming the characters and images.
The dots are extremely small (usually between 50 and 60 microns in diameter) and are positioned very
precisely, with resolutions of up to 1440x720 dots per inch
LASER PRINTER:
It is a non-impact printer that works at a very high speed and produces high quality text and graphics.
It uses the photocopier technology. When a document is sent to the printer, a laser beam "draws" the
document on a drum (which is coated with a photo-conductive material) using electrical charges.
After the drum is charged, it is rolled in toner (a dry powder type of ink).
OUTPUT DEVICES
PLOTTER
A plotter is used to print vector graphics with a high print quality.
They are widely used to draw maps, in scientific applications and
in applications like CAD, CAM and CAE
OUTPUT DEVICES
Output Devices
PORTS AND CONNECTORS
Devices like scanners and printers are connected through the points called as ports.
All ports are connected to the mother board of the computer but are visible from outside.
The following are the ports that are commonly used.
Universal Serial Bus (USB) They have replaced serial and parallel ports in the motherboard.
Computers are provided with at least 4 USB ports to support scanner, printer and mouse.
Current USB ports are capable of transferring 1 GB file in 20 Seconds.
PROGRAMMING LANGUAGES
Program: The set of instructions given to the computer to achieve a specific task is called program.
Programming: The process of providing instructions to solve a specific problem is called programming.
Programming Language: The language that is used to write a program is called programming language.
There are mainly 3 types of programming languages.
1) Machine level language
This is the language of computers. It is set of instructions which are given to the computer in the form of 0’s
and 1’s.
Program execution is very fast.
Difficult to read and write machine language programs.
PROGRAMMING LANGUAGES
2) Assembly level language
It is also called as Symbolic language. The set of instructions are given to the computer in the
form of symbolic names.
Easy to remember, easy to write as compared to machine language.
Ex: ADD R1,R2
MUL R1, R2
There is a need of translator to translate assembly language into machine language.
Assembler: Assembler is a translator which translates the program written in assembly
language into the machine language.
PROGRAMMING LANGUAGES
3) High level language
It is written using symbols and words just like English language.
It is easy to read, write and maintain.
Ex: ‘C’ is a programming language.
It takes more time to execute when compared with machine or assembly language.
Compiler: The compiler is a translator which accepts the program written in high-level language and
produces the corresponding machine language program (machine code).
INTRODUCTION TO C
PROGRAMMING
C is a programming language. It was developed at AT&T's Bell Laboratories of USA in 1972.
It was designed and written by “Dennis Ritchie”. It is being used on several different software platforms.
Characteristics of C
C is a Robust language.
It is considered as a High-level language.
C is a Core language as many other programming languages (such as C++, Java or Perl) are based on C.
Portable language.
Suited for Structured programming.
Extensible language.
The Enduring Importance of C
Programming
C is a foundational language powering much of modern technology. It
remains relevant in operating systems, embedded systems, and high-
performance applications. Understanding C's key advantages is crucial in
the 21st century.
C's Role in Operating Systems
Core Foundation Linux Kernel Hardware Access
C forms the core of operating systems About 95% of the Linux kernel is C enables direct hardware access for
like Linux, Windows, and macOS written in C, enabling efficient efficiency and control in OS functions.
kernels. memory management.
The Android OS, built on the Linux kernel, owes its performance to C programming.
C in Embedded Systems and IOT
3 Mature Libraries
Libraries like BLAS and LAPACK offer optimized numerical
computation.
Game engines like Unreal Engine and Unity use C/C++ for core
components and physics engines.
C as a Foundation for Languages
2 Active Community
Open-source projects drive continuous development.
Modern Updates 3
Ongoing standards address modern challenges (C11, C17).
Career Opportunities
There's high demand and good salaries.
UNIX was originally written in C, setting a The Linux kernel is predominantly C. The C allows for low-level hardware control
setting a precedent for OS development. The Windows kernel has significant portions crucial for OS functions like memory
development. portions in C as well. management.
Embedded Systems: Controlling
Controlling the Physical World
World
1 Dominant Language 2 Performance
C provides the necessary
C is the dominant language in performance and resource
embedded systems control.
programming.
3 Wide Usage
Used in microcontrollers in cars, appliances, and industrial equipment.
equipment.
Game Development:
Performance Matters
Game Engines Optimized Sections
Game engines like Unity and Performance-critical sections
Unreal Engine rely on C/C++. optimized with C for speed.
Console Creation
Many games and consoles are created using C or C++.
Databases: Efficient Data Management
Speed
2 C's speed is essential for database
performance.
DBMS in C
1
Database management systems (DBMS)
(DBMS) are often written in C.
Memory Control
C provides precise control over memory.
3 memory.
Compilers: Building Languages
Languages with C
Many Compilers
Many compilers are written in C, including GCC.
Manipulate Memory
C's ability to directly manipulate memory is crucial.
Efficient Code
Parsers and code generators leverage C's features.
Networking: Foundation of
Internet Infrastructure
1 Networking Protocols
Networking protocols built using C for control.
2 TCP/IP Stacks
C allows control over network packets and sockets.
3 Web Servers
Apache and Nginx use C for critical modules.
C's Lasting Legacy
C remains a powerful and relevant language with influence in software and
and applications. Understanding C provides insight into architecture and
programming. It continues to be a valuable skill for software engineers.
APPLICATIONS OF C
Common consumer devices like microwave ovens, washing machines and digital cameras are
consisting of many programs which are written in C language.
Several professional 3D computer games and many popular gaming frameworks have been
built using C language.
FUNDAMENTALS OF PROBLEM SOLVING
Problem Solving is the process of working through the details of a problem to reach a solution.
There are three approaches to problem solving:
1. Algorithm
2. Flowchart
3. Pseudo Code
Algorithm
The algorithm is a ‘step-by-step procedure’ to be followed in solving a problem.
In order to qualify as an algorithm, a sequence of instructions must possess following
characteristics:
a. Definiteness: Instructions must be precise and unambiguous. i.e., each and every instruction
should be clear and should have only one meaning.
b. Finiteness: Not even a single instruction must be repeated infinitely. i.e., each instruction
should be clear and performed in finite time.
c. Termination: After the algorithm gets executed, the user should get the desired result.
ALGORITHM
i. Sequence: Sequence means that each step of the Algorithm is executed in the specified order.
ii. Decision: Decision statements are used when the outcome of process depends on some
condition.
iii. Repetition: Repetition involves executing one or more steps for a number of times can be
implemented using while, do-while, for loops.
ALGORITHM
Example:
1. Write an algorithm to compute the simple interest.
Step 1: [Initialize]
Start
Step 2: [Input the values of P, T, R]
Read P, T, R
Step 3: [Compute the Simple Interest]
SI= (P*T*R)/100
Step 4: [Display the Simple Interest]
Print SI
Step 5: [Finished] Stop
FLOWCHARTS
A flowchart is a “graphical or symbolic” representation of an algorithm.
Flowcharts used to design and develop complex programs to help the users to visualize the logic
of the program or better understanding of the program.
The symbols used to write flowcharts are given below:
Rectangle- Computational steps (used while assigning and calculating some results)
Small Circle- Continuation from one point in the process flow to another
Arrows- the flowchart direction and connects the various flow chart symbols.
FLOWCHARTS
Advantages of Flowcharts
They act as a guide or blueprint for the programmer to code the solution in any programming language.
It helps programmers to understand the logic of complicated and lengthy problems.
They help to analyse the problem in a more effective manner.
Flowchart can be used to debug programs that have error(s).
Limitations of Flowcharts
Drawing flowcharts is a laborious and time consuming activity.
Flowchart of a complex program becomes complex and clumsy.
A little bit of alteration in the solution may require complete redrawing of the flowchart.
The essentials of what is done may get lost in the technical details of how it is done.
There are no well-defined standards that limit the details that must be incorporated in a flow chart.
PSEUDO CODE
“Pseudo code is nothing but a series of steps to solve a given problem written using a mixture
of English language and C like language.”
Pseudo code consists of statements which are a combination of English and C. It is not quite ‘C’
code but can be translated.
Pseudo code is an outline of a program that can easily be converted into programming
language.
Flowcharts can be considered as graphical alternatives to pseudo codes but requires more
space on paper.
KEY DIFFERENCES BETWEEN ALGORITHM AND PSEUDOCODE
• The algorithm uses high-level constructs meaning the snippet of code but the pseudo code
involves natural language with high-level programming builds.
Start
Steps Input P, T, R
Start
1. Input P, T, R SI = (P * T * R) / 100
2. SI = (P * T * R)/100
3. Print SI Print SI
Stop
Stop
PSUEDO CODE TO FIND SIMPLE INTEREST.
• Step 1: start
• Step 2 : Read the three input quantities P, N and R.
• Step 3 : Calculate simple interest as Simple interest = P* N* R/100
• Step 4: Print simple interest.
• Step 5: Stop.
Input an integer n and check whether it is odd or even
Steps
Start
Start
Input n Input n
If n%2 = 0
Print “Even” N%2= No Print “Odd”
0?
Else Print “Odd”
Yes
Stop Print “Even”
Stop
Find the biggest of 3 numbers
Steps Start A
Start
Input a, b, c Input a, b, c No
c > big ?
big = a
If b > big Yes
big = b big = a
If c > big big = c
big = c No
Print big b > big?
Stop Yes
Print big
big = b
A Stop
Generate the numbers 1 to 100
Steps
Start
Start
Initialize counter, c = 1
while c<=100 repeatedly do c=1
print c
c=c+1 Print c
End while
Stop c=c+1
c <= 100 No
Stop
?
Yes
Assignments – Algorithms and Flow Chart
1.Input radius of a circle, find the area and circumference of the circle.
2.Input marks in 5 subjects, find the total and average.
3.Input 2 values, simulate a calculator.
4.Input value in degrees and convert to radians radians = degrees * π / 180
5.Input 3 sides of a triangle a, b, c and find the area. area = √s (s-a)(s-b)(s-c) s=
(a + b + c)/2
6.Input 2 values, swap them and print the new values.
7.Input 3 numbers and find the smallest of them.
8.Find the sum of the following number sum = 1 + 2 + 3+ 50
HISTORY OF C
INTRODUCING C LANGUAGE
• C is a structured and procedural programming language.
• C is used to develop both system and application software due to its portable
features.
Features of C
• Structured programming language
• Provides various operators and data types
• Can be compiled and executed on any computer
• Use of functions
• Use of pointers
117
STRUCTURE OF A C PROGRAM
Preprocessor directives
Global declarations
void main()
{
Local declarations
Statements
}
Other functions as required
118
119
CREATING AND RUNNING PROGRAMS
1. Writing and editing program
2. Compiling program
Programmer
Object
Executable
Results
BUILDING A C PROGRAM
1. Writing and editing programs
• Text Editor : The software used to write programs
• After completing a program, save the file to the disk. The file is known as source
file.
2. Compiling programs
• Code in a source file must be translated into machine language which is done by
compiler.
• C compiler contains 2 separate programs
Pre processor Translator
Pre processor
• Reads the code and prepares it for translator.
• While preparing the code, scans pre processor commands.
• Translation Unit : The process of preparing the code for translation into machine
language.
Translator
• Does the actual work of translating the code to machine language.
• Reads translation unit and writes the resulting object module to a file that can be
compiled with other precompiled units to form final program.
• Object model : code in machine language.
BUILDING A C PROGRAM
3. Linking programs
• Linker assembles all the functions – our’s and system’s into final executable
program.
4. Executing programs
• Loader : OS program which gets the program into main memory.
• After this, the file is executed.
• The program reads data for processing and prepares for output.
/* First C Program */
#include<stdio.h>
void main()
{
printf(“My first C Program”);
}
Output :
My first C Program
126
/* Three lines of statement */
#include<stdio.h>
void main()
{
printf(“Two types of Software”);
printf(“1.System Software”);
printf(“2.Application Software”);
}
Output :
Two types of Software 1.System Software 2.Application Software
127
Backslash constants (Escape sequence)
Non printing characters can be printed using escape sequence.
It always starts with \ followed by a character.
128
1.
#include<stdio.h>
void main()
{
printf(“RNS Istitute of Technology\n”);
printf(“R.R.Nagar\tBangalore”);
}
Output
RNS Istitute of Technology
R.R.Nagar Bangalore
129
2.
#include<stdio.h>
void main()
{
printf(“A\nA\tB\nA\tB\tC\nA\tB\tC\tD”);
}
Output
A
A B
A B C
A B C D
130
Write C programs to get the following outputs
1.
Students’ of RNSIT
Semester I \ II
“Bangalore”
2.
Marks Grade
75 – 100 A
60 – 74 B
50 – 59 C
40 – 49 D
<40 E
131
BASIC C CONCEPTS
1. Character set
2. Tokens
Character Set
• Alphabets A - Z, a - z
• Digits 0-9
• Special symbols * , @ , % , { , [ , ) , #
• White spaces, new line, horizontal tab
132
Tokens
Each individual unit in a program is a Token.
Example
c = a + b * 10; Result = (x * y) * (x – y);
13
3
Keywords (Reserved words)
• Reserved words which have a pre-defined meaning in C compiler.
• Used for specific task in C language.
13
4
Identifiers
Names provided to the elements of the program such as variables, functions and arrays.
Rules for naming an identifier
1. Can consist of alphabets, digits and _ (underscore).
2. Must always begin with an alphabet or _ and can be followed by digits.
3. No special symbols allowed.
4. Case sensitive.
5. Cannot be a keyword.
13
5
Valid examples of Identifiers
Total sum1
Voter_ID roll_no
Invalid Identifiers
for 1stname
sum-of-digits roll number
#USN NO I Class
void stream(branch)
13
6
Constants(Literals)
A fixed value assigned to an identifier whose value cannot be changed.
Types of constants
Constants
Decimal
Octal
Hexa Decimal
13
7
1. Integer constant b) Octal
Whole numbers without decimal part. • between 0 – 7.
a) Decimal • Can be + or –
Constants having digit combination • The constant must have the prefix 0
between 0 – 9. (Zero).
Can be + or – Valid ex: 077 -0756 01234
Valid ex: -45 756 1234 Invalid ex : 0102 56 -017.7 856
Invalid ex : 102 56 4.50 -+56
13
8
c) Hexa Decimal
• Constants having digit combination between 0 – 9 and A – F.
• A ---> 10 F --->15
• Can be + or –
• The constant must have the prefix 0X / 0x.
13
9
2. Float constant
• Represents a number having fractional part.
• May be + or –
Examples : -221.45, 44567.34, 0.000009
3. Character constant
• Represents a single character within a pair of ‘ ‘
• Stored as integers in computer’s memory.
Examples :
char op = ‘+’;
char choice = ‘Y’;
14
0
4. String constant
Represents a sequence of characters within a pair of “ “
Examples : “Good Morning”, “10 + 40”, “R.N.S”
Data Types
• Defines the type of data that is stored in a variable.
• Determines how much storage should be allocated to a variable.
14
1
BUILTIN DATATYPES IN C
Data type Description Size (bytes) Range
14
2
char
Each character constant is stored internally in the computer as integer constant.
Ex :
void main()
{ Char constant ASCII value
char var1 =‘a’; ‘A’ 65
‘B’ 66
char var2 = ‘E’;
‘a’ 97
char var3 = ‘7’, var4 = ‘*’;
‘b’ 98
} ‘0’ 48
‘1’ 49
14
3
int float
Signed int : +ve or –ve values Ex :
Unsigned int : only +ve values void main()
Ex : { float a, b, c;
void main() a=7.1;
{ int a = 10; b=77.89;
int b, sum; c=a-b;
b=60; }
sum=a+b;
}
14
4
double
Ex :
void main()
{ double a, b, c;
a=78907.1976;
b=751237.89;
c=a*b;
}
void
Stores no values, non-specific data type.
14
5
PROGRAM
#include TO DISPLAY SIZE OF DIFFERENT DATA TYPES
<stdio.h>
main()
{
printf(" short int is %d bytes \n", sizeof(short int));
printf(" int is %d bytes \n", sizeof(int));
printf(" int * is %d bytes \n", sizeof(int *));
printf(" long int is %d bytes \n", sizeof(long int));
printf(" long int * is %d bytes \n", sizeof(long int *));
printf(" signed int is %d bytes \n", sizeof(signed int));
14
6
printf(" signed int is %d bytes \n", sizeof(signed int));
printf(" unsigned int is %d bytes \n", sizeof(unsigned int));
printf("\n");
printf(" float is %d bytes \n", sizeof(float));
printf(" float * is %d bytes \n", sizeof(float *));
printf(" double is %d bytes \n", sizeof(double));
printf(" double * is %d bytes \n", sizeof(double *));
printf(" long double is %d bytes \n", sizeof(long double));
printf(“ \n ");
printf(" signed char is %d bytes \n", sizeof(signed char));
printf(" char is %d bytes \n", sizeof(char));
14
7
printf(" char * is %d bytes \n", sizeof(char *));
printf("unsigned char is %d bytes \n", sizeof(unsigned char));
}
OUTPUT:
14
8
Variable
An identifier which can store a value.
The value may change later in the program.
Refers to a specific memory location where the data can be stored.
14
9
Declaring a Variable Initializing a Variable
Syntax: Ex:
Datatype variable name; int a =40;
Ex: float num1, num2;
int a; num1=67;
float num1, num2; num2=6.8;
char grade, name[21]; char grade=‘A’;
15
0
MANAGING INPUT AND OUTPUT FUNCTIONS
Stream is a logical entity that represents a file or
device, that can accept input or output.
putchar ( variable_name)
For example:
alphabet = getchar();
if(islower(alphabet))
putchar(toupper(alphabet));
else
putchar(tolower(alphabet));
1
11/19/2021 5
3
EXAMPLE 1
#include<stdio.h>
void main()
{
char c;
printf("\n Enter a character \n");
c=getchar(); //get a single character;
printf("Thanks for entering!!!See the entered character below");
putchar(c); //print a single character;
} 1
11/19/2021 5
4
➢ getch() method pauses the Output Console until a key is
pressed.
➢ It does not use any buffer to store the input character.
EXAMPLE 2 ➢ The getch() method can be used to accept hidden inputs
like password, ATM pin numbers, etc.
#include <stdio.h>
#include <conio.h>
int main()
{
printf("Enter a key to exit the console screen.\n");
getch();
return 0;
}
1
11/19/2021 5
5
EXAMPLE 3:
#include <stdio.h>
#include <conio.h>
int main()
{
printf("%c", getch());
return 0;
}
FORMATTED INPUT - SCANF
• FORMATTED INPUT – Refers to the input data that has been scanned in a specific
format to enhance readability. scanf ( formatted scan using the format identifiers
)
scanf(“control string”, arg1,arg2,arg3…argn);
Conversion character (%), a data type character (d,f,e,s,..) , optional field width
1
11/19/2021 5
7
FORMATTED INPUT – SCANF
EXAMPLE
#include<stdio.h> 1
int main()
{
int a,b,c;
printf("Enter the first value");
scanf("%d",&a);
printf("Enter the second value");
scanf("%d",&b);
c=a+b;
printf("%d + %d = %d\n",a,b,c);
return 0;
}
1
11/19/2021 6
0
FORMATTED INPUT – SCANF
int main ()
{EXAMPLE 2
char city[20];
float gdp;
a b
INPUTTING REAL NUMBERS :
scanf(“%f %f %f ”, &x, &y, &z); Input data : 475.89 43.21e-01 678
163
FORMATTED INPUT
Inputting Character Strings : %ws OR %wc
164
FORMATTED OUTPUT –
PRINTF
FORMATTED OUTPUT – Refers to the output data that has been arranged in a
specific format to enhance readability. printf ( formatted print using the
format identifiers )
printf(“control string”, arg1,arg2,arg3….argn);
11/19/2021 165
The printf function is used to display information required by the user and also to
print the values of the variables
Flags Specify output justification such as decimal point,numerical sign, trailing zeros or octal, decimal
or hexadecimal prefixes.
Width specifies the minimum number of characters to print after being padded with
zeros or blank spaces, that is it specifies the minimum number of positions in the output
PRINTF FORMAT SPECIFIERS
11/19/2021 171
PRINTF –
#include <stdio.h>
EXAMPLE 1
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( up to 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
11/19/2021 177
#include <stdio.h> – EXAMPLE 2
PRINTF
int main ()
{
char str1[20], str2[30];
179
FORMATTED OUTPUT
OUTPUT OF REAL NUMBERS :
Format specification: %w.pf
We can also display a real number in exponential notation : %w.pe
The display takes the form : [-] m.nnnne[+-]xx ---- 12345.67891
Some systems also support a special field specification character that lets the user
define the field size at run time.
printf(“%*.*f ”,7,2,number);
180
FORMATTED OUTPUT
y = 98.7654 ---- 9.87650e+01
181
FORMATTED OUTPUT
PRINTING A SINGLE CHARACTER: %wc
PRINTING STRINGS :
The format specification for outputting strings is similar to that of real numbers.
%w.ps
182
MIXED DATA OUTPUT
It is permitted to mix data types in one printf statament.
183
184
185
186
QUERIES ?? THANK YOU
19
1