0% found this document useful (0 votes)
41 views

C Module-1

The document provides an introduction to C programming presented by Dr. Naveenkumar D T of SJBIT, Bengaluru. It discusses the history of computers through the different generations from vacuum tubes to present day systems incorporating artificial intelligence. The characteristics, concepts, and examples of each generation are outlined, showing the progression from large, expensive early computers to today's smaller, more powerful and affordable systems.

Uploaded by

naveen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

C Module-1

The document provides an introduction to C programming presented by Dr. Naveenkumar D T of SJBIT, Bengaluru. It discusses the history of computers through the different generations from vacuum tubes to present day systems incorporating artificial intelligence. The characteristics, concepts, and examples of each generation are outlined, showing the progression from large, expensive early computers to today's smaller, more powerful and affordable systems.

Uploaded by

naveen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

Welcome

Introduction to
C
Programming
Dr. Naveenkumar D T
Associate Professor
Department of civil engineering
SJBIT, Bengaluru
Wisdom of wood cutter
C

2
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

3
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

4
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

5
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Introduction to Computers

Dr. Naveenkumar D T
Associate Professor
Department of civil engineering
SJBIT, Bengaluru
C

7
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

8
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

9
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

10
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

11
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

12
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

13
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

14
Dr. Naveenkumar D. T. SJBIT, Bengaluru
What is computer?
C ❑ An electronic device that is designed to accept data, perform the
required mathematical and logical operations at high speed, and
output the result.
❑ Past: large size, high power consumption and costly for
commercial applications.
❑ Hence, used for computing trajectories for astronomical or
military applications
❑ Present: smaller size, less power and cheaper

❑ Opened way for commercial purposes

❑ Cellular phones, GPS units, portable organizers, ATMs, and gas


pumps, work with computers.

15
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Characteristics of Computers
C Speed

Economical Versatile

No IQ Computer Memory

Diligence Accuracy

Automation

16
Dr. Naveenkumar D. T. SJBIT, Bengaluru
❑ Speed: millions of operations/second. The speed usually given in

C nanoseconds (ns) and picoseconds (ps), where 1 ns = Ixl09 sec and 1


ps = 1x1012 sec.
❑ Versatile: multiple tasks of different nature at the same time.

❑ Memory: internal or primary memory (storage space) as well as


external or secondary memory.
❑ Accuracyalways gives accurate results, provided the correct data
and instructions are input.
❑ Automation: task without any user intervention.

❑ Diligence: never get tired of a repetitive task.

❑ No IQ: do not have any decision-making abilities of their own.


They need guidance to perform various tasks.
❑ Economical: Computers are considered as short-term
investments for achieving long-term gains. They save time, money,

17 and energy.

Dr. Naveenkumar D. T. SJBIT, Bengaluru


Stored Program Concept
C ❑ introduced by Sir John Neumann in the late 1940s.
 Before any data is processed, instructions are read into
memory.
 Instructions are stored in the computer's memory for
execution.
 Instructions are stored in binary form (using onlv 0s and 1s).

 Processing starts with the first instruction in the program


which is copied into a control unit circuit. The control unit
executes the instructions.
 Instructions written are performed sequentially until there is
a break in the current flow
 Input/Output and processing operations are performed
18 simultaneously.
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Types of Stored Program Computers

❑ A computer with a Von Neumann architecture

stores data and instructions in the same


memory.

❑ Later Harvard University proposed a stored

program concept in which there was a separate


memory to store data and instructions.

19
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

20
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Computer Generations
C

21
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Vacuum Tubes: The First Generation
❑ Hardware technology manufactured using thousands of
vacuum tubes.
❑ Memory Electromagnetic relay as primary memory and
punched cards to store data and instructions.
❑ Software Technology Programming in machine or
assembly language.
❑ Used for Scientific applications

❑ Examples ENIAC. EDVAC. HDSAC. UNIVAC I, IBM


701

22
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

23
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

24
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Highlights

❑ Fastest calculating device of those times

❑ too bulky and required a complete room for storage

❑ Highly unreliable as vacuum tubes emitted a large

amount of heat and burnt frequently

❑ Required air-conditioned rooms for installation

Costly

❑ Difficult to use

❑ Required constant maintenance because vacuum

25 tubes used filaments that had limited life time.


