2. BASICS OF COMPUTER: INTRODUCTION TO DIGITAL COMPUTER, BASIC
OPERATIONS OF COMPUTER, FUNCTIONAL COMPONENTS OF COMPUTER,
CLASSIFICATION OF COMPUTERS.
INTRODUCTION TO OPERATING SYSTEM: [DOS, WINDOWS, LINUX AND ANDROID]
PURPOSE, FUNCTION, SERVICES AND TYPES.
NUMBER SYSTEM: BINARY, OCTAL AND HEXADECIMAL NUMBER SYSTEMS, THEIR
MUTUAL CONVERSIONS.
BINARY ARITHMETIC. BASICS OF PROGRAMMING: APPROACHES TO PROBLEM
SOLVING, CONCEPT OF ALGORITHM AND FLOWCHARTS.
TYPES OF COMPUTER LANGUAGES:- MACHINE LANGUAGE, ASSEMBLY LANGUAGE
AND HIGH LEVEL LANGUAGE, CONCEPT OF ASSEMBLER, COMPILER, LOADER AND
LINKER.
UNIT-1 TOPICS
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
2
3. STANDARD I/O IN “C”, FUNDAMENTAL DATA TYPES- CHARACTER TYPE, INTEGER,
SHORT, LONG, UNSIGNED, SINGLE AND DOUBLE FLOATING POINT.
STORAGE CLASSES- AUTOMATIC, REGISTER, STATIC AND EXTERNAL.
OPERATORS AND EXPRESSION USING NUMERIC AND RELATIONAL OPERATORS,
MIXED OPERANDS.
TYPE CONVERSION, LOGICAL OPERATORS, BIT OPERATIONS, ASSIGNMENT
OPERATOR, OPERATOR PRECEDENCE AND ASSOCIATIVELY.
FUNDAMENTALS OF C PROGRAMMING: STRUCTURE OF C PROGRAM, WRITING
AND EXECUTING THE FIRST C PROGRAM, COMPONENTS OF C LANGUAGE.
STANDARD I/O IN C.
UNIT-2 TOPICS
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
3
4. CONDITIONAL PROGRAM EXECUTION: APPLYING IF AND SWITCH
STATEMENTS, NESTING IF AND ELSE, USE OF BREAK AND DEFAULT WITH
SWITCH.
PROGRAM LOOPS AND ITERATIONS: USE OF WHILE, DO WHILE AND FOR
LOOPS, MULTIPLE LOOP VARIABLES, USE OF BREAK AND CONTINUE
STATEMENTS.
FUNCTIONS: INTRODUCTION, TYPES OF FUNCTIONS, FUNCTIONS WITH
ARRAY, PASSING VALUES TO FUNCTIONS, RECURSIVE FUNCTIONS.
UNIT-3 TOPICS
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
4
5. ARRAYS: ARRAY NOTATION AND REPRESENTATION, MANIPULATING
ARRAY ELEMENTS, USING MULTI-DIMENSIONAL ARRAYS.
STRUCTURE, UNION, ENUMERATED DATA TYPES.
UNIT-4 TOPICS
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
5
6. POINTERS: INTRODUCTION, DECLARATION, APPLICATIONS FILE
HANDLING.
STANDARD C PREPROCESSORS, DEFINING AND CALLING MACROS.
CONDITIONAL COMPILATION, PASSING VALUES TO THE COMPILER.
UNIT-5 TOPICS
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
6
7. Some Basic Computer Understanding
1: What is a computer?
2: Different Types
3: Different Operating Systems
4: Different Brands
5: Basic Components
6: Hardware & Software
7: How a computer boots up
8: Different applications of a computer
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
7
8. Basics of Computer:
Introduction to Digital Computer:- A Computer is an Electronic
device which takes Input and gives Output.
Computers are machines that perform tasks or calculations according
to a set of instructions, or programs.
It works through an interaction of Hardware & Software.
Hardware items such as our monitor, keyboard, mouse, printer.
Software such as System software and Application software.
COMPUTER is a MACHINE that manipulates DATA according to a list
of INSTRUCTION. To accomplish a task using a computer, need a
combination of hardware, software .
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
8
10. Basic Operations of Computer:-
Program & Data
Results
Central Processing
Unit
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
10
Input
Unit
Output
Unit
Storage
Unit
Control Unit
Arithmetic
Logic Unit
11. Basic Operations:
Input Unit:- Information and Programs are entered into the COMPUTER through
Input Devices such as the KEYBOARD, DISKS, or through other Computers via network
connections or modems connected to the INTERNET. The Input Device also retrieves
information off Disks.
Output Unit:- This unit takes care of receiving processed information from
processing unit & present it to the user in suitable form. A computer produces results in
binary form & output unit does Decoding to make it usable to the users.
The devices that can output information from computer are known as output unit devices.
Monitors, Speakers, Projectors are soft output devices whereas printers, plotters
produces hard copy output.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
11
12. Processing Unit:-
The assignment of performing calculations and contrasts are known as
processing. The unit in Computer System that is accountable for processing is
ALU (Arithmetic and Logical Unit).
ALU is the place where real execution of the instructions takes place during the
processing operations. All calculations & comparisons are made in the ALU.
The data and instructions deposited in the primary storage are moved to it as
when required. ALU may produce Intermediate results and store it in the
memory which are also transferred back to the ALU for the final processing.
After conclusion of processing the final results are send to storage units from
ALU.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
12
13. Storage Unit:-
Before actual processing start, data & directions entered to the computer must be
stored somewhere inside the computer. Similarly, results produced by the computer
are required to be stored before it is passed to the output unit. The middle result
created by the computer must also be kept for further processing. Thus the status of
storage Unit in a computer system is vital.
Based on whether storage device is inside the main machine or not, it can be
internal internal or external storage. Similarly, looking at whether the storage device
works close with CPU or works as holdup media, they can be primary storage or
unimportant storage. Primary storage are also called primary memory. Unimportant
storage are known with other names such as backup storage or secondary memory.
For the storage purpose, a computer system may have different devices such as
registers, cache, RAM/ROM, flash, magnetic disks, optical disks and so on.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
13
14. Control Unit:-
It manages co-ordinates the entire system.
CU doesn’t perform any actual processing on data yet it is known as a central nervous
system for the comforts of the computer.
It controls all the processing & calculations of the ALU.
It directs operation of the processor.
It tells how to respond to a program's instructions.
It directs the operation of the other units by providing timing and control signals.
Most computer resources are managed by the CU.
It directs the flow of data between the CPU and the other devices.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
14
15. Functional Components of COMPUTER
The five classic components of a Computer are as follows:-
Processor(CPU)
Main Memory
Secondary Memory
Input Devices
Output Devices
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
15
16. FIG. THE OPERATION OF A PROCESSOR
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
16
CPU
Output Devices
Storage
Devices
Input Devices Memory
CPU
Output Devices
Storage
Devices
Input Devices Memory
19. FUNCTIONAL COMPONENTS OF COMPUTER
1. Processor:- The processor is an electronic device about a one inch
square, covered in plastic.
2. Memory:- The processor performs all the fundamental computations
of the computer system.
3. Input & Output Devices:- Input & Output devices allow the
computer system to interact with the outside world by moving data into
& out of the system.
4. Storage Devices:- There are two types of storage devices used with
computers: a primary storage device, such as RAM, and a secondary
storage device, like a hard drive. Secondary storage can be removable,
internal, or external storage.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
19
20. CLASSIFICATION OF COMPUTERS
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
20
Computers
Analog Digital Hybrid (Analog +Digital)
Purpose Performance& Size
Special Purpose
General Purpose
Embedded Micro Mini Mainframe Super
21. Classification of Computers
1. Analog Computer:-
Analog computers are used to process continuous data.
Analog computers represent variables by physical quantities.
such as flow, temperature, pressure.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
21
22. 2. Digital Computer:-
Digital computer represents physical quantities with the help of digits or
numbers.
These numbers are used to perform Arithmetic calculations and also make
logical decision to reach a conclusion, depending on, the data they receive from
the user.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
22
23. 3. Hybrid Computers
Various specifically designed computers are with both digital and analog
characteristics combining the advantages of analog and digital computers when
working as a system.
Hybrid computers are being used extensively in process control system.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
23
24. SUPER COMPUTER
It is used for large purpose works.
Used for scientific research.
Used in research laboratories.
These computers are extremely expensive and the speed is measured
in billions of instructions per seconds.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
24
25. MINI COMPUTERS
Mini Computers are smaller in size as well as speed.
They are versatile that they can be fitted where ever they are needed.
Their speeds are rated between one and fifty million instructions per second
(MIPS).
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
25
26. MICRO COMPUTERS
These are the smallest range of computers.
less storing space and processing speed.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
26
27. Applications of Computers:- Today computers are widely used in fields such as
engineering, health care, banking, education, etc.
Word Processing
Internet
Digital Video or Audio composition
Desktop Publishing
e- business
Bioinformatics
Health Care
Meteorology
Multimedia & Animation
Travel & Tourism
Simulation
Robotics
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
27
28. Introduction to Operating System
The Interaction between the user and the system is known as Operating
System.
It provides a user-friendly environment in which a user may easily develop and
execute programs.
The OS manages these following resources and allocates them to specific
programs and users.
Processor Management
Memory Management
File Management
Device Management
Concurrency Control
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
28
29. 4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
29
Application Programs
System Programs
Operating System
Machine Language
Hardware
Position of Operating System
30. Types of OS: DOS, WINDOWS, LINUX and ANDRIOID
DOS:- Disk Operating System(1981)
It is a non-graphical command line operating system.
It was very powerful OS of that time
Easy to load and install.
The following are the commands used frequently-
CD- to change the current directory
COPY- to copy a file
DEL- to delete a file
DIR- to list directory contents
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
30
31. EDIT- to start an editor to create or edit text files
FORMAT- to format a disk
HELP- to display information about a command
MKDIR- to create a new directory
RD- to remove a directory
REN- to rename a file
TYPE- to display contents of a file on the screen
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
31
32. WINDOWS
Developed by Microsoft.
Initially two editions were taken- Home Users & IT Professionals.
IT Professionals.
--Well suited for server environment.
--Limited multimedia features.
--Enhanced networking capability & security.
Home Users support-
--More functionalities & multimedia features
--Limited support for security & networking
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
32
33. S.No Version Year Reason/Limitations
1. Version 1.0 1985 Lack of functionality
2. Version 2.0 1987 Slightly more popularity
3. Version 2.03 1988 Different look
4. Version 3.0 1990 Commercial success, user interface
5. Version 3.1 1992 Offered OS a new facelift
6. Windows NT 1993 Designed for professional platform
7. Windows 95 1995 Support for pre-emptive multitasking
8. Windows 98 1998 Slower & less reliable than its previous one
9. Windows 00 2000 Consumer version
10. Windows XP 2001 Very popular.
11. Windows 7 2009 New features, compatibility with H/W
12. Windows 8 2012 Start screen-launch programs, search files,
browse the web.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
33
34. LINUX
It is very powerful, free, open-source operating system based on UNIX.
It is free to download and one can make change to it.
Some advantage includes-
--Low cost
--Stability
--Performance
--Networking, Security
--Flexibility, Multitasking
--Compatibility
--Fast & easy to install
--Better use of hard disk
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
34
35. ANDROID
It is Google’s OS, used on mobile devices.
Leading smartphones manufacturers such as Samsung, HTC, Motorola.
Currently it is one of the top operating systems.
Open source OS powered by the Linux Kernel.
Users can use this OS to develop apps.
It is a multitasking OS.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
35
36. PURPOSE
To provide interaction b/w user and system.
To manage the computer hardware.
Provides a user interface.
To manage process management.
To organize memory management.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
36
37. FUNCTION, SERVICES and TYPES
Function & Services
Functions are little bit same as the services.
The OS protects stored information from malicious users.
The OS allows users to create, copy, delete, and rename files.
Memory management is one of the important function of OS.
Multiple processes can be executed at the same time.
With the help of icons it is easy to interact for users.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
37
38. TYPES OF OPERATING SYSTEMS
Based on usage and requirements, OS can be classified into different categories.
Batch operating system(BOS)
Single –user single-tasking operating system(SUSTOS)
Single-user multitasking operating system(SUMOS)
Multi-user multitasking operating system(MUMOS)
Multiprocessing(MP)
Real-time operating system(RTOS)
Network operating system(NOS)
Time-sharing operating system(TSOS)
Distributed operating system(DOS)
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
38
39. BOS:
IT allows very limited interaction between user & processor.
Programs are bundled as a “batch” and executed together.
On large data, it performs very well.
Its processing is performed automatically.
The problems with Batch Systems are as follows −
--Lack of interaction between the user and the job.
--CPU is often idle, because the speed of the mechanical I/O devices is slower than the
CPU.
--Difficult to provide the desired priority.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
39
40. SUSTOS:
It allows only one program to execute at a time.
Example- the Palm OS for Palm handled computers.
SUMOS:
Allows single user to perform several tasks simultaneously.
We usually use this in desktop and laptop computers.
Example- typing in Ms-Word while listening a song & downloading a file from the
Internet.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
40
41. MUMOS:
It enables multiple users on different computers to access a single system.
By one CPU and one OS, many terminals can connect to the main computer.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
41
42. MP:
It means two or more processors(CPUs) within a single computer system.
Complex programs can be divided into smaller programs.
Multiplicity of the processors and how they do act together are transparent to the others.
Following are some advantages of this type of system:-
--Enhanced performance
-- Execution of several tasks by different processors concurrently, increases the
system's throughput without speeding up the execution of a single task.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
42
43. RTOS
It guarantees the maximum time for critical operations and complete them on time.
Real-time systems are used when there are rigid time requirements.
It is referred to as Hard Real-Time Operating Systems.
Hard real-time systems guarantee that critical tasks complete on time.
RTOS are used to control machinery, scientific instruments and industrial systems.
Soft real-time systems are less restrictive.
For example, multimedia, virtual reality, Advanced Scientific Projects like undersea
exploration and planetary rovers, etc.
Some more examples, Scientific experiments, medical imaging systems, industrial
control systems, weapon systems, robots, air traffic control systems, etc
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
43
44. NOS
It runs on a server.
It provides the server the capability to manage data, users, groups,
security, applications, and other networking functions.
It allows shared file and printer access among multiple computers in a
network.
Examples of network operating systems include Microsoft Windows
Server 2003, Microsoft Windows Server 2008, UNIX, Linux, Mac OS X,
Novell NetWare, and BSD.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
44
45. Advantages of network operating systems:
--Centralized servers are highly stable.
--Security is server managed.
Disadvantages
High cost of buying and running a server.
Dependency on a central location for most operations.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
45
46. TSOS
time sharing systems are an extension of multiprogramming systems.
the prime focus is on minimizing the response time.
Multiple jobs are executed by the CPU by switching between them.
i.e the user can receive an immediate response.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
46
Advantages Disadvantages
Provides the advantage of quick response. Question of security and integrity of user
programs and data.
Avoids duplication of software. Problem of reliability.
Reduces CPU idle time. Problem of data communication.
47. DOS
It use multiple central processors to serve multiple real-time applications and
multiple users.
Processors communicate with one another through various communication
lines (such as high-speed buses or telephone lines).
These are referred as loosely coupled systems or distributed systems.
These processors are referred as sites, nodes, computers, and so on.
Advantages
Better service to the customers.
Reduction of the load on the host computer.
Reduction of delays in data processing.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
47
48. NUMBER SYSTEM: BINARY, OCTAL, DECIMAL AND
HEXADECIMAL
Data is stored in a computer in the form of 0s & 1s.
A number is represented by a string of digits, where each digit position has an associated
weight.
Each number system is associated with a base or radix.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
48
System Base Symbols
Used by
humans?
Used in
computers?
Decimal 10 0, 1, … 9 Yes No
Binary 2 0, 1 No Yes
Octal 8 0, 1, … 7 No No
Hexadecimal 16 0, 1, … 9,A, B,..F No No
49. BINARY:
1. Convert 1101 into a decimal number.
Decimal number = 1*23 + 1*22 + 0*21 +1*20
= 1 * 8 + 1* 4 + 0 +1*1
= 8 + 4+ 0+ 1
= 13.
2. Convert (13)10 into a binary number.
13/2 = 6 rem 1
6/2 = 3 rem 0
3/2 = 1 rem 1
1/2 = 1 rem 1
(13)10 =(1101)2
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
49
50. OCTAL:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
50
The octal number system: Base-8
Eight digits: 0,1,2,3,4,5,6,7
The hexadecimal number system: Base-16
Sixteen digits: 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
For our purposes, base-8 and base-16 are most useful as a “shorthand”
notation for binary numbers
10
1012
8 )5.87(84878281)4.127(
10
0123
16 )46687(16151651661611)65( FB
51. NUMBERS WITH DIFFERENT BASE:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
51
Decimal Binary Octal Hex
0 0000 0 0
1 0001 1 1
2 0010 2 2
3 0011 3 3
4 0100 4 4
5 0101 5 5
6 0110 6 6
7 0111 7 7
8 1000 10 8
9 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
52. 4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
52
Converting from octal to binary: Replace each octal digit with its equivalent 3-
bit binary sequence
Converting from binary to octal: Make groups of 3 bits, starting from the
binary point. Add 0s to the ends of the number if needed. Convert each bit
group to its corresponding octal digit.
= 6 7 3 . 1 2
= 110 111 011 . 001 010
=
8)12.673(
2)001010.110111011(
10110100.0010112 = 010 110 100 . 001 0112
= 2 6 4 . 1 38
53. BINARY AND HEX CONVERSIONS
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
53
Converting from hex to binary: Replace each hex digit with its
equivalent 4-bit binary sequence
Converting from binary to hex: Make groups of 4 bits, starting from the
binary point. Add 0s to the ends of the number if needed. Convert each
bit group to its corresponding hex digit.
261.3516 = 2 6 1 . 3 516
= 0010 0110 0001 . 0011 01012
10110100.0010112 = 1011 0100 . 0010 11002
= B 4 . 2 C16
54. BINARY ARITHMETIC:
Rules of Binary Addition
0 + 0 = 0, 0+1 = 1, 1+0 = 1
1+1 = 0, and carry 1 to the next more significant bit.
Rules of Binary Subtraction
0 - 0 = 0, 1-0 = 1, 1-1 = 0
0-1= 0, and borrow 1 from the next more significant bit.
Rules of Multiplication
0 * 0 = 0, 1*0 = 0, 1*1 = 1, 0*1= 0
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
54
55. BASICS OF PROGRAMMING:
Program is a set of instruction to solve the problem.
‘C’ has now become a widely used professional language for various
reasons.
Easy to learn
Structured language
It produces efficient programs.
It can handle low-level activities.
It can be compiled on a variety of computers.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
55
56. SOME FACTS ABOUT “C”
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around 1970
The language was formalized in 1988 by the American National
Standard Institute (ANSI).
By 1973 UNIX OS almost totally written in C.
Today C is the most widely used System Programming Language.
Most of the state of the art software have been implemented using C.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
56
57. WHY TO USE “C”
C was adopted as a system development language.
It produces code that runs nearly as fast as code written in assembly language.
Some examples of the use of C might be:
Operating Systems Language Compilers
Assemblers Text Editors
Print Spoolers Network Drivers
Modern Programs Data Bases
Language Interpreters Utilities
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
57
58. APPROACHES TO PROBLEM SOLVING
People who are really good at solving problems go about it
systematically.
They have a way of placing the problem in context.
They don't jump to conclusions.
They evaluate alternatives.
A good way to become a systematic problem solver is to
adopt the following five-step problem-solving process.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
58
59. IDENTIFY THE PROBLEM.
This is critical: you must try to solve the right
problem.
Identify the right problem by asking the right
questions and observing.
You cannot identify the customer's problems
by presenting your products.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
59
60. ANALYZE THE PROBLEM.
How often does the problem occur?
How severe is it?
Are there any special circumstances that are
present when it occurs?
What might be the causes of the problem?
Can you rule out any causes?
How long has it been going on?
Has it gotten worse?
How is the problem affecting other processes or people?
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
60
62. IDENTIFY DECISION CRITERIA.
How will you and the customer make decisions when it is time to
decide?
How will you weigh the criteria?
Can you identify independent standards that can be used?
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
62
63. DEVELOP MULTIPLE SOLUTIONS.
Don't stop at the first solution that you or others identify.
It may be good, but much better ones may exist.
Evaluate alternative scenarios.
As objectively as possible, assess the pros and cons of each.
Choose the optimal solution.
Use the criteria you developed in the third step of this problem-solving
process to choose the best solution.
Develop a base of support that will ensure you can implement the
solution.
Prepare for contingencies.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
63
64. CONCEPT OF ALGORITHM AND FLOWCHARTS
The sequence of steps to be performed in order to solve a
problem by the computer is known as an algorithm.
Three reasons for using algorithms are efficiency, abstraction and reusability.
Flowchart is a diagram that shows the step-by-step execution of a control
structure.
Flowchart is a graphical or symbolic representation of an algorithm.
It is the diagrammatic representation of the step-by-step solution to a given
problem.
A diamond-shaped box represents a decision.
A rectangular box represents an assignment statement or a process.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
64
65. EXAMPLE OF ALGORITHM
Write an algorithm to add two numbers.
STEP1 Read the Value of A and B.
STEP2 SUM = A+B.
STEP3 Display SUM.
STEP4 Stop.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
65
66. EXAMPLE OF A FLOWCHART
Write (Display) the Sum, Average and Product
Flowchart for the above problem will look like
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
66
Start
Read X,Y,Z
S= X+Y+Z
A=S/3
P=X*Y*Z
Write S,A,P
Stop
67. ADVANTAGES OF USING FLOWCHARTS:
Communication: Flowcharts are better way of communicating
the logic of a system to all concerned.
Effective analysis: With the help of flowchart, problem can be
analyzed in more effective way.
Proper documentation:Program flowcharts serve as a good
program documentation, which is needed for various purposes.
Efficient Coding: The flowcharts act as a guide or blueprint
during the systems analysis and program development phase.
Proper Debugging: The flowchart helps in debugging process.
Efficient Program Maintenance:The maintenance of operating
program becomes easy with the help of flowchart. It helps the programmer to
put efforts more efficiently on that part.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
67
68. ASSIGNMENT NO-1 DATE:-22/02/2017
Q1. Explain digital computer in detail.
Q2. Write five input and output devices.
Q3. Give the difference between RAM and ROM.
Q4. Write short note on Binary Conversions.
Q5. Give the difference between program, algorithm, and
flowchart.
Note: You can submit assignment in a hard copy or soft copy.
Last Date:- 25/02/2017
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
68
69. Example Of A If-else Flowchart
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
69
70. 4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
70
Start
Read A, B
Is A > B
Print A Print B
End
Yes No
Flow Chart to find largest of two numbers:
71. LIMITATIONS OF USING FLOWCHARTS:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
71
Complex logic: Sometimes, the program logic is quite complicated. In that
case, flowchart becomes complex and clumsy.
Alterations and Modifications: If alterations are required the flowchart may
require re-drawing completely.
Reproduction: As the flowchart symbols cannot be typed, reproduction of
flowchart becomes a problem.
72. TYPES OF COMPUTER LANGUAGES: MACHINE,
ASSEMBLY, & HIGH LEVEL LANGUAGES
A programming language is an artificial language that can be used to
control the behavior of a machine, particularly a computer .
Programming languages, like human languages, are defined through
the use of syntactic and semantic rules, to determine structure and
meaning respectively.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
72
73. MACHINE LANGUAGE:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
73
• It is the lowest-level programming language.
Machine languages are the only languages understood by
computers.
74. ASSEMBLY LANGUAGE:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
74
An assembly language is a low-level language for programming computers.
The word "low" does not imply that the language is inferior to high-level
programming languages but rather refers to the small or nonexistent amount of
abstraction between the language and machine language, because of this, low-level
languages are sometimes described as being "close to the hardware."
It implements a symbolic representation of the numeric machine codes and other
constants needed to program a particular CPU architecture.
75. HIGH LEVEL LANGUAGE:
High-level languages are relatively easy to learn because the
instructions bear a close resemblance to everyday language, and
because the programmer does not require a detailed knowledge of the
internal workings of the computer.
Each instruction in a high-level language is equivalent to several
machine-code instructions, therefore it is more compact than equivalent
low-level programs.
High-level languages are used to solve problems and are often
described as problem-oriented languages
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
75
76. Concept of Assembler
It translates the assembly language into machine level language.
Translate mnemonic operation codes to machine code.
Assign addresses to symbolic labels used by the programmer
Fig1. The flow of assembler
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
76
Assembler
Assembly language code Object code
77. COMPILER:
It is a program translator that translates the instruction of a higher level
language to machine language.
It is called compiler because it compiles machine language instructions for
every program instructions of higher level language.
The programs written by the programmer in higher level language is called
source program.
After this program is converted to machine languages by the compiler it is called
object program.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
77
78. INTERPRETER:
An interpreter is another type of program translator used for translating
higher level language into machine language.
It takes one statement of higher level languages, translate it into machine
language and immediately execute it.
Translation and execution are carried out for each statement.
It differs from compiler, which translate the entire source program into
machine code.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
78
High level language interpreter Low level language
79. LOADER:
Software that copies programs
from a storage device to the
main memory, where they can be
executed.
A loader is a special type of
program that is part of an OS.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
79
Object code
source code
Assembly code
Executable code
compiler
Preprocessor
assembler
Link editor
libraries
80. LINKER:
Software that transforms source code written in a programming language into
machine language comprising of just two digits, 1 & 0.
It is also called link editor and binder.
It combines object modules to form an executable program.
TRANSLATOR:
A computer program, which translates a code written in one programming
language to a code in another language that the computer understands.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
80
81. UNIT-2 STANDARD I/O IN “C”
When we say Input, it means to feed some data into a program.
When we say Output, it means to display some data on screen, printer, or in
any file.
The Standard Files
C programming treats all the devices as files.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
81
Standard File File Pointer Device
Standard input stdin Keyboard
Standard output stdout Screen
Standard error stderr Your screen
82. STANDARD I/O IN “C”
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scan() function reads formatted input from standard input (keyboard).
The printf() function sends formatted output to the standard output (screen).
#include <stdio.h> //This is needed to run printf() function.
int main() {
printf(“ C programming”); // displays the content inside quotation.
return 0;
}
OUTPUT
C programming
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
82
83. TYPES AND THEIR VALUES
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
83
Predefined Types Values
Read Character from File getc, fgetc and getchar
Write Character to File putc, fputc and putchar
Read String from File fgets and gets
Read Binary Data from File fread
Write String to File fputs and puts
Write Binary Data to File fwrite
Read Formatted Input scanf, fscanf, sscanf
Write Formatted Output printf, fprintf, sprintf
File Position fgetpos, fsetpos, rewind, fseek, and ftell
84. FUNDAMENTAL DATA TYPES:
A data type is--
A set of values AND.
A set of operations on those values.
A data type is used to--
Identify the type of a variable when the variable is declared.
Identify the type of the return value of a function.
Identify the type of a parameter expected by a function.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
84
85. FUNDAMENTAL DATA TYPES:
void – used to denote the type with no values
int – used to denote an integer type
char – used to denote a character type
float, double – used to denote a floating point type
int *, float *, char * – used to denote a pointer type,
which is a memory address type.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
85
86. TWO CLASSIFICATIONS OF DATA TYPES
Built-in data types
Fundamental data types (int, char, double, float, void,
pointer)
Derived data types (array, string, structure)
Programmer-defined data types
Structure
Union
Enumeration
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
86
87. DERIVED DATA TYPES:
Array – a finite sequence (or table) of variables of the same data type
String – an array of character variables
Structure – a collection of related variables of the same and/or different
data types. The structure is called a record and the variables in the
record are called members or fields
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
87
88. PRIMARY DATA TYPES
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
88
PDT(Integer)
Signed
int
Short int
Long int
Unsigned
Unsigned
int
Unsigned
short int
Unsigned
long int
89. SINGLE AND DOUBLE FLOATING POINT
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
89
Floating point type
float
double
Long double
91. SIZE & RANGE OF DATA TYPES:
Type Size(bits/bytes) Range
Char or signed char 8/1 -128 to 127
Unsigned char 8/1 0 to 255
int or signed int 16/2 - 32768 to 32767
Unsigned int 16/2 0 to 65535
Short int or
Signed short int 8/1 -128 to 127
Unsigned short int 8/1 0 to 255
Long int or
Signed long int 32/4 -2147483648 to 2147483647
Unsigned long int 32/4 0 to 4294967295
float 32/4 3.4 E- 38 to 3.4 E + 38
double 64/8 1.7 E – 308 to 1.7 E + 308
Long double 64/8 3.4 E- 4932 to 3.4 E + 4932
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
91
92. STORAGE CLASSES: AUTOMATIC, REGISTER, STATIC
AND EXTERNAL
A storage class defines the scope (visibility) and life time of variables
and/or functions within a C Program.
There are following storage classes which can be used in a C Program
• Auto (automatic variables)
• Register variables
• Static variables
• Extern(external variables)
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
92
93. AUTO - STORAGE CLASS
auto is the default storage class for all local variables.
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class.
auto can only be used within functions, i.e. local variables.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
93
94. AUTO - STORAGE CLASS
Formal parameters and local variables of functions are variables that
are automatically allocated on the stack when a function is called and
automatically deallocated when the function returns.
They are of storage class auto.
By default they are assigned garbage value by the compiler.
Example
void main()
{
int detail; or
auto int detail; //Both are same
}
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
94
95. REGISTER - STORAGE CLASS
register is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum
size equal to the register size (usually one word) and cant have the
unary '&' operator applied to it (as it does not have a memory location).
{
register int Miles;
}
Register should only be used for variables that require quick access -
such as counters.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
95
96. REGISTER VARIABLES
If you declare a variable of type register, it simply alerts the compiler to
the fact that this memory cell will be referenced more often than most.
Register is a special high-speed memory location inside the central
processor.
Syntax :
register int number;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
96
97. STATIC VARIABLES:
Static variable is allocated and initialized one time, prior to program
execution.
It remains allocated until the entire program terminates.
A static variable tells the compiler to persist the variable until the end of
program.
static is initialized only once and remains into existence till the end of
program.
Scope of internal static variable remains inside the function in which it
is defined.
External static variables remain restricted to scope of file in each they
are declared.
They are assigned 0 (zero) as default value by the compiler.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
97
99. EXTERNAL VARIABLES
The extern keyword is used before a variable to inform the compiler
that this variable is declared somewhere else.
The extern declaration does not allocate storage for variables.
A variable that is declared outside any function is a Global variable.
Problem when extern is not used
main()
{
a = 10; // Error: cannot find variable a
printf("%d", a);
}
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
99
100. EXTERN:
Storage class of names known to the linker.
Example: extern int square (int x);
Means the function will be available to the linker.
It notifies the compiler that such a function exists and that the linker
will know where to find it.
int number;
void main() {
number=10; }
fun1() {
number=20; }
fun2() {
number=30; } Here the global variable number is available to all three
functions.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
100
101. OPERATORS AND EXPRESSIONS:
Operators form expressions by joining individual constants, variables, array elements.
Operators are symbols which take one or more operands or expressions and perform
arithmetic or logical computations.
C includes a large number of operators which fall into different categories.
These operators are used to form expressions. Some operators are as follows-
--arithmetic operators,
--unary operators,
--relational and logical operators,
--assignment operators and the
--conditional operators
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
101
102. OPERATOR PRECEDENCE:
Consider the following arithmetic operation:
- left to right
6 / 2 * 1 + 2 = 5
- right to left
6/2 * 1 + 2 = 1
- using parentheses
= 6 / (2 * 1) + 2
= (6 / 2) + 2
= 3 + 2
= 5
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
102
103. USING NUMERIC AND RELATIONAL OPERATORS:
--Arithmetic operators:
There are five main arithmetic operators in ‘C’.
They are ‘+’ for additions,
‘-' for subtraction,
‘*’ for multiplication,
‘/’ for division and
‘%’for remainder after integer division.
This ‘%’ operator is also known as modulus operator.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
103
104. ARITHMETIC OPERATORS:
Operator example Meaning
+ a + b Addition –unary
- a – b Subtraction-
unary
* a * b Multiplication
/ a / b Division
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
104
105. EXAMPLE OF ARITHMETIC OPERATOR
Operands can be integer quantities, floating-point quantities or
characters.
Example m=30 & n=20 respectively , now performing addition,
subtraction, multiplication, division, and modulus on m& n, we get…….
m+n=50
m-n=10
m*n=600
m/n=1
m%n=10
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
105
106. UNARY OPERATORS:
‘C’ includes a class of operators that act upon a single operand to
produce a new value.
Such operators are known as unary operators.
Unary operators usually precedes their single operands,
though some unary operators are written after their operands.
The most common unary operator is unary minus, where a minus
sign precedes a numerical constant, a variable or an expression.
e.g. -5,-10, -20(numbers)
x=-y(variable)
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
106
107. MIXED OPERANDS:
When one of the operands is real and the other is integer.
If either operand is of the real type, then only the real operation is
performed .
Then the result is always a real number.
Example ---
15 / 10.0 = 1.5
Whereas
15 / 10 = 1.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
107
108. TYPE CONVERSION:
Type conversion is done when the expression has variables of different
data types.
The data type is promoted from lower to higher level.
Type conversion is automatically done when the value is assign.
The hierarchy of data types (from higher to lower) is shown as:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
108
109. CONVERSION HIERARCHY OF DATA TYPES
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
109
Long double
double
int
short
float
Unsigned long int
Long int
unsigned int
char
110. EXAMPLE1
Consider the code given below
float x;
int y= 3;
x=y;
Now here integer value is promoted to float.
This is known as promotion.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
110
111. EXAMPLE2
Now, x= 3.0, as automatically integer value is converted into its
equivalent floating point representation.
Consider the following group of statements:
float f= 3.5;
int i;
i= f;
Statement i= f results in f to be demoted to type int,
the fractional part of f will be lost and I will contain 3 (not 3.5).
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
111
112. RELATIONAL OPERATORS:
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal
to
== Equal to
!= Not equal to
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
112
113. LOGICAL OPERATORS:
For relational expression, 0 is FALSE, 1 is TRUE.
Any numeric value is interpreted as either TRUE or FALSE when it is used in a C /
C++ expression or statement that is expecting a logical (true or false) value. The rules
are:
1. A value of 0 represents FALSE.
2. Any non-zero (including negative numbers) value represents TRUE.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
113
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
114. LOGICAL OPERATORS:
Expressions Evaluates as
(3 == 3) && (4 != 3)
True (1) because both operands are
true
(4 > 2) || (7 < 11)
True (1) because (either) one
operand/expression is true
(3 == 2) && (7 == 7) False (0) because one operand is false
! (4 == 3)
True (1) because the expression is
false
(3 == 3) && (4 != 3)
True (1) because both operands are
true
NOT(FALSE) = TRUE
NOT(TRUE) = FALSE
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
114
115. BIT OPERATORS:
A bit is the smallest digit capable of being stored in a modern day digital
computer.
A byte, consisting of 8 bits is the smallest unit of storage that a computer can work
with.
A word ( usually somewhere between 32 and 64 bits) is the smallest addressable
item in a computer.
---The word size of a computer is usually dictated by either the bus size of the
system or the word size of the CPU.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
115
116. BITWISE OPERATORS:
Operator Name Description
& bitwise AND 1 only if both operands are 1.
| bitwise OR 1 if ether or both operands are
1
^ bitwise exclusive or 1 if either but not both
operands are 1
<< Left Shift Shifts bits of the first operand
by the number of bits specified
by the second operand.
>> Right Shift Shifts bits of the first operand
by the number of bits specified
by the second operand.
~ Complement Flips the bits in the operand.
All 1’s become 0’s and all 0’s
become 1’s.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
116
117. BITWISE OPERATORS:
Bitwise operators are used to directly manipulate the bits of
integral operands such as char, short, int, long (both signed
and unsined).
Normally unsigned integers are used when dealing with
bitwise operations.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
117
118. ASSIGNMENT OPERATORS:
The compound assignment operators consist of a binary operator and
the simple assignment operator.
They perform the operation of the binary operator on both operands
and store the result of that operation into the left operand.
The following table lists the simple and compound assignment
operators and expression examples:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
118
119. Simple Assignment Operator
=
The simple assignment operator has the following form:
lvalue = expr
The operator stores the value of the right operand expr in the
object designated by the left operand lvalue.
The left operand must be a modifiable lvalue.
The type of an assignment operation is the type of the left
operand.
i = 5 + x;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
119
120. CONDITIONAL OPERATORS:
Syntax:
exp1 ? exp2 : exp3
Where exp1,exp2 and exp3 are expressions
Working of the ? Operator:
Exp1 is evaluated first, if it is nonzero(1/true) then the expression2 is evaluated
and this becomes the value of the expression,
If exp1 is false(0/zero) exp3 is evaluated and its value becomes the value of the
expression
Ex: m=2;
n=3
r=(m>n) ? m : n;
4/23/2019
ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
120
121. OPERATOR PRECEDENCE AND ASSOCIATIVELY :
The operator within C are grouped hierarchically according to their order of evaluation
known as precedence.
operations with a higher precedence are carried out before operations having a lower
precedence.
Arithmetic operators *,/ and % are under one precedence group and
+,- are under another precedence group.
The operators *, / and % have higher precedence than + and -.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
121
122. Consecutive operations within the same precedence group are carried
out. This is known as associativity.
Example, say there are 3 variables a, b, and c having values 5,10 and
15 respectively.
The different operations on these three variables and their result is as
follows:
a+b/c=5,
b*c-a=145
a*b/c= 3,
(a+c)*b/a=40
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
122
123. OPERATOR PRECEDENCE:
Precedence and Associativity of C Operators
Symbol Type of Operation Associativity
[ ] ( ) . –> postfix ++ and
postfix ––
Expression Left to right
prefix ++ and prefix –– sizeof
& * + – ~ !
Unary Right to left
typecasts Unary Right to left
* / % Multiplicative Left to right
+ – Additive Left to right
<< >> Bitwise shift Left to right
< > <= >= Relational Left to right
== != Equality Left to right
& Bitwise-AND Left to right
^ Bitwise-exclusive-OR Left to right
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
123
125. FUNDAMENTALS OF C PROGRAMMING:
C was developed in 1972 by “Dennis Ritchie” at AT & T Bell Lab.
It was developed for the ease of programming.
Some features for which it is so popular:
---It is very calm to learn
---It is a planned language
---It produces well-organized programs.
---It can handle low-level activities.
---It can be compiled on a multiplicity of computers.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
125
126. STRUCTURE OF C PROGRAM
An example of simple program in C
#include <stdio.h>
void main(void)
{
printf(“I love programmingn”);
printf(“You will love it too once ”);
printf(“you know the trickn”);
}
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
126
Preprocessor directive
Null Data Type
Closing parenthesis
Angle bracket
Standard input output
function
Line termination
127. WRITING AND EXECUTING THE FIRST C PROGRAM
#include<stdio.h>
#include<conio.h>
Void main()
{
clrscr();
Int a, b, c;
Printf(“enter the value of a & b”);
Scanf(“%d %d”, &a, &b);
c= a+b;
Printf(“value of c is =%d”, c);
getch();
}
OUTPUT
Enter the value of a & b
5 5
10
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
127
128. COMPONENTS OF C LANGUAGE
Some basic component of a C program.
#include - The #include is known as a preprocessor directive
It is used to tell the C preprocessor to find the stdio file with
extension .h.
main() – Execution of a program starts from a main() function.
printf() - This is the standard way of producing output.
The functionality of printf() is referenced in stdio.h by the C
compiler.
scanf() - This is the standard way of taking input from user.
comments: Comments are information given by the program to make
a program readable and easy to understand.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
128
129. STANDARD I/O IN C
So far our C programs are as follows:
/* description of program */
#include <stdio.h>
/* any other includes go here */
int main(){
/* program body */
return 0;
}
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
129
130. UNIT-3 CONDITIONAL PROGRAM EXECUTION
C supports two types of decision control statements.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
130
Selection/Branching
statement
Conditional type
if If-else If-else-if switch
Unconditional
type
131. CONDITIONAL BRANCHING STATEMENTS:
These statements helps to jump from one part to another part.
Whether a particular condition is satisfied or not.
It includes:-
---- if statement
---- if- else statement
---- if- else- if statement
---- Switch statement
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
131
132. IF STATEMENTS
The if statement allows the program to test the state of the program
variables using a Boolean expression.
Syntax
If (test expression)
{
Statement 1;
……………
Statement n;
}
Statement x;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
132
Test
exp
Statement block
1
Statement x
FALSE
TRUE
133. IF-ELSE STATEMENT
The if-else statement expresses simplest decision making.
The syntax is
if (expression)
statement1
elseopt
Statement2
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
133
138. SWITCH STATEMENT
The switch statement is used to select one of several alternatives when the
selection is based on the value of a single variable or an expression.
switch (controlling expression) {
case label1:
statement1
break;
case label2:
statement2
break; ……..
case labeln:
statementn
break;
default:
statementd; }
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
138
If the result of this controlling expression
matches label1, execute staement1 and then break
this switch block.
If the result matches none of all labels, execute the
default statementd.
139. USE OF BREAK AND DEFAULT WITH SWITCH
Switch (exp)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
…………….
…………….
default:
default-block
break; } statement-x;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
139
140. PROGRAM LOOPS AND ITERATIONS:
In looping, a sequence of statements are executed until some
conditions for termination of the loop are satisfied.
Two segments are:
------- body of the loop
------- control statement
Depending on the position of the control statement in the loop,
A control structure may be either—
-------- entry controlled loop or
-------- exit controlled loop.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
140
141. LOOP CONTROL STRUCTURES
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
141
True
Test
condition
?
Test
condition
?
Body of the
loop
Body of the
loop
False
False
True
EntryEntry
(b) Exit controlled loop(a) Entry controlled loop
142. USE OF WHILE:
THE WHILE STATEMENT IS USED TO REPEAT A COURSE OF
ACTION.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
142
143. THE WHILE STATEMENT
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
143
Format
While (test condition)
{
Body of the loop
Syntax
Statement x;
While (condition)
{
statement block;
}
Statement y;
WAP to calculate the sum
of first 10 nos.
int i= 1, sum= 0;
while(i<=10)
{
sum = sum +1;
i= i+1;
}
printf(“n sum =% d”, sum);
return 0;
}
OUTPUT
Sum= 55
144. DO WHILE
DO STATEMENT
The do statement is a variant of the while statement that tests its
condition at the bottom of the loop.
General Form of the do Statement-
do
statement
while (expr);
next statement
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
144
do
{
body of the loop
}
while (test-condition);
145. EXAMPLE OF DO-WHILE STATEMENT
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
145
int i =1;
do
{
printf(“n % d”, i);
i=i+1;
}
while(i<=10);
return 0;
}
The code will print nos
from 1 to 10.
146. COMPARISON B/W WHILE, DO, FOR
WHILE DO FOR
while (...) {
...
continue;
...
cont: ;
}
do {
...
continue;
...
cont: ;
}
for (...) {
...
continue;
...
cont: ;
}
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
146
148. SYNTAX OF FOR LOOP
for (initialization ; test-condition ; increment)
{
body of the loop
}
Example
for (i = 1; i<=n ; i++)
{
printf(“n %d”, i);
}
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
148
149. MULTIPLE LOOP VARIABLES
MLV are the loops which can be placed inside other loops.
Example:
………..
………..
while(……..)
{
for(………)
{ …….
……..
if (……..) goto end_of_program;
………
}
………
………
} end_of_program
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
149
Jumping out
of loops
150. USE OF BREAK AND CONTINUE STATEMENTS.
The break statement causes an exit from the innermost enclosing
loop or switch statement.
The continue statement causes the current iteration of a loop to
stop and the next iteration to begin immediately.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
150
151. DIFFERENCE B/W BREAK & CONTINUE
break continue
while (……)
{
if (condition)
break;
………..
}
……….
Transfers control out of the loop while.
Example
int i = 1;
while (i<= 10)
{
if (i==5)
break;
printf(“n % d”, i);
i=i+1; }
return 0; }
while (……)
{
……….
if (condition)
continue;
………..
}
Transfers control to the condition
expression of the while loop.
Example
int i = 1;
for (i=1; i<=10; i++)
{
if (i==5)
continue;
printf(“t % d”, i);
}
return 0; }
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
151
152. THE GOTO STATEMENT
GOTO is used to branch unconditionally from one point to another.
The general forms of goto & label statements are shown below:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
152
goto label;
………….
………….
………….
label;
Statement;
label;
statement;
………….
………….
………….
goto label;
Forward jump Backward jump
153. FUNCTIONS:
A complex problem is often easier to solve by dividing it into several
smaller parts, each of which can be solved by itself.
This is called structured programming.
These parts are sometimes made into functions in C.
main() then uses these functions to solve the original problem.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
153
154. Main() Function Calls Func1()
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
154
main()
{
…………
func1();
…………
return 0;
}
func1()
{
Statement block;
}
Main
function
Function A Function B
Function B1 Function B2
Function c
155. DEFINITION OF FUNCTIONS:
A function definition shall include the following elements:
1. Function name;
2. Function type;
3. List of parameters;
4. Local variable declarations;
5. Function statements; and
6. A return statement.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
155
Function header
Function body
156. FUNCTIONS WITH ARRAY
Example, the call
largest (a, n)
Will pass the whole array a to the called function.
The largest function header might look like:
float largest (float array [ ], int size)
The declaration of the formal argument array is made as follows:
float array [ ];
The pair of brackets informs the compiler that the argument array is as
array of numbers.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
156
157. PASSING VALUES TO FUNCTIONS
Three rules to pass an array to a function:
A. The function must be called by passing only the name of the
array.
B. In the function definition, the formal parameter must be an array
type; the size of the array does not need to be specified.
C. The function prototype must show that the argument is an array.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
157
158. RECURSIVE FUNCTIONS
Recursion: the ability of a subprogram to call itself.
Each recursive solution has at least two cases
base case: the one to which we have an answer
general case: expresses the solution in terms of a call to itself with a smaller
version of the problem.
For example, the factorial of a number is defined as the number times the product of all
the numbers between itself and 0:
N! = N * (N 1)!
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
158
159. UNIT-4 ARRAYS
An array is a named collection of homogeneous items in which individual
items are accessed by their place within the collection.
An array is a collection of variables of the same type that are referred to by a
common name.
Eg.
product part numbers:
int part numbers[] = {123, 326, 178, 1209};
student scores:
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};
characters:
char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
159
160. INITIALIZATION OF ARRAY
Array – a set of elements all of the same type stored contiguously in
memory – e.g.,
int A[25]; // 25 integers
struct Str B[15]; /* 15 objects of
type struct Str */
double C[]; /* indeterminate #
of doubles */
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
160
161. ARRAY NOTATION
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
161
An array of size N is indexed from zero to N-1
79 87 94 82 67 98 87 81 74 91scores
The entire array
has a single name
Each value has a numeric index
This array holds 10 values that are indexed from 0 to 9
162. MANIPULATING ARRAY ELEMENTS
Some other examples of array declarations:
float[] prices = new float[500];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[1750];
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
162
163. 2D ARRAY
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
163
A one-dimensional array stores a list of elements
A two-dimensional array can be thought of as a table of elements,
with rows and columns
one
dimension
two
dimensions
164. 3D ARRAY
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
164
An array can be declared with multiple dimensions.
2 Dimensional 3 Dimensional
Multiple dimensions get difficult to visualize graphically.
•
int [][][] table3 = { { {1,2}, {3,4} },
{ {5,6,7} , {8}, {9,10}
}
};
165. USING MULTI-DIMENSIONAL ARRAYS
An array can have many dimensions – if it has more than one
dimension, it is called a multidimensional array
Each dimension subdivides the previous one into the specified number
of elements
Each dimension has its own length constant
Because each dimension is an array of array references, the arrays
within one dimension can be of different lengths
these are sometimes called ragged arrays
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
165
166. MULTIDIMENSIONAL ARRAY
Arrays with more than one index
number of dimensions = number of indexes
Arrays with more than two dimensions are a simple extension of
two-dimensional (2-D) arrays
A 2-D array corresponds to a table or grid
one dimension is the row
the other dimension is the column
cell: an intersection of a row and column
an array element corresponds to a cell in the table
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
166
168. STRUCTURE:
A structure is a collection of one or more components (members).
Structures are called records in many other programming languages.
Members are known as fields.
Declaring a structure:-
struct {
char name[25];
int id, age;
char sex;
} s1, s2;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
168
169. INITIALIZING A STRUCTURE:-
struct {
char name[25];
int id, age;
char sex;
}
s1 = { "Smith, John", 2813, 25, 'M'},
s 2 = { "Smith, Mary", 4692, 23, 'F'};
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
169
170. ACCESSING THE MEMBERS OF A STRUCTURE:
The members of a structure are accessed by writing first the name
of the structure, then a period, then the name of the member:
struct student {
char name[25];
int id, age;
char sex;
} s;
strcpy(s.name, "Doe, John");
s.id = 18193;
s.age = 18;
s.sex = 'M';
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
170
173. INITIALIZATION OF STRUCTURE
ARRAYS
Structure arrays are initialized by enclosing the list of values of its
elements within a pair of braces.
Example:
struct unit
{ char ch ;
int i ;
} ;
struct unit series [3]=
{ (‘a’, 100) (‘b’, 200) (‘c’, 400)
};
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
173
174. UNION:
A union is similar to a structure, except that its members are
overlaid (located at the same memory address).
A union is like a structure in which all members are stored at the
same address.
Example:
union {
int i;
double d;
} u;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
174
175. ACCESSING THE MEMBER
The members of a union are accessed in the same way as members of
a structure:
u.i = 15;
or
u.d = 8.89;
Since u.i and u.d have the same memory address, changing the value
of one alters the value of the other.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
175
176. Difference Between Structure & Union
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
176
// declaring structure
struct struct_example
{
int integer;
float decimal;
char name[20];
};
// declaring union
union union_example
{
int integer;
float decimal;
char name[20];
};
180. ENUMERATED DATA TYPES
Enumeration Data Types
Declaration
Assignment
Operations
Looping with Enumeration
Types
A data type is
A set of values together
with
A set of operations on those
values.
A name for the data type.
A set of values for the data
type.
A set of operations on the
values.
4/23/2019
ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
180
182. UNIT-5 POINTERS
• In a generic sense, a “pointer” is anything that tells us where something
can be found.
– Addresses in the phone book
– URLs for webpages
-- Road signs
What actually ptr is?
ptr is a variable storing an address
ptr is NOT storing the actual value of i
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
182
183. EXAMPLE OF POINTER
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
183
int i = 5; ptr
int *ptr;
ptr = &i;
printf(“i = %dn”, i);
printf(“*ptr = %dn”, *ptr);
printf(“ptr = %pn”, ptr);
Output:
i = 5
*ptr = 5
ptr = effff5e0
address of i
5i
value of ptr
= address of
i
in memory
184. POINTER APPLICATIONS IN C PROGRAMMING
Passing Parameter by Reference
Accessing Array element
Dynamic Memory Allocation :
Reducing size of parameter
Some other pointer applications :
--Passing Strings to function
--Provides effective way of implementing the different data
structures such as tree, graph, linked list
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
184
185. FILE HANDLING: GOALS
By the end of this unit we should understand …
… how to open a file to write to it.
… how to open a file to read from it.
… how to open a file to append data to it.
… how to read strings from a file.
… how to write strings to a file.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
185
186. DEFINITION
A file is a collection of related data that a computers treats as a single
unit.
Computers store files to secondary storage so that the contents of files
remain intact when a computer shuts down.
When a computer reads a file, it copies the file from the storage device
to memory; when it writes to a file, it transfers data from memory to the
storage device.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
186
187. OPERATIONS ON FILE
Opening a file
Reading data from a file
Writing data to a file
Closing a file
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
187
188. OPENING A FILE
A file must be “opened” before it can be used.
FILE *fp;
:
fp = fopen (filename, mode);
fp is declared as a pointer to the data type FILE.
filename is a string - specifies the name of the file.
fopen returns a pointer to the file which is used in all subsequent
file operations.
mode is a string which specifies the purpose of opening the file:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
188
189. EXAMPLES
“r” :: open the file for reading only
“w” :: open the file for writing only
“a” :: open the file for appending data to it.
FILE *in, *out ;
in = fopen (“mydata.dat”, “r”) ;
out = fopen (“result.dat”, “w”);
FILE *empl ;
char filename[25];
scanf (“%s”, filename);
empl = fopen (filename, “r”) ;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
189
190. CLOSING A FILE
After all operations on a file have been completed, it must be closed.
Ensures that all file data stored in memory buffers are properly written to
the file.
General format: fclose (file_pointer) ;
FILE *xyz ;
xyz = fopen (“test”, “w”) ;
…….
fclose (xyz) ;
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
190
191. STANDARD C PREPROCESSORS
The C preprocessor executes before a program is compiled.
Some actions it performs are the inclusion of other files in the file being compiled,
definition of symbolic constants and macros, conditional compilation of program code
and conditional execution of preprocessor directives.
Preprocessor directives begin with # and only white-space characters and comments may
appear before a preprocessor directive on a line.
Macro definition
#define, #undef
File inclusion
#include
Conditional Compilation
#if, #ifdef, #ifndef, #elseif, #else
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
191
193. #INCLUDE PREPROCESSOR DIRECTIVE
The #include preprocessor directive has been used throughout
this text.
The #include directive causes a copy of a specified file to
be included in place of the directive.
The two forms of the #include directive are:
#include <filename>
#include "filename"
The difference between these is the location the preprocessor
begins searches for the file to be included.
If the file name is enclosed in quotes, the preprocessor starts
searches in the same directory as the file being compiled for
the file to be included (and may search other locations, too).
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
193
194. #DEFINE PREPROCESSOR DIRECTIVE: SYMBOLIC
CONSTANTS
The #define directive creates symbolic constants—constants represented as symbols—and
macros—operations defined as symbols.
The #define directive format is
#define identifier replacement-text
When this line appears in a file, all subsequent occurrences of identifier that do not appear in
string literals will be replaced by replacement-text automatically before the program is compiled.
Consider the following macro definition with one argument for the area of a circle:
#define CIRCLE_AREA ( x ) ( ( PI ) * ( x ) * ( x ) )
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
194
195. #ERROR AND #PRAGMA PREPROCESSOR DIRECTIVES:
The #error directive
#error tokens
prints an implementation-dependent message including the tokens
specified in the directive.
The tokens are sequences of characters separated by spaces.
For example,
#error 1 - Out of range error
contains 6 tokens.
When a #error directive is processed on some systems, the tokens in
the directive are displayed as an error message, preprocessing stops and
the program does not compile.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
195
196. PREPROCESSOR DIRECTIVES
Directive Function
#define Defines a macro substitution
#undef Undefines a macro
#include Specifies the files to be included
#ifdef Test for a macro definition
#endif Specifies the end of #if
#ifndef Tests whether a macro is not defined
#if Test a compile time condition
#else Specifies alternatives when #if test fails
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
196## token pasting It combines two arguments
197. TYPES OF MACROS
Macro substitution is a process where an identifier in a program is
replaced by a predefined string composed of one or more tokens.
These directives can be divided into three categories:
Macro substitution directives
File inclusion directives
Compiler control directives
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
197
Simple MS
Argumented MS
Nested MS
198. MACRO SUBSTITUTION
General form:
#define identifier string
1. SIMPLE MS:
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
198
MACRO IDENTIFIER STRING
#define COUNT 200
#define FALSE 0
#define SUBJECTS 5
#define PI 3.1415
#define CAPITAL “LUCKNOW”
199. MACRO SUBSTITUTION
2. Argumented MS
The preprocessor permits us to define more complex & more useful form of
replacements.
It takes the form:
#define identifier (f1, f2,………….fn) string
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
199
MACRO IDENTIFIER STRING
#define MAX(a, b) (((a)>(b))?(a):(b))
#define MIN (a, b) (((a)<(b))?(a):(b))
#define ABS(x) (((x)>(0))?(x):(-x))
#define STREQ(s1, s2) (strcmp((s1,)(s2))==0)
#define STRGT(s1, s2) (strcmp((s1,)(s2))>0)
200. MACRO SUBSTITUTION
Nested MS:
We can also use one macro in the definition of another macro.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
200
MACRO IDENTIFIER STRING
#define M 5
#define N M+1
#define SQUARE(x) ((x)* (x))
#define CUBE(x) (SQUARE (x) *(x))
#define SIXTH(x) (CUBE (x) * CUBE (x))
201. CONDITIONAL COMPILATION:
Conditional compilation enables you to control the execution of
preprocessor directives and the compilation of program code.
Each of the conditional preprocessor directives evaluates a constant
integer expression.
Cast expressions, sizeof expressions and enumeration constants cannot
be evaluated in preprocessor directives.
The conditional preprocessor construct is much like the if selection
statement.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
201
202. CONDITIONAL COMPILATION
Structure similar to if
#if !defined( NULL )
#define NULL 0
#endif
Every #if must end with #endif
#ifdef short for #if defined( name )
#ifndef short for #if !defined( name )
Other statements
#elif – equivalent of else if in an if structure
#else – equivalent of else in an if structure
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
202
203. PASSING VALUES TO THE COMPILER
CALL BY VALUE CALL BY REFERENCE
Formal parameters are local variables
to callee.
Values of the actual parameters are
copied to the formal parameters when
function is called.
Conceptually simple.
Values of actual parameters are
protected.
Costly copying if parameters are large.
Can only return 1 value.
Formal parameters are pointers to
actual parameters.
Every use of the formal parameter is
implicitly dereferenced.
Actual parameters must have l-values.
(If not, either prohibit, or create
temporary unnamed variable in caller).
Aliasing problem.
Can’t use in remote procedure call.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
203
204. CALL BY VALUE & CALL BY REFERENCE
4/23/2019
ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
204
#include<stdio.h>
void interchange(int number1, int number2)
{
int temp;
temp = number1;
number1 = number2;
number2 = temp;
}
int main() {
int num1 = 50, num2 = 70;
interchange(num1, num2);
printf(“n Number 1 : %d”, num1);
printf(“n Number 2 : %d”,num2);
return(0); }
206. FILE HANDLING FUNCTIONS
File handling functions Description
fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
fgetc () fgetc () function reads a character from file.
fputc () fputc () functions write a character to file.
gets () gets () function reads line from keyboard.
puts () puts () function writes line to o/p screen.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
4/23/2019ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
206
207. CONTD…..
File handling functions Description
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fputchar ()
fputchar () function writes a character onto the output
screen from keyboard input.
fseek ()
fseek () function moves file pointer position to given
location.
SEEK_SET
SEEK_SET moves file pointer position to the beginning of
the file.
SEEK_CUR SEEK_CUR moves file pointer position to given location.
SEEK_END SEEK_END moves file pointer position to the end of file.
ftell () ftell () function gives current position of file pointer.
rewind ()
rewind () function moves file pointer position to the
beginning of the file.
fflush () fflush () function flushes a file. 4/23/2019
ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
207
208. CONTD……
getc () getc () function reads character from file.
getch () getch () function reads character from keyboard.
getche ()
getche () function reads character from keyboard and
echoes to o/p screen.
getchar () getchar () function reads character from keyboard.
putc () putc () function writes a character to file.
putchar () putchar () function writes a character to screen.
printf () printf () function writes formatted data to screen.
sprinf () sprinf () function writes formatted output to string.
scanf () scanf () function reads formatted data from keyboard.
remove () remove () function deletes a file. 4/23/2019
ANKUR SRIVASTAVA ASSISTANT PROFESSOR JETGI
208
210. STRINGS
A special kind of array is an array of characters
ending in the null character 0 called string arrays
A string is declared as an array of characters
char s[10]
char p[30]
When declaring a string don’t forget to leave a
space for the null character which is also known as
the string terminator character
211. C OFFERS FOUR MAIN OPERATIONS
ON STRINGS
strcpy - copy one string into another
strcat - append one string onto the right side of the other
strcmp – compare alphabetic order of two strings
strlen – return the length of a string
213. EXAMPLE WITH STRCPY
#include <stdio.h>
#include <string.h>
main()
{
char x[] = “Example with strcpy”;
char y[25];
printf(“The string in array x is %s n “, x);
strcpy(y,x);
printf(“The string in array y is %s n “, y);
}
215. EXAMPLE WITH STRCAT
#include <stdio.h>
#include <string.h>
main()
{
char x[] = “Example with strcat”;
char y[]= “which stands for string concatenation”;
printf(“The string in array x is %s n “, x);
strcat(x,y);
printf(“The string in array x is %s n “, x);
}
216. STRCMP
strcmp(stringa, stringb)
Compares stringa and stringb alphabetically
Returns a negative value if stringa precedes
stringb alphabetically
Returns a positive value if stringb precedes stringa
alphabetically
Returns 0 if they are equal
Note lowercase characters are greater than
Uppercase
217. EXAMPLE WITH STRCMP
#include <stdio.h>
#include <string.h>
main()
{
char x[] = “cat”;
char y[]= “cat”;
char z[]= “dog”;
if (strcmp(x,y) == 0)
printf(“The string in array x %s is equal to
that in %s n “, x,y);
218. CONTINUED
if (strcmp(x,z) != 0)
{printf(“The string in array x %s is not equal to that in z %s n “,
x,z);
if (strcmp(x,z) < 0)
printf(“The string in array x %s precedes that in z %s n “, x,z);
else
printf(“The string in array z %s precedes that in x %s n “, z,x);
}
else
printf( “they are equal”);
}
219. STRLEN
strlen(str) returns length of string excluding null character
strlen(“tttt”) = 4 not 5 since 0 not counted
220. EXAMPLE WITH STRLEN
#include <stdio.h>
#include <string.h>
main()
{
int i, count;
char x[] = “tommy tucket took a tiny ticket ”;
count = 0;
for (i = 0; i < strlen(x);i++)
{
if (x[i] == ‘t’) count++;
}
printf(“The number of t’s in %s is %d n “, x,count);
}
221. INPUT OUTPUT FUNCTIONS OF
CHARACTERS AND STRINGS
getchar() reads a character from the screen in a non-interactive
environment
getche() like getchar() except interactive
putchar(int ch) outputs a character to screen
gets(str) gets a string from the keyboard
puts(str) outputs string to screen
222. SOME USEFUL C CHARACTER
FUNCTIONS
Don't forget to #include <ctype.h> to get the function prototypes.
223. FUNCTIONS
Function Return true if
int isalpha(c); c is a letter.
int isupper(c); c is an upper case letter.
int islower(c); c is a lower case letter.
int isdigit(c); c is a digit [0-9].
224. MORE FUNCTIONS
Function Return true if
int isxdigit(c); c is a hexadecimal digit
[0-9 A-F ].
int isalnum(c); c is an alphanumeric character (c is a
letter or a digit);
int isspace(c); c is a SPACE, TAB, RETURN,
NEWLINE, FORMFEED, or vertical tab character.
225. EVEN MORE C FUNCTIONS
Function Return true if
int ispunct(c); c is a punctuation character (neither
control nor alphanumeric).
int isprint(c); c is a printing character.
int iscntrl(c); c is a delete character or ordinary control
character.
226. STILL MORE C FUNCTIONS
Function Return true if
int isascii(c); c is an ASCII character, code less than 0200.
int toupper(int c); convert character c to upper case (leave it
alone if not lower)
int tolower(int c); convert character c to lower case (leave it
alone if not upper)
227. MATHEMATICAL FUNCTIONS AND CODE REUSE
The primary goal of software engineering is to write error-free code.
Code reuse: reusing program fragments that
have been written and tested.
C library functions provide most commonly used functions.
e.g., mathematical library <math.h>
To use existing C library functions, we have to include the header file of
the corresponding library.
e.g., #include <math.h>
228. SOME MATHEMATICAL C LIBRARY FUNCTIONS
Function Header File Description
abs(x) <stdlib.h> Return the absolute value of x
cos(x) <math.h> Return the cosine of angle x
exp(x) <math.h> Return the value of ex
pow(x, y) <math.h> Return the value of xy
sqrt(x) <math.h> Return the squre root of x
229. AN EXAMPLE: THE USAGE OF SQRT
FUNCTION
Suppose we want to write a program which
reads a double value from the user.
Then it computes and outputs the square root of
the double value.