CP Module1
CP Module1
Module 1:
Introduction to C: Introduction to computers, input and output devices,
designing efficient programs. Introduction to C, Structure of C program,
Files used in a C program, Compilers, Compiling and executing C
programs, variables, constants, Input/output statements in C.
What is Computer?
• Computer is an electronic device, which takes input from the user in the form
of data and instructions.
• Once the computer receives the data, it waits for the user’s instructions to
process the data.
• On receiving the instructions from the user, the computer processes the data
and generates the output and displays it to the user.
• The data that is given as an input to the computer can be text, numerals,
audio, video and image etc.
• Input: Sending the data and command to the computer is known as input.
• Processing: Work done by the computer with the help of processing hardware
and software to produce results is known as processing.
• Output: The result displayed by the computer is called as output.
• Storage: A place to save results inside or outside the computer is known as
storage.
Characteristics of computers:
Diligence: Unlike humans, computers don’t get tired from doing the
same task over and over.
Fig: Von Neumann Architecture with shared memory for instructions and
data
Read/Write Data
Instruction
s
History of Computers:
Advantages: They used less electricity, generated less heat, were faster and
more reliable, and had better memory.
Advantages: They were faster, could handle one million transactions per
second, were smaller and cheaper, and had better memory for scientific and
business use.
Disadvantage: They were still hard to maintain and could heat up quickly.
Advantages: They are smaller, cheaper, faster, more powerful, reliable, use
less power, and have advanced features.
Comparison table
Classification of Computers:
1) Supercomputers:
2) Mainframe Computers:
3) Minicomputers:
4) Microcomputers:
Network Computers:
Smartphones:
Tablet Computers:
Similar to Laptops: Tablets are portable computers that look like a flat
slate and can be operated with a stylus (a special pen for touch screens).
Portable: They are lightweight and easy to carry, making them great for
on-the-go use.
Advantages: Users can write notes by hand, reducing the need for paper
and making note-taking easier.
Disadvantages: Tablets can be more expensive than laptops and are
generally more delicate, making them prone to damage.
Applications of Computers:
Word Processing:
o Description: Word processing software is essential for creating
and editing text documents. It allows users to format text, add
images, and collaborate on documents easily.
o Example: Microsoft Word is widely used in businesses, schools,
and homes for tasks like writing reports, resumes, and essays.
Features like spell check and templates enhance productivity.
E-Business (B2C):
o Description: E-business enables companies to sell products and
services directly to consumers over the Internet. This model has
transformed retail and consumer behavior.
o Example: Amazon is a leading example of B2C e-business, offering
everything from books to electronics. Customers can shop online,
read reviews, and receive products quickly, revolutionizing the
shopping experience.
Electronic Banking:
o Description: Also known as online banking, this application allows
users to conduct banking activities from their homes or on the go.
It provides convenience and accessibility.
o Example: Services like PayPal and mobile banking apps enable
users to check balances, transfer funds, pay bills, and even deposit
checks using their smartphones, making financial management
easier.
Bioinformatics:
o Description: This interdisciplinary field combines biology and
computer science to analyze complex biological data, especially
useful in genomics and drug discovery.
o Example: Bioinformatics tools are used in genetics to sequence
DNA and identify genetic markers for diseases, which is crucial for
personalized medicine and targeted therapies.
Geographic Information System (GIS):
o Description: GIS technology allows for mapping and analyzing
spatial data. It is essential for urban planning, environmental
monitoring, and disaster management.
o Example: ArcGIS is a popular GIS software that helps
governments and organizations visualize data, track changes in
land use, and manage resources effectively.
Weather Forecasting:
o Description: Computers play a key role in meteorology, using data
models to predict future weather conditions. Accurate forecasting
is vital for safety and planning.
o Example: Weather apps and websites rely on complex algorithms
and satellite data to provide real-time updates and forecasts,
helping individuals and businesses make informed decisions.
Multimedia and Animation:
o Description: This application involves combining various forms of
media—text, images, audio, and video—to create engaging content
for entertainment and education.
o Example: Software like Adobe Premiere and After Effects is used in
film and video production to create stunning visual effects and
animations, enhancing storytelling.
Input:
• The process of entering the data and instructions into the computer system is
called Input.
• The data and instructions can be entered by using different input devices
such as keyboard, mouse, scanner, and trackball.
• Note that computers understand binary language, which consists of only two
symbols (0 and 1), so it is the responsibility of the input devices to convert the
input data into binary codes.
Storage:
• Storage is the process of saving data and instructions permanently in the
computer so that they can be used for processing.
• A computer has 2 types of storage area:
1. Primary storage
2. Secondary storage
1. Primary storage:
• Primary storage, also known as the main memory, is the storage area that is
directly accessible by the CPU at very high speeds.
• It is used to store the data and parts of programs, the intermediate results of
processing, and the recently generated results of jobs that are currently being
worked on by the computer.
• Primary storage space is very expensive and therefore limited in capacity.
• Another drawback of main memory is that it is volatile in nature; that is, as
soon as the computer is switched off, the information stored gets erased.
• Hence, it cannot be used as a permanent storage of useful data and programs
for future use. An example of primary storage is random access memory (RAM).
2. Secondary storage:
• Secondary storage is also known as auxiliary memory, this memory is just the
opposite of primary memory. It overcomes all the drawbacks of the primary
storage area.
• It is cheaper, non-volatile, and used to permanently store data and programs
of those jobs that are not being currently executed by the CPU.
• Secondary memory supplements the limited storage capacity of the primary
memory. An example is the magnetic disk used to store data, such as C and D
drives, for future use.
Output:
• Output is the process of giving the result of data processing to the outside
world (external to the computer system).
• The results are given through output devices such as monitor, and printer.
• Since the computer accepts data only in binary form and the result of
processing is also in binary form, the result cannot be directly given to the
user.
• The output devices, therefore, convert the results available in binary codes
into a human-readable language before displaying it to the user.
Control:
• The control unit (CU) is the central nervous system of the entire computer
system. It manages and controls all the components of the computer system.
• It is the CU that decides the manner in which instructions will be executed
and operations performed. It takes care of the step-by-step processing of all
operations that are performed in the computer.
• Note that the CPU is a combination of the arithmetic logic unit (ALU) and the
CU. The CPU is better known as the brain of the computer system because the
entire processing of data is done in the ALU, and the CU activates and
monitors the operations of other units (such as input, output, and storage) of
the computer system.
Processing:
• The process of performing operations on the data as per the instructions
specified by the user (program) is called processing.
• Data and instructions are taken from the primary memory and transferred to
the ALU, which performs all sorts of calculations.
• The intermediate results of processing may be stored in the main memory, as
they might be required again.
• When the processing completes, the final result is then transferred to the
main memory.
• Hence, the data may move from main memory to the ALU multiple times
before the processing is over.
CPU:
• The CPU is the brain of the computer. It performs all calculations and
controls the devices connected to the computer system.
• The faster the CPU, the quicker programs can process the instructions.
RAM:
• A fast CPU is of no use if the computer does not have sufficient RAM.
• RAM is the computer's memory which stores information used by applications
that are currently being executed by the CPU.
• More memory means more applications can be executed at the same time
without degrading the system's performance.
Video card:
• The video card is a board that plugs into the motherboard of the computer
and generates images for display.
• Many video cards these days have their own RAM and processor to enhance
the speed of the graphics display.
• Many computers come with an in-built video chip.
• In such a computer, a separate video card is used only if the computer has to
be used for high-end multimedia work or to play video games.
Sound card:
• As with video cards, sound cards are expansion boards that are used to
enable a computer to manipulate sound.
• For example, sound cards allow the users to plug in speakers and a
microphone. Some sound cards also provide the jacks for hooking your
computer up to a common stereo.
• These days, many computers come with a built-in sound chip, which makes it
unnecessary to buy a separate card unless a higher quality of sound is needed.
Modem:
• A modem (modulator-demodulator) is a device that enables the computer to
use a telephone line to communicate and connect to the Internet.
Network card:
• A network card is used to connect the computer either to other computers or
to the Internet (in case you are using a fast Internet connection such as cable
or DSL).
Fans:
• There are one or more fans inside the computer to keep the air moving and
the computer cool.
Cables:
• There are multiple wires inside the computer that are flat, ribbon-like cables.
• They are used to provide power and communication to the various parts
inside the computer.
Input devices:
Input devices allow users to send data and commands to a computer, enabling
interaction and control. They convert physical actions or signals into digital
data that the computer can process.
1. Keyboard
What It Is: The keyboard is a tool that lets you type letters, numbers,
and commands into a computer, much like a typewriter.
Layout: It has many keys, including letters (A-Z), numbers (0-9), and
special keys like "Enter," "Shift," and "Function" keys that perform
specific tasks.
Numeric Keypad: This is a group of number keys usually located on the
right side of the keyboard, making it easier to enter numbers quickly,
similar to a calculator.
Advantages: Keyboards are generally user-friendly and affordable,
making them accessible for everyone.
Limitations: They aren’t suitable for tasks like drawing pictures, and
moving the cursor around can be slower than using a mouse.
2. Mouse
3. Touchpad
4. Scanner
What It Is: OCR is a technology that converts printed text from scanned
documents into editable digital text.
How It Works: The OCR process involves scanning the document and
analyzing the shapes of characters to translate them into text that can be
edited or searched.
Applications: This technology is useful for turning books, forms, and
other printed materials into digital formats that are easy to edit and
store.
Advantages: OCR makes it simple to digitize printed materials, allowing
for easy editing and sharing.
Limitations: It may have difficulty recognizing certain fonts or poorly
printed documents, which can lead to errors in the digital text.
OUTPUT DEVICES
1. Monitors
1. Types: The main types are CRT, LCD, and Plasma, each with different
technologies.
2. Display Quality: CRTs provide good image quality, while LCDs and
Plasmas offer clearer and brighter displays.
3. Space and Weight: CRTs are bulky and heavy, while LCDs and Plasmas
are slim and lightweight.
4. Power Consumption: CRTs consume more power than LCDs and
Plasma monitors, which are more energy-efficient.
5. Viewing Angles: Plasmas have the best viewing angles, while LCDs may
struggle with color clarity when viewed from the side.
2. Projectors
3. Printers
1. Types: There are impact printers (like dot matrix and daisy wheel) and
non-impact printers (like inkjet and laser).
2. Print Quality: Non-impact printers generally offer better quality and
color output compared to impact printers.
3. Speed: Laser printers are faster, making them suitable for high-volume
printing, while impact printers are slower.
4. Cost: Inkjet printers have a lower initial cost but higher maintenance
costs due to ink cartridges, while laser printers are more cost-effective in
the long run.
5. Uses: Printers are used for everything from simple documents to high-
quality color prints for presentations.
4. Speakers
1. Sound Quality: Good quality speakers produce clear and rich sound for
music, movies, and games.
2. Types: Speakers come in various types, including standalone speakers,
soundbars, and headphones.
3. Applications: Used in home theaters, offices, and for personal listening
experiences.
4. Volume Control: Speakers can project sound across large spaces, while
headphones offer personal listening without disturbing others.
5. Connectivity: Many speakers connect via Bluetooth or USB, making
them versatile for different devices.
5. Plotters
Plotters are specialized printers for creating high-quality graphics. Key points
include:
PROGRAMMING PARADIGMS
1. Monolithic Programming
Explanation: This approach involves writing one large program without
breaking it down into smaller parts. All code is in one place, which
makes it straightforward but also problematic.
Features:
Single Module: Everything is contained in one big piece of code.
Difficult Maintenance: Since everything is together, fixing bugs
or making changes can be hard and time-consuming.
Shared Data: All parts of the program can access and change the
same data, which can lead to errors if not managed carefully.
Examples: Assembly Language and BASIC are commonly used in
monolithic programming.
2. Procedural Programming
o Explanation: This style focuses on writing programs as a series of
instructions or procedures. It emphasizes the steps needed to
complete tasks.
o Advantages:
Clear Goal: The main focus is to write correct programs that
perform specific tasks.
Easier to Write: Generally simpler than monolithic
programming, as it allows for structured sequences of
commands.
o Disadvantages:
No Reusability: It’s harder to use the same code in different
programs, as each program is written independently.
Time-Consuming: Writing and maintaining procedural
programs can take more effort.
Global Data Issues: Shared data can be modified
accidentally, leading to bugs.
o Examples: Languages like C and Pascal are typical procedural
languages.
3. Structured Programming
o Explanation: This approach breaks down a program into smaller,
manageable modules. Each module can be developed and tested
independently, making the entire program easier to manage.
o Features:
Top-Down Design: The overall program is planned first, and
then broken into smaller parts.
Modular Code: Each module can be written, tested, and
reused in other programs, promoting efficiency.
Requirement Analysis
Explanation: This phase is crucial for understanding what users expect
from the software and why it needs to be developed.
Key Activities:
Gather User Expectations: Collect information from users to identify
their needs and expectations.
Analyze Requirements: Review the gathered information to define clear
objectives for the software.
Algorithms
What They Are: An algorithm is a structured sequence of steps
designed to solve a specific problem.
Key Features:
o Finite Steps: Must complete in a limited number of steps,
ensuring it provides an answer.
o Clarity and Precision: Should be clear and unambiguous, with
each step well-defined.
o No Infinite Loops: Must avoid repeating instructions endlessly.
o Desired Outcome: Should produce the expected result when
executed.
Control Structures in Algorithms
Decision: Decision statements are used when outcomes depend on
specific conditions. For example: if x = y, then print "EQUAL".
Repetition: This involves executing steps multiple times using loops
like while, do-while, and for, which continue until a condition is met.
Sequence: Each step in the algorithm is executed in a defined order.
Flowcharts
What They Are: Flowcharts visually represent a process, helping to
clarify its logic.
Key Features:
o Symbolic Representation: Different shapes represent various
steps, connected by arrows to indicate the flow of logic.
o Visualization: Helps identify flaws and bottlenecks in complex
processes, making it easier to understand the workflow.
Pseudocode
What It Is: Pseudocode is a simplified, informal description of an
algorithm designed for human readability.
Key Features:
o High-Level Outline: Focuses on the logic rather than technical
details, omitting unnecessary elements like variable declarations.
o Easy Translation: Can be easily converted into actual
programming code.
o Descriptive Language: Uses simple English phrases to explain
tasks within the algorithm, enhancing understanding without
specific programming syntax.
Note: This structured approach to software development ensures that
each phase is thoroughly planned and executed, resulting in efficient
programs that meet user needs. Each step plays a vital role in
maintaining the overall quality and effectiveness of the software.
TYPES OF ERRORS
When writing programs, errors can occur that affect the program's output or
prevent it from compiling. Understanding these errors is crucial for effective
programming.
1. Run-Time Errors
o What They Are: These errors happen while the program is
running.
o Causes:
Dividing by zero.
Opening a file that already exists.
Running out of memory.
Trying to calculate the square root or logarithm of a negative
number.
o Impact: Run-time errors can stop the program unexpectedly. To
avoid this, the code should be able to handle these errors
gracefully. This ability is known as robustness.
2. Compile-Time Errors
o What They Are: These errors occur during the compilation process
when the code is checked for correctness.
o Types:
Syntax Errors: Occur when the rules of the programming
language are broken. For example, writing int a: instead of
int a; will cause a syntax error.
Semantic Errors: These are errors that, while syntactically
correct, do not make sense in the program’s context. For
example, a * b = c; is incorrect; it should be c = a * b;.
3. Logical Errors
o What They Are: These errors occur when the program runs but
produces incorrect or unexpected results.
o Detection: Logical errors are not caught by the compiler, so
programmers must review their code carefully or use a debugger to
find these errors.
o Example: If you intended to write c = a + b; but mistakenly wrote c
= a * b; , the statement is syntactically correct but logically wrong.
4. Linker Errors
o What They Are: These occur when the linker cannot find the
definition for a declared function.
o Example: If you use clrscr(); but forget to include the header file
conio.h, a linker error will occur.
Testing Approaches
Testing is essential for ensuring that a program functions correctly and meets
its requirements. Different methods focus on various aspects of the software.
Debugging Approaches
Debugging involves identifying and fixing errors in the code. Various methods
can help locate issues.
Introduction to C
Characteristics of C
Uses of C
Structure of a C program
• A C program contains one or more functions
• The statements in a C program are written in a logical
sequence to perform a specific task.
• Execution of a C program begins at the main() function
• You can choose any name for the functions.
• Every program must contain one function that has its
name as main().
Where, #include refers to the preprocessor statement
used for the standard input/output functions and it
starts with the hash (#) symbol.
Header file
• When working with large projects, it is often desirable to make sub-routines
and store them in a different file known as header file. The advantage of header
files can be realized when
a) The programmer wants to use the same subroutines in different programs.
b) The programmer wants to change, or add, subroutines, and have those
changes be reflected in all other programs.
• Conventionally, header files names ends with a “.h” extension and its name
can use only letters, digits, dashes, and underscores.
• While some standard header files are available in C, but the programmer may
also create his own user defined header files.
Object Files:
• Object files are generated by the compiler as a result of processing the source
code file.
• Object files contain compact binary code of the function definitions.
• Linker uses this object file to produce an executable file (.exe file) by
combining the of object files together.
• Object files have a “.o” extension, although some operating systems including
Windows and MS-DOS have a “.obj” extension for the object file.
• While there is a different compiler for every individual language, the same
linker is used for object files regardless of the original language in which the
new program was written.
• The output of the linker is an executable or runnable file.
Using Comments
• It is a good programming practice to place some comments in the code to help
the reader understand the code clearly.
• Comments are just a way of explaining what a program does. It is merely an
internal program documentation.
• The compiler ignores the comments when forming the object file. This means
that the comments are non-executable statements.
C supports two types of commenting.
• // is used to comment a single statement. This is known as a line comment.
A line comment can be placed anywhere on the line and it does not require to
be specifically ended as the end of the line automatically ends the line.
• /* is used to comment multiple statements. A /* is ended with */ and all
statements that lie within these characters are commented.
C tokens
• Tokens are the basic building blocks in C language.
• It is the smallest individual unit in C program.
• A program is constructed using a combination of these tokens. 6main types of
tokens in C are:
Character set in C
• In C, character means any letter from English alphabet, a digit or a special
symbol used to represent information.
• The character set of C can therefore be given as:
1. English alphabet: Include both lower case (a-z) as well upper case (A-Z)
letters.
2. Digits: Include numerical digits from 0 to 9.
3. Special characters: Include symbols such as ~, @, %, ^, &, *, {, }, <, >, =, _, +,
-, $, /, (, ), \, ;, : , [, ], ‘, “, ?, ., !, |.
4. White space characters: These characters are used to print a blank space on
the screen like \b, \t, \v, \r, \f, \n.
5. Escape sequences.
Keywords
• C has a set of 32 reserved words often known as keywords.
• All keywords are basically a sequence of characters that have a fixed meaning.
• By convention all keywords must be written in lowercase (small) letters.
• The keywords are for, while, do-while, auto break, case, char, continue, do,
double, else, enum, extern, float, goto, if, int, long, register, return, short,
signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile.
Keywords in C
Identifiers
Identifiers are names given to program elements such as variables, arrays and
functions.
Rules for forming identifier name
1. It cannot include any special characters or punctuation marks (like #, $, ^,
?, ., etc) except the underscore"_".
2. There cannot be two successive underscores
3. Keywords cannot be used as identifiers
4. The names are case sensitive. So, example, “FIRST” is different from “first”
and “First”.
5. It must begin with an alphabet or an underscore.
It can be of any reasonable length. Though it should not contain more than 31
characters.
Example: roll_number, marks, name, emp_number, basic_pay, HRA, DA,
dept_code, a , sum, temp.
Variables
• A variable is defined as a meaningful name given to the data storage location
in computer memory.
• When using a variable, we actually refer to address of the memory where the
data is stored. C language supports two basic kinds of variables.
• Numeric variables can be used to store either integer values or floating point
values.
• While an integer value is a whole numbers without a fraction part or decimal
point, a floating point number, can have a decimal point in them.
• Numeric values may also be associated with modifiers like short, long, signed
and unsigned.
• By default, C automatically a numeric variable signed..
• Character variables can include any letter from the alphabet or from the
ASCII chart and numbers 0 – 9 that are put between single quotes.
Declaring Variables
• To declare a variable specify data type of the variable followed by its name.
• Variable names should always be meaningful and must reflect the purpose of
their usage in the program.
• Variable declaration always ends with a semicolon. Example,
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
Initializing Variables
• Assigning a value to a variable is called variable initialization.
• The syntax is variable_name=value; Initialization can be done in two ways:-
1. We can assign an initial value to a variable within the declaration part itself
called static initialization.
Ex:- int a=10;, float x=100.0000;
2. We can assign an initial value to a variable during the program execution
called dynamic initialization.
Ex:- printf(Enter a value to a”);
scanf(“%d”, &a);
Constants
• Constants are identifiers whose value does not change.
• Constants are used to define fixed values like PI or the charge on an electron
so that their value does not get changed in the program even by mistake.
• There are mainly four types of constants in C:
1.Integer constants
2.Floating-point constants
3.Character constants
4.String constants
To declare a constant, precede the normal variable declaration with const
keyword and assign it a value. For example,
• const float pi = 3.14;
Another way to designate a constant is to use the pre-processor command
define.
• #define PI 3.14159
Declaring Constants
Rules that need to be applied to a #define statement which defines a constant.
Rule 1: Constant names are usually written in capital letters to visually
distinguish them from other variable names which are normally written in
lower case characters. Note that this is just a convention and not a rule.
Rule 2: No blank spaces are permitted in between the # symbol and define
keyword
Rule 3: Blank space must be used between #define and constant name and
between
constant name and constant value
Rule 4: #define is a pre-processor compiler directive and not a statement.
Therefore, it does not end with a semi-colon.
Input/Output statements in C
There are two types of Input and Output functions. They are,
1. Formatted I/O functions.
2. Unformatted I/O functions.
Formatted I/O functions enables the user to specify the type of the data and
the way in which it should be read in or written out.
Ex: Formatted input function- scanf()
Formatted output function- printf()
Rules:
1. The controlled string must be enclosed within a pair of double quotes.
2. For every input variable, there must be one character group.
3. Each character group should begin with a % symbol and followed by a
conversion character.
4. Multiple number of character groups can be allowed within the control
string, in such case they may be contiguous or separated by blank space.
5. The address_list contains addresses of input variables.
6. Each input variable in the address list must be proceeded by an ampersand
(&). Ex. &a,&b. for string input variable & is not compulsory.
7. All the address list variables are separated by commas. Do not use blank
spaces.
8. The address list is not enclosed within double quotes.
9. The values for the address list variables should match in number, type and
order of the variables.
10. There must be a comma to separate control string and the address list.
Examples:
1. scanf(“%d %f %d”,&x,&y,&z);
2. scanf(“%d %c %d”,&a,&ch,&b);
3. scanf(“%f %c %f”,&x,&ch,&z);
4. scanf(“%d %s”,&number,name);
5. scanf(“%f %f”,&fval1,&fval2);
6. scanf(“%c %s”,&ch,str);
Example of printf()
1. printf(“ well come to c program”);
2. printf(“%d”, number);
3. printf(“%f %d”, fval,number);
4. printf(“sum of two number = %d”, sum);
5. printf(“%s, is a input string”, str);
6. printf(“x = %d and y = %d”, x,y);
The unformatted Input output function do not specify the types of data and the
way it should be read or written.
The unformatted input output functions only operates on character and string
type of data.