Dr. Naveenkumar D. T. SJBIT, Bengaluru
Transistors: Second Generation
C (1955-1964)
❑ Hardware: manufactured using transistors

❑ Reliable, powerful, cheaper, smaller, and cooler than vacuum

tubes.

❑ Memory Magnetic core memory was used as primary memory;

magnetic tapes and magnetic disks were used to store data and
instructions. These computers had faster and larger memory than
the first generation computers.

❑ Software Technology Programming was done in high level

programming languages. Batch operating system was used.

❑ Used for Scientific and commercial applications

26 ❑ Examples Honeywell 400, IBM 7030, CDC 1604, UNIVAC LARC


Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

27
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

28
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Highlights
❑ Faster, smaller, cheaper, reliable, and easier to use
than the first generation computers
❑ They consumed 1/I0th the power consumed by first
generation computers
❑ Bulky in size and required a complete room for its
installation
❑ Dissipated less heat than first generation computers
but still required air-conditioned rooms
❑ Costly

29 ❑ Difficult to use
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Integrated Circuits: The Third
C Generation (1964-1975)
❑ Hardware manufactured using integrated chips (ICs). ICs consist of
several components such as transistors, capacitors, and resistors on a
single chip to avoid wired interconnections between components.
These computers used SSI and MSI technology. Minicomputers came
into existence.
❑ Memory Larger magnetic core memory was used as primary
memory; larger capacity magnetic tapes and magnetic disks were used
to store data and instructions.
❑ Software Technology high level programming languages such as
FORTRAN, COBOL, Pascal, and BASIC.
❑ Used for Scientific, commercial, and interactive online applications

30 ❑ Examples IBM 360/370, PDP-8, PADP-11, CDC6600

Dr. Naveenkumar D. T. SJBIT, Bengaluru


C

31
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

32
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Highlights

❑ Faster, smaller, cheaper, reliable, and easier to

use than the second-generation computers

❑ They consumed less power than second


generation computers

33
Dr. Naveenkumar D. T. SJBIT, Bengaluru
The Microprocessor: The Fourth
C Generation (1975-1989)
❑ Hardware Technology lCs with LSI (Large Scale Integrated) and later with
VLSI technology (Very Large Scale Integration). Microcomputers came into
existence. Use of personal computers became widespread. High Speed computer
networks in the form of LANs, WANs, and MANs started growing. Besides
mainframes, supercomputers were also used.
❑ Memory Semiconductor memory as primary memory, large capacity magnetic
disks as built-in secondary memory. Magnetic tapes and floppy disks as portable
storage devices.
❑ Software Technology Programming was done in high level programming
language such as C and C++. GUI based OS (e.g. Windows) introduced. Had
icons and menus among other features. UNIX also introduced as an open source
operating system. Apple Mac OS and MS DOS were also released during this
period. All these operating systems had multi-processing and multi-
programming capabilities.
34
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

35
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

36
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C ❑ Used for Scientific, commercial, interactive

online, and network applications

❑ Examples IBM PC, Apple II, TRS-80, VAX

9000 CRAY-1, CRAY-2, CRAY-X/MP

❑ Highlights Faster, smaller, cheaper, powerful,

reliable and easier to use than the previous


generation computers

37
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Artificial Intelligence: The Fifth
C Generation (1989-Present)
❑ Hardware Technology manufactured using ICs with ULSI. The use of
Internet became widespread and very powerful mainframes, desktops,
portable laptops, and smartphones.
❑ Memory Semiconductor memory as primary memory; large capacity
magnetic disks are as built-in secondary memory. Magnetic tapes and floppy
disks were used as portable storage devices, which have now been replaced by
optical disks and USB flash drives.
❑ Software Technology Programming is done in high-level programming
languages such as Java, Python, and C#. Graphical User Interface (GUI)-based
OS such as Windows, Unix, Linux, Ubuntu, and Apple Mac are being used.
❑ Used for Scientific, commercial, interactive online, multimedia (graphics,
audio, video), and network applications
❑ Examples IBM notebooks, Pentium PCs, SUM workstations, IBM SP/2,
Param supercomputer
38
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

39
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Highlights
❑ Faster, smaller, cheaper, powerful, reliable, and easier to
use than the previous generation computers
❑ Speed of microprocessors and the size of memory are
growing rapidly
❑ High-end features available on mainframe computers in
the fourth generation are now available on the
microprocessors.
❑ Consume less power than computers of prior generations

❑ Air-conditioned rooms required for mainframes and


supercomputers hut not for microprocessors
40
Dr. Naveenkumar D. T. SJBIT, Bengaluru
CLASSIFICATION OF
C COMPUTERS

41
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Supercomputers
C ❑ Among the four - fastest, most powerful, and most expensive

❑ First developed in the 1980s to process large amounts of data


and to solve complex scientific problems.
❑ Use parallel processing technology and can perform more
than one trillion calculations in a second.
❑ A single supercomputer can support thousands of users at
the same time.
❑ Used for weather forecasting, nuclear energy research,
aircraft design, automotive design, online banking,
controlling industrial

42
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Mainframe computers
C ❑ Are large-scale computers (smaller than supercomputers).

❑ Very expensive and need a very large clean room with AC

❑ thereby making them very costly to deploy.

❑ Can also support multiple processors.


 Eg: IBM S/390 mainframe can support 50,000 users at the same
time.

❑ Users can access mainframes by either using terminals or via PCs.

❑ The two types of terminals that can be used with mainframe


systems are as follows:
 Dumb Terminals - only a monitor and a keyboard

 Intelligent Terminals – own processor but no storage


43
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Minicomputers
C ❑ smaller, cheaper, and slower than mainframes

❑ AKA midrange computers, capabilities b/n mainframe


and personal computers.
❑ Used in business, education, hospitals, government
organizations, etc.
❑ Single user or specifically designed to handle multiple
users simultaneously
❑ Can also be used as servers in a networked
environment - hundreds of PCs can be connected to it

44
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Microcomputers
C ❑ AKA PCs, are very small and cheap.

❑ The first one was designed by IBM in 1981 and was named
IBM-PC.
❑ Later on, many computer hardware companies copied this
design and termed as PC-compatible.
❑ Another type of popular PC is designed by Apple.

❑ PCs and PC-compatible computers commonly use the


Windows operating system, while Apple computers use the
Macintosh operating system (MacOS) St classified into the
following categories
❑ Classification: Desktop, Laptops, Workstations, Network

45 Computers, Handheld Computers (Smartphones,, Tablet )


Dr. Naveenkumar D. T. SJBIT, Bengaluru
Designing efficient
programs
Dr. Naveenkumar D T
Associate Professor
Department of civil engineering
SJBIT, Bengaluru
Programming paradigms
C ❑ Programming paradigm is a fundamental style of programming that
defines how the structure and basic elements of a computer program
will be built. The «riimy programs and the set of capabilities. Monolithic
prognmmitlgr-emphasizes on finding a solution
 Monolithic programming – emphasizes on finding solution

 Procedural programming—lays stress on algorithms

 Structured programming—focuses on modules

 Object-oriented programming—emphasizes on classes and objects

 Logic-oriented programming—focuses on goals usually expressed in


predicate calculus
 Rule-oriented programming—makes use of 'if-then-else' rules for
computation
 Constraint-oriented programming—utilizes invariant relationships to

47 solve a problem
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Monolithic programming
C ❑ Written using monolithic programming
language such as assembly language and
BASIC
❑ Consist of global data and sequential code.

❑ The global data can be accessed and modified


(knowingly or mistakenly) from any part of the
program, thereby posing a serious threat lo its
integrity.
48
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

49
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Procedural programming
C ❑ A program is devided into subroutines that can access global
data. To avoid repetition of code, each subroutine performs a
well defined task.
❑ jump', 'goto', and 'call' instructions, the sequence of
execution of instructions can be altered.

50
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Advantages
❑ The only goal is to write correct programs

❑ Programs are easier to write as compared to


monolithic programming
Disadvantages
❑ No concept of reusability

❑ Requires more time and effort to write programs

❑ Programs are difficult to maintain

❑ Global data is shared and therefore may get altered


(mistakenly)
51
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Structured programming
C ❑ Specifically designed to enforce a logical structure on the program
to make it more efficient and easier to understand and modify.
❑ Basically used in large programs that require large development
team to develop different parts of the same program.
❑ Employs a top-down approach in which the overall program
structure is broken down into separate modules. T
❑ his allows the code to be loaded into memory more efficiently and
also be reused in other programs.
❑ Modules are coded separately and tested individually, it is then
integrated with other modules to form the overall program
structure

52
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

53
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Advantages

C ❑ Programs that are easy to understand and change

❑ Gives the big picture first and focus on details later.

❑ Many programmers can work on a single, large program.

❑ Takes less time as modules or procedures written for one program can
be reused
❑ Each module performs a specific task.

❑ Each module has its own local data.

❑ Easy to debug every procedure can be checked individually for the


presence of any error
Disadvantages
❑ Not data-centered

❑ Global data is shared and may get modified

❑ Main focus is on functions


54
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Object-oriented programming
C ❑ organizes software design around data, or objects, rather
than functions and logic. An object can be defined as a
data field that has unique attributes and behavior.
❑ Features:
 Programs are data centred.

 Programs are divided in terms of objects and not procedures.

 Functions that operate on data are tied together with the


data.
 Data is hidden and not accessible by external functions. New
data and functions can be easily added as and when required.
 Follows a bottom up accroach for problem solving.
55
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

56
Dr. Naveenkumar D. T. SJBIT, Bengaluru
ALGORITHM
C ❑ Defined procedure for performing some calculation.

❑ The algorithm gives logic of the program, that is, a step-by-step


description of how to arrive at a solution.
❑ Algorithm provides a blueprint to write a program to solve a
particular problem in finite number of steps.
❑ In order to qualify as an algorithm, a sequence of instructions
must process the following characteristics:
 Instructions must be precise

 Instructions must be unambiguous

 Not even a single instruction must be repeated infinitely

 After the algorithm gets terminated, the desired result must be

57 obtained
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Control Structures Used In Algorithms

C Sequence: each step executed in specified order.

Decision: When the outcome depends on some


condition.

58
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Repetition: executing one or more steps for a
number of times. Can be implemented using
constructs such as the while, do-while, and for
loops.

59
Dr. Naveenkumar D. T. SJBIT, Bengaluru
FLOWCHART
C ❑ A graphical or symbolic representation of a process.

❑ Used to design and document complex processes to help the viewers to visualize
the logic of the process to gain a better understanding of the process and find
flaws, bottlenecks, and other less-obvious features within it.
Start and end symbols also known as the terminal symbol is always the first and the
last symbol in a flowchart.
Generic processing step also called an activity is represents instructions like add a to
b, save the result.
Input/ Output symbols are represented as a parallelogram and are used to get input
from users or display the results to them.
A Conditional or decision symbol is used to depict a Yes/No question or True/False
test.
Labeled connectors represented by an identifying label inside a circle are used in
complex or multi-sheet diagrams to substitute for arrows.

60
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Limitations of using Flowcharts
❑ Drawing flowcharts is a laborious and a time
consuming activity.
❑ Flowchart of a complex program becomes, complex
and clumsy. At times, a little bit of alteration in the
solution may require complete re-drawing of the
flowchart
❑ Essentials of what is done may get lost in the
technical details of how it is done.
❑ There are no well defined standards that limits the
details that must be incorporated in a flowchart
61
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

62
Dr. Naveenkumar D. T. SJBIT, Bengaluru
PSEUDOCODE
C ❑ Structured English that describes algorithms. It facilitates the designers to
focus on the logic of the algorithm without getting bogged down by the
details of language syntax.
❑ Pseudocode is a compact and informal high-level description of an algorithm
that uses the structural conventions of a programming language.
❑ It is meant for human reading rather than machine reading, so it omits the
details that are not essential for humans. Such details include keywords,
variable declarations, system-specific code and subroutines.
❑ It is commonly used in textbooks and scientific publications for documenting
algorithms, and for sketching out the program structure before the actual
coding is done. This would help even the non-programmers to understand
the logic of the designed solution.
❑ There are no standards defined for writing a pseudocode because a
pseudocode is not an executable program. Flowcharts can be considered as a
graphical alternative to pseudocode, but are more spacious on paper.
63
Dr. Naveenkumar D. T. SJBIT, Bengaluru
❑ Example: Write a pseudocode to calculate the weekly wages of an employee. The pay depends
on wages per hour and the number of hours worked. Moreover, if the employee has worked

C for more than 30 hours then he gets twice the wages per hour, for every extra hour that he
has worked.
Read hours worked
Read wages per hour
Set overtime charges to 0
Set overtime hrs to 0
If hours worked > 30 then
Calculate overtime hrs = hours worked – 30
Calculate overtime charges =overtime hrs * (2 * wages per hour)
Set hours worked = hours worked - overtime hrs
ENDIF
Calculate salary = (hours worked * wages per hour) + overtime charges
Display salary
End

64 Variables: hours worked, wages per hour, overtime charges, overtime hrs, salary

Dr. Naveenkumar D. T. SJBIT, Bengaluru


Introduction to C
Dr. Naveenkumar D T
Associate Professor
Department of civil engineering
SJBIT, Bengaluru
INTRODUCTION
C ❑ C was developed in the early 1970s by Dennis

Ritchie at Bell Laboratories

❑C was initially developed for writing system


software

❑ Today, C has become a popular language and

various software programs are written using this


language.

❑ Many other commonly used programming


66 languages such as C++ and Java are also based on C
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Characteristics of C
C ❑ A high level programming language

❑ Small size - C has only 32 keywords - relatively easy to learn

❑ Makes extensive use of function calls

❑ Well suited for structured programming. In this programming approach,

❑ Unlike PASCAL it supports loose typing (as a character can be treated as an


integer and vice versa)
❑ Stable language.

❑ Quick language

❑ Facilitates low level (bitwise) programming

❑ Supports pointers to refer computer memory, array, structures and functions.

❑ C is a core language

❑ C is a portable language.

67 ❑ C is an extensible language

Dr. Naveenkumar D. T. SJBIT, Bengaluru


USES OF C

C ❑ Primarily used for system programming.

❑ The portability, efficiency, the ability to access specific


hardware addresses and low runtime demand on system
resources makes it a good choice for implementing
operating systems and embedded system applications.
❑ Compilers, libraries, and interpreters of other
programming languages are often implemented in C.
❑ Sometimes used as an intermediate language by
implementations of other languages.
 BitC, Gambit, the Glasgow Haskell Compiler, Squeak, and
Vala.

68 ❑ C is widely used to implement end-user applications


Dr. Naveenkumar D. T. SJBIT, Bengaluru
Structure of A C Program
C A C program basically
main()
{
Statement 1;
Statement 2;
……………

consists of the following }


……………
Statement N;

Function1()

parts:
{
Statement 1;
Statement 2;
……………
……………

Preprocessor Commands }
Function2()
Statement N;

Functions
Statement 1;
Statement 2;
……………
……………
Statement N;

Variables }
………………….
………………….
FunctionN()

Statements & Expressions {


Statement 1;
Statement 2;
……………

Comments
……………

69
Statement N;
}

Dr. Naveenkumar D. T. SJBIT, Bengaluru


C YOUR FIRST C PROGRAM
// This is my first program in C

#include<stdio.h>
int main()
{
/* My first program in C */
printf("\n Welcome to the world of C ");
return 0;
}

Output“: Welcome to the world of C

70
Dr. Naveenkumar D. T. SJBIT, Bengaluru
FILES USED IN A C PROGRAM
C
Files in a C
program

Source Header Object Executable


File File File File

71
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Source code file

C ❑ Contains the source code of the program.

❑ The file extension of any C source code file is “.c”.

❑ Contains code that defines the main function and maybe other functions.

❑ The main() is the starting point of execution

Header Files
❑ A file with extension .h

❑ Contains C function declarations and macro definitions to be shared between


several source files.
❑ Advantages

 The programmer wants to use the same subroutines in different programs.

 The programmer wants to change, or add, subroutines, and have those changes
be reflected in all other programs.

❑ Some standard header files are available in C, but the programmer may also
create his own user defined header files

72
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Object Files

C ❑ 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)
❑ Object files have a “.o” extension,

Binary Executable File


❑ Generated by the linker by combining object files to produce
that can be directly executed.
❑ On Windows operating system, the executable files have “.exe”
73 extension.
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Compiling and executing C programs
C ❑ The compilation process is done in two steps.

❑ In the first step, the preprocessor program reads the source file as

text, and produces another text file as output.

❑ Source code lines which begin with the hash symbol are actually

not written in C but in the preprocessor language.

❑ The output of the preprocessor is a text file which does not contain

any preprocessor statements.

❑ This file is ready to be processed by the compiler. The linker


combines the object file with library routines (supplied with the
compiler) to produce the final executable file.

74
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

75
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C KEYWORDS
❑ C has a set of 32 reserved words often known as
keywords.
❑ By convention all keywords must be written in
lowercase (small) letters.
Example: 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,
76 unsigned, void, volatile
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Variables
C ❑ A meaningful name given to the data storage location in
computer memory.
❑ 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.
 Integer value is a whole numbers without a fraction part or decimal point,

 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 ve any letter from the alphabet or from


the ASCII chart and numbers 0 – 9 that are put between single
77 quotes.
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C Initialize Variables:
Variables are initialized with an equal sign followed by a
constant expression.

The general form of initialization is:


variable-name = value; or
type variable-name = value;
Example,
int d = 3, f = 5; /* initializing d and f. •/
double pi = 3.14159 /* declares an approximation of pi. */
char x = 'x’; /* the variable x has the value *x'. */
78
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C

79
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Constants
C ❑ Are identifiers whose value does not change.

❑ 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.
❑ 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
80
Dr. Naveenkumar D. T. SJBIT, Bengaluru
Input/output statements in C
C scanf() function
❑ used to read formatted data from the keyboard. The syntax of the scanf() can be given as,

 scanf (“control string”, arg1, arg2, ………….argn);

❑ The control string specifies the type and format of the data that has to be obtained from
the keyboard and stored in the memory locations pointed by the arguments arg1, arg2,…,
argn.
 The prototype of the control string can be give as: [=%[*][width][modifiers]type=]

❑ * is an optional argument that suppresses assignment of the input field. That is, it
indicates that data should be read from the stream but ignored (not stored in the memory
location).
❑ width is an optional argument that specifies the maximum number of characters to be
read.
❑ modifiers is an optional argument that can be h, l or L for the data pointed by the
corresponding additional arguments. Modifier h is used for short int or unsigned short
int, l is used for long int, unsigned long int or double values. Finally, L is used long double
data values.

81 ❑ Type is same as specifier in printf()

Dr. Naveenkumar D. T. SJBIT, Bengaluru


C int num;
float fnum;
char ch, str[10];
double dnum;
short snum;
long int lnum;
printf(“\n Enter the values : “);
scanf("%d %f %c %s %e %hd %ld", &num, &fnum,
&ch, str, &dnum, &snum, &lnum);
printf("\n num = %d \n fnum = %.2f \n ch = %c \n str =
%s \n dnum = %e \n snum = %hd \n lnum = %ld",
num, fnum, ch, str, dnum, snum, lnum);
82
Dr. Naveenkumar D. T. SJBIT, Bengaluru
C printf() function
❑ used to display information required to the user
and also prints the values of the variables. Its
syntax can be given as
 printf (“conversion string”, variable list);

❑ control string: a C string that contains the text that


has to be written on to the standard output device.
The prototype of the control string can be given as
below

83  %[flags][width][.precision][length]specifier
Dr. Naveenkumar D. T. SJBIT, Bengaluru
flags is an optional argument, which specifies output justification

C like decimal point, numerical


sign, trailing zeros or octadecimal or hexadecimal prefixes.
width is an optional argument which specifies the minimum
number of positions that the output characters will occupy.
precision is an optional argument which specifies the number of
digits to print after the decimal point or the number of characters
to print from a string.
modifier is an optional argument (h, l, or L) , which modifies the
type specifier.
type is used to define the type and the interpretation of the value
of the corresponding argument.
printf ("Welcome to the world of C language");

84 Output: Welcome to the world of C language


Dr. Naveenkumar D. T. SJBIT, Bengaluru
C
flag description
length
h

L
specifiers.
Description
When the argument is a short int or unsigned short int.
When the argument is a long int or unsigned long int for integer

When the argument is a long double (used for floating point specifiers)

- Left-justify within the data given field


width

+ Displays the data with its numeric sign (either


+ or -)
Used to provide additional specifiers like o, specifier Qualifying Input
x, X, 0, 0x or 0X for octal and hexa
# c For single character
decimal values respectively for values
different than zero. d For decimal values

The number is left-padded with zeroes (0) F For floating point numbers
0
instead of spaces E, e Floating point numbers in exponential format
G, G Floating point numbers in the shorter of e format
o For Octal number.
s For a sequence of (string of) characters
u For Unsigned decimal value
x,X For Hexadecimal value.

85
Dr. Naveenkumar D. T. SJBIT, Bengaluru
ω
C

86
86
Dr. Naveenkumar D. T. SJBIT, Bengaluru

You might also like