Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

PROGRAMMING FOR PROBLEM SOLVING

Semester I L T P Credits
Subject code - CSE21CS103PPS 3 0 0 3
Prerequisites:
1. Mathematical Knowledge , Logical and Analytical Thinking

Course Objectives: Course Outcomes:


The objective of this course is to make After completion of the course, the student will
the student be able to
CO103.1 Formulate simple algorithms for
To introduce the basic concepts of arithmetic and logical problem. (PO1, PO2)
Computing environment, algorithms
and flowcharts CO103.2 Implement conditional branching,
iteration and recursion. (PO1, PO3)
To acquire knowledge about the basic
concept of writing a program CO103.3 Decompose a problem into functions
and synthesize a complete program using divide
To understand modular and structured and
programming constructs in C conquer approach.(PO1, PO3,PO4)

To learn the usage of structured data CO103.4 Use arrays, pointers, structures and
types and memory management using file management to solve real world
pointers problems.(PO2, PO3,PO6)
.
To learn the concepts of data handling CO103.5 Apply programming to solve matrix
using pointers addition and multiplication problems and
searching and
sorting problems. (PO2, PO3,PO5)

Unit – I (11)

Introduction to computing: Introduction to components of a computer system (disks, memory, processor,


where a program is stored and executed, operating system, compilers etc.). Algorithm, Flowchart / Pseudo
code with examples
Introduction to C Language : History of C , Features, Structure of C program, Character set, Tokens, Data
types, I/O statements, Type conversion Syntax and Logical Errors in compilation, object and executable code

Unit – II (11)

Operators and Control Structures: Operators, Operator precedence ,Arithmetic expressions, Conditional
Branching and Loops, Writing and valuation of conditionals and consequent branching
Arrays: Arrays (1-D, 2-D), Character arrays and Strings

Unit – III (10)

Basic Algorithms: Searching, Basic Sorting Algorithms (Bubble and Selection), Finding roots of Equations.
Functions: Functions (including using built in libraries), storage Classes, Parameter passing in functions, call
by value. Passing arrays to functions, idea of call by reference
Unit – IV(10)

Recursion: Recursion, as a different way of solving problems. Example programs, such as Finding Factorial,
Fibonacci series.
Structure: Structures, Defining structures and Array of Structures, Unions concept

Unit – V (8)

Pointers : Idea of pointers, Defining pointers, dynamic memory allocation ,Use of Pointers in self-referential
structures, notion of linked list (no implementation), command line arguments.
File Handling: Introduction to File Handling, Types of files , File operations, File input/output statements.

Text Books:

T1. Schaum's Outline of Programming with C ,Byron Gottfried, McGraw-Hill ,2019 ,Fourth Edition(Unit 1-5)
T2. Programming in ANSI C, E. Balaguruswamy, Tata McGraw-Hill,2017, Seventh Edition(Unit 1-5)
T3.Computer Science A structured programming approach using C ,Behrouz A. Forouzan and Richard F.
Gilberg , Cengage Learning , 2007 ,Third Edition(Unit 1-5)

References/ Suggested Reading

R1. Let us C, Yashvant Kanetkar ,BPB publications ,2017 ,Sixteenth Edition


R2 Computer fundamentals and programming ,A.K Sharma ,Universities press ,2018 ,Second Edition
UNIT-I

INTRODUCTION TO COMPUTING

COMPUTER SYSTEMS

A Computer is an electronic device that stores, manipulates and retrieves the data.‖ We can
also refer computer computes the information supplied to it and generates data.
A System is a group of several objects with a process. For Example: Educational System
involves teacher, students (objects). Teacher teaches subject to students i.e., teaching (process).
Similarly a computer system can have objects and process.
The following are the objects of computer System
a) User ( A person who uses the computer)
b) Hardware
c) Software
Hardware: Hardware of a computer system can be referred as anything which we can touch
and feel. Example : Keyboard and Mouse.
The hardware of a computer system can be classified as
Input Devices(I/P)
Processing Devices (CPU)
Output Devices(O/P)

KEYBOARD ALU, CU, MONITOR


MU

OUTPUT

ALU: It performs the Arithmetic and Logical Operations such as


+,-,*,/ (Arithmetic Operators)
&&, || ( Logical Operators)
CU: Every Operation such as storing , computing and retrieving the data should be governed by
the control unit.
MU: The Memory unit is used for storing the data.
The Memory unit is classified into two types.
They are 1) Primary Memory
2) Secondary Memory
Primary memory: The following are the types of memories which are treated as primary ROM:
It represents Read Only Memory that stores data and instructions even when the computer is
turned off. The Contents in the ROM can not be modified once if they are written . It is used to
store the BIOS information.
RAM: It represents Random Access Memory that stores data and instructions when the computer
is turned on. The contents in the RAM can be modified any no. of times by instructions. It is
used to store the programs under execution.
Cache memory: It is used to store the data and instructions referred by processor.
Secondary Memory: The following are the different kinds of memories

Magnetic Storage: The Magnetic Storage devices store information that can be read, erased and
rewritten a number of times.
Example: Floppy Disks, Hard Disks, Magnetic Tapes
Optical Storage: The optical storage devices that use laser beams to read and write stored
data. Example: CD(Compact Disk),DVD(Digital Versatile Disk)

COMPUTER SOFTWARE
Software of a computer system can be referred as anything which we can feel and
see.Example: Windows, icons
Computer software is divided in to two broad categories: system software and application
software .System software manages the computer resources .It provides the interface between the
hardware and the users. Application software, on the other hand is directly responsible for
helping users solve their problems.

System Software
System software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.
The operating system provides services such as a user interface, file and database access, and
interfaces to communication systems such as Internet protocols. The primary purpose of this
software is to keep the system operating in an efficient manner while allowing the users access to
the system.
System support software provides system utilities and other operating services. Examples of
system utilities are sort programs and disk format programs. Operating services consists of
programs that provide performance statistics for the operational staff and security monitors to
protect the system and data.
The last system software category, system development software, includes the language
translators that convert programs into machine language for execution , debugging tools to
ensure that the programs are error free and computer –assisted software engineering(CASE)
systems.

Application software
Application software is broken in to two classes: general-purpose software and application –
specific software. General purpose software is purchased from a software developer and can be
used for more than one application. Examples of general purpose software include word
processors, database management systems , and computer aided design systems. They are labeled
general purpose because they can solve a variety of user computing problems.
Application –specific software can be used only for its intended purpose.

A general ledger system used by accountants and a material requirements planning system used
by a manufacturing organization are examples of application-specific software. They can be used
only for the task for which they were designed they cannot be used for other generalized tasks.
The relationship between system and application software is shown below. In this figure, each
circle represents an interface point .The inner core is hard ware. The user is represented by the
out layer. To work with the system, the typical user uses some form of application software. The
application software in turn interacts with the operating system, which is a part of the system
software layer. The system software provides the direct interaction with the hard ware. The
opening at the bottom of the figure is the path followed by the user who interacts directly with
the operating system when necessary.
COMPUTING ENVIRONMENTS
The word ‗compute„ is used to refer to the process of converting information to data. The
advent of several new kinds of computers created a need to have different computing
environments.
The following are the different kinds of computing environments available
1. Personal Computing Environment
2. Time Sharing Environment
3. Client/Server Environment
4. Distributed Computing Environment
Personal Computing Environment
In 1971, Mercian E. Hoff, working for INTEL combined the basic elements of the central
processing unit into the microprocessor. If we are using a personal computer then all the
computer hardware components are tied together. This kind of computing is used to satisfy the
needs of a single user, who uses the computer for the personal tasks.
Ex: Personal Computer

Time-Sharing Environment
The concept of time sharing computing is to share the processing of the computer basing
on the criteria time. In this environment all the computing must be done by the central computer.
The complete processing is done by the central computer. The computers which ask for
processing are only dumb terminals.

Client/Server Environment
A Client/Server Computing involves the processing between two machines. A client
Machine is the one which requests processing. Server Machine is the one which offers the
processing. Hence the client is Capable enough to do processing. A portion of processing is
done by client and the core(important) processing is done by Server.

Distributed Computing
A distributed computing environment provides a seamless integration of computing
functions between different servers and clients. A client not just a requestor for processing the
information from the server. The client also has the capability to process information. All the
machines Clients/Servers share the processing task.
Example: Ebay on Internet

COMPUTER LANGUAGES
To write a program (tells what to do) for a computer, we must use a computer language.
Over the years computer languages have evolved from machine languages to natural
languages. The following is the summary of computer languages
1940„s -- Machine Languages
1950„s -- Symbolic Languages
1960„s -- High Level Languages
Machine Language
In the earliest days of computers, the only programming languages available were
machine languages. Each computer has its own machine language which is made of streams of
0„s and 1„s. The instructions in machine language must be in streams of 0„s and 1„s. This is also
referred as binary digits. These are so named as the machine can directly understood the
programs
Advantages:
1) High speed execution
2) The computer can understood instruction immediately
3) No translation is needed.
Disadvantages:
1) Machine dependent
2) Programming is very difficult
3) Difficult to understand
4) Difficult to write bug free programs
5) Difficult to isolate an error
Example Addition of two numbers
2 □ 0010
+ 3 □ 0011

5 0101

Symbolic Languages (or) Assembly Language


In the early 1950„s Admiral Grace Hopper, a mathematician and naval officer, developed
the concept of a special computer program that would convert programs into machine language.
These early programming languages simply mirrored the machine languages using symbols or
mnemonics to represent the various language instructions. These languages were known as
symbolic languages. Because a computer does not understand symbolic language it must be
translated into the machine language. A special program called an Assembler translates
symbolic code into the machine language. Hence they are called as Assembly language.
Advantages:
1) Easy to understand and use
2) Easy to modify and isolate error
3) High efficiency
4) More control on
hardware Disadvantages:
1) Machine Dependent Language
2) Requires translator
3) Difficult to learn and write programs
4) Slow development time
5) Less efficient
Example:
2 PUSH2,A
3 PUSH3,B
+ ADDA,B
5 PRINTC
High-Level Languages
The symbolic languages greatly improved programming efficiency they still
required programmers to concentrate on the hardware that they were using working with
symbolic languages was also very tedious because each machine instruction had to be
individually coded. The desire to improve programmer efficiency and to change the focus from
the computer to the problems being solved led to the development of high-level languages.
High-level languages are portable to many different computer allowing the programmer
to concentrate on the application problem at hand rather than the intricacies of the computer.
C A systems implementation Language
C++ C with object oriented enhancements
JAVA Object oriented language for internet and general applications using basic C syntax

Advantages:
1) Easy to write and understand
2) Easy to isolate an error
3) Machine independent language
4) Easy to maintain
5) Better readability
6) Low Development cost
7) Easier to document
8) Portable
Disadvantages:
1) Needs translator
2) Requires high execution time
3) Poor control on hardware
4) Less efficient
Example: C language
#include<stdio.h>
void main()
{
int a, b, c;
scanf("%d%d%",&a,&b);
c=a+b;
printf("%d",c);
}

Difference between Machine, Assembly, High Level Languages

Feature Machine Assembly High Level


Form 0„s and 1„s Mnemonic codes Normal English
Machine Dependent Dependent Dependent Independent
Translator Not Needed Needed(Assembler) Needed(Compiler)
Execution Time Less Less High
Languages Only one Different Manufacturers Different Languages
Nature Difficult Difficult Easy
Memory Space Less Less More

Language Translators
These are the programs which are used for converting the programs in one language into
machine language instructions, so that they can be executed by the computer.

1) Compiler: It is a program which is used to convert the high level


language programs into machine language
2) Assembler: It is a program which is used to convert the assembly
level language programs into machine language
3) Interpreter: It is a program, it takes one statement of a high level language
program, translates it into machine language instruction and then
immediately executes the resulting machine language instruction and soon.
Comparison between a Compiler and Interpreter

COMPILER INTERPRETER
A Compiler is used to compile an entire An interpreter is used to translate each line of
program and an executable program is the program code immediately as it is entered
generated through the object program
The executable program is stored in a disk for The executable program is generated in RAM
future use or to run it in another computer and the interpreter is required for each run of
the program
The compiled programs run faster The Interpreted programs run slower
Most of the Languages use compiler A very few languages use interpreters.

CREATING AND RUNNING PROGRAMS


The procedure for turning a program written in C into machine Language. The process is
presented in a straightforward, linear fashion but you shuld recognize that these steps are
repeated many times during development to correct errors and make improvements to thecode.
The following are the four steps in this process
1) Writing and Editing the program
2) Compiling the program
3) Linking the program with the required modules
4) Executing the program
Sl. No. Phase Name of Code Tools File Extension
1 Text Editor Source Code C Compilers .C
Edit,
Notepad Etc..,
2 Compiler Object Code C Compiler .OBJ
3 Linker Executable C Compiler .EXE
Code
4 Runner Executable C Compiler .EXE
Code

Writing and Editing Programs


The software used to write programs is known as a text editor. A text editor helps
us enter, change and store character data. Once we write the program in the text editor we save it
using a filename stored with an extension of .C. This file is referred as source code file.

Compiling Programs
The code in a source file stored on the disk must be translated into machine language.
This is the job of the compiler. The Compiler is a computer program that translates the source
code written in a high-level language into the corresponding object code of the low-level
language. This translation process is called compilation. The entire high level program is
converted into the executable machine code file. The Compiler which executes C programs is
called as C Compiler. Example Turbo C, Borland C, Get.,

The C Compiler is actually two separate programs:


 The Preprocessor

 The Translator

The Preprocessor reads the source code and prepares it for the translator. While preparing the
code, it scans for special instructions known as preprocessor commands. These commands tell
the preprocessor to look for special code libraries. The result of preprocessing is called the
translation unit.
After the preprocessor has prepared the code for compilation, the translator does the
actual work of converting the program into machine language. The translator reads the
translation unit and writes the resulting object module to a file that can then be combined with
other precompiled units to form the final program. An object module is the code in the machine
language.

Linking Programs
The Linker assembles all functions, the programs functions and system functions into one
executable program.

Executing Programs
To execute a program we use an operating system command, such as run, to load the program into
primary memory and execute it. Getting the program into memory is the function of an operating
system program known as the loader. It locates the executable program and reads it into memory.
When everything is loaded the program takes control and it begin execution.

ALGORITHM

Algorithm is a finite sequence of instructions, each of which has a clear meaning and can be
performed with a finite amount of effort in a finite length of time. No matter what the input values
may be, an algorithm terminates after executing a finite number of instructions.

We represent an algorithm using a pseudo language that is a combination of the constructs of a


programming language together with informal English statements.

The ordered set of instructions required to solve a problem is known as an algorithm.

The characteristics of a good algorithm are:


 Precision – the steps are precisely stated (defined).
 Uniqueness – results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
 Finiteness – the algorithm stops after a finite number of instructions are executed.
 Input – the algorithm receives input.

 Output – the algorithm produces output.


 Generality – the algorithm applies to a set of inputs.

Example
P. Write a algorithm to find out number is odd or even?
Ans.
step 1 : start
step 2 : input number
step 3 : rem=number mod 2
step 4 : if rem=0then
print "number even"
else
print "number odd"
endif
step 5 :stop

FLOWCHART
Flowchart is a diagrammatic representation of an algorithm. Flowchart is very helpful in writing
program and explaining program to others.

Symbols Used In Flowchart


Different symbols are used for different states in flowchart, For example: Input/output and
decision making has different symbols. The table below describes all the symbols that are used in
making flowchart
Symbol Purpose Description

Used to indicate the flow of logic by connecting


Flow line
symbols.

Terminal(Stop/Start) Used to represent start and end of flowchart.

Input/output Used for input and output operation.

Used for arithmetic operations and data-


Processing
manipulations.

Used to represent the operation in which there are


Desicion
two alternatives, true and false.

On-page Connector Used to join different flow line

Off-page Connector Used to connect flowchart portion on different page.

Predefined Used to represent a group of statements performing


Process/Function one processing task.

Examples of flowcharts in programming


Draw a flowchart to add two numbers entered by user.
Draw flowchart to find the largest among three different numbers entered by user.

INTRODUCTION TO C LANGUAGE
C is a general-purpose high level language that was originally developed by Dennis Ritchie for the
Unix operating system. It was first implemented on the Digital Equipment Corporation PDP-11
computer in 1972.
The Unix operating system and virtually all Unix applications are written in the C language. 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.
Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around1970
 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
Why to use C?
C was initially used for system development work, in particular the programs that make-up the
operating system. C was adopted as a system development language because 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
 Prints poolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities
The Unix operating system and virtually all Unix applications are written in the C language. 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.

HISTORY TO C LANGUAGE
C is a general-purpose language which has been closely associated with the UNIX operating system
for which it was developed - since the system and most of the programs that run it are written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards.
The influence of BCPL on C proceeded indirectly through the language B, which was written by
Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DECPDP-
BCPL and B are "type less" languages whereas C provides a variety of data types.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C Programming
Language by Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C. The resulting definition, the ANSI standard, or "ANSI C",
was completed late 1988.

BASIC STRUCTURE OF C PROGRAMMING

18
1. Documentation section: The documentation section consists of a set of comment lines giving
the name of the program, the author and other details, which the programmer would like to use
later.
2. Link section: The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using the
#define directive.
4. Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that
is outside of all the functions. This section also declares all the user-defined functions.
5. main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in the declaration
and executable part end with semicolon.
6. Subprogram section: If the program is a program then the subprogram section contains all the
functions that are called in the main () function. User-defined functions are generally placed
immediately after the main () function, although they may appear in any order.

PROCESS OF COMPILING AND RUNNING C PROGRAM


We will briefly highlight key features of the C Compilation model here.

19
The steps involved in Creating and Running Programs are:
 Writing and Editing Programs
 Compiling Programs
 Linking Programs
 Executing Programs

Writing and Editing Programs


 To solve a particular problem a Program has to be created as a file using text editor /word
processor. This is called source file.
 The program has to be written as per the structure and rules defined by the high-level
language that is used for writing the program ( C, JAVAetc).
Compiling Programs
 The compiler corresponding to the high-level language will scan the source file, checks the
program for the correct grammar (syntax) rules of the language.
 If the program is syntactically correct, the compiler generates an output file called ‗Object File„
which will be in a binary format and consists of machine language instructions corresponding to
the computer on which the program gets executed.

20
Linking Programs:
 Linker program combines the Object File with the required library functions to produce
another file called ― executable file‖. Object file will be the input to the linker program.
 The executable file is created on disk. This file has to be put into (loaded) the memory.
Executing Programs:
 Loader program loads the executable file from disk into the memory and directs the CPU to
start execution.
 The CPU will start execution of the program that is loaded into the memory.

C TOKENS

C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
Each and every smallest individual unit in a C program is known as C tokens. C
tokens are of six types. They are
Keywords (eg: int,while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg:―total‖,―hello‖),Special
symbols (eg: (),{}),
Operators (eg: +,/,-,*)

21
C KEYWORDS
C keywords are the words that convey a special meaning to the c compiler. The keywords
cannot be used as variable names.

The list of C keywords is given below:

auto break case char const

continue default do double else

enum extern float for goto

if int long register return

short signed size of static struct

switch typedef union unsigned void

volatile while

C IDENTIFIERS

Identifiers are used as the general terminology for the names of variables, functions and arrays.
These are user defined names consisting of arbitrarily long sequence of letters and digits with either
a letter or the underscore(_) as a first character.
There are certain rules that should be followed while naming c identifiers:
They must begin with a letter or underscore (_).
They must consist of only letters, digits, or underscore. No other special character is allowed. It
should not be a keyword.
It must not contain whitespace.
Itshouldbeupto31characterslongasonlyfirst31charactersaresignificant. Some
examples of identifiers:

Name Remark

22
A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword

C CONSTANTS
A C constant refers to the data items that do not change their value during the program execution.
Several types of C constants that are allowed in C are:

Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.
Example of valid decimal integer constants
341, -341, 0, 8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants.

Example of valid octal integer constants


010, 0424, 0, 0540
Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or
0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants
0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in programming.

Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.

23
Example of valid real constants in fractional form or decimal
notation 0.05, -0.905, 562.05,0.015

Representing a real constant in exponent form


The general format in which a real number may be represented in exponential or scientific form is
mantissa e exponent
The mantissa must be either an integer or a real number expressed in decimal notation.
The letter e separating the mantissa and the exponent can also be written in uppercase i.e. E And,
the exponent must be an integer.
Examples of valid real constants in exponent form are:
252E85, 0.15E-10, -3e+8
Character Constants
A character constant contains one single character enclosed within single quotes.
Examples of valid character constants
‗a„ , ‗Z„,‗5„
It should be noted that character constants have numerical values known as ASCII values, for
example, the value of ‗A„ is 65 which is its ASCII value.
Escape Characters/ Escape Sequences
C allows us to have certain non graphic characters in character constants. Non graphic characters are
those characters that cannot be typed directly from keyboard, for example, tabs, carriage return, etc.
These non graphic characters can be represented by using escape sequences represented by a backslash()
followed by one or more characters.
NOTE: An escape sequence consumes only one byte of space as it represents a single character.

Escape Sequence Description


a Audible alert(bell)
b Backspace
f Form feed
n New line
r Carriage return
t Horizontal tab
v Vertical tab

24
\ Backslash
― Double quotation mark
‗ Single quotation mark
? Question mark
Null

STRING CONSTANTS
String constants are sequence of characters enclosed within double quotes. For example,
―hello‖
―abc‖
―hello911‖
Every sting constant is automatically terminated with a special character „‟ called thenull
character which represents the end of the string.
For example,―hello‖ will represent―hello‖in the memory.
Thus, the size of the string is the total number of characters plus one for the null character.

SPECIAL SYMBOLS
The following special symbols are used in C having some special meaning and thus, cannot be
used for some other purpose.
[] () {} , ; : * … = #
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
VARIABLES

A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be applied
to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
25
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −

Type Description

char Typically a single octet(one byte). This is an integer type.

int The most natural size of integer for the machine.

float A single-precision floating point value.

double A double-precision floating point value.

void Represents the absence of type.

C programming language also allows defining various other types of variables like Enumeration,
Pointer, Array, Structure, Union, etc.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type as
follows −

type variable_list;

Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-
defined object; and variable list may consist of one or more identifier names separated by commas.
Some valid declarations are shown here −

int i, j, k;
char c, ch;
float f, salary;
double d;

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create
variables named i, j and k of type int.

Variables can be initialized (assigned an initial value) in their declaration. The initialize consists

26
of an equal sign followed by a constant expression as follows −

type variable_name = value;


Some examples are −

extern int d = 3, f=5; // declaration of d andf.


int d = 3, f=5; // definition and initializing d and f.
byte z=22; // definition and initializesz.
char x= 'x'; // the variable x has the value'x'.

For definition without an initialize: variables with static storage duration are implicitly initialized
with NULL (all bytes have the value 0); the initial value of all other variables are undefined.

Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a variable with the
given type and name so that the compiler can proceed for further compilation without requiring
the complete detail about the variable. A variable definition has its meaning at the time of compilation
only; the compiler needs actual variable definition at the time of linking the program. A variable
declaration is useful when multiple files are used.

27
Data types in C Language
Data types specify how we enter data into our programs and what type of data we enter. C language
has some predefined set of data types to handle various kinds of data that we can use in our program.
These data types have different storage capacities.
C language supports 2 different type of data types:

1. Primary data types:

These are fundamental data types in C namely integer (int), floating point (float),
character(char) and void.

2. Derived data types:

Derived data types are nothing but primary data types but a little twisted or grouped together
like array, structure, union and pointer. These are discussed in details later.

Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x
can hold only integer values. Every variable which is used in the program must be declared as what
data-type it is.

28
Integer type
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine:

Type Size(bytes) Range

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535

short int or signed short int 1 -128 to 127

unsigned short int 1 0 to 255

long int or signed long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

Floating point type


Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

Float 4 3.4E-38 to 3.4E+38

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

29
Character type
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

void type

void type means no value. This is usually used to specify the type of functions which returns
nothing. We will get acquainted to this data type as we start learning more advanced topics in C
language, like functions, pointers etc.

I/O Statements:
INPUT AND OUTPUT STATEMENTS :
The simplest of input operator is getchar to read a single character from the input device.
varname=getchar();
you need to declare varname.
The simplest of output operator is putchar to output a single character on the output device.
Syntax: putchar(varname)
The getchar() is used only for one input and is not formatted.
Formatted input refers to an input data that has been arranged in a particular format,
for that we have scanf.
Syntax: scanf("control string", arg1, arg2,...argn);
Control string specifies field format in which data is to be entered.
arg1, arg2... argn specifies address of location or variable where data is stored.
eg scanf("%d%d",&a,&b);
%d used for integers
%f floats

30
%l long
%c character
for formatted output you use printf
Syntax: printf("control string", arg1, arg2,...argn);
/* program to exhibit i/o */
#include<stdio.h> main()
{
int a,b;
float c;
printf("Enter any number");
a=getchar();
printf("the char is ");
putchar(a);
printf("Exhibiting the use of scanf");
printf("Enter three numbers");
scanf("%d%d%f",&a,&b,&c);
printf("%d%d%f",a,b,c);
}

Type Conversion or Type Casting


Definition: Type Casting in C is used to convert a variable from one data type to another data type, and
after type casting compiler treats the variable as of the new data type .
Syntax: (type_name) expression

Example: float f=(float) 9/4;


printf("f : %f\n", f );

Type conversion in c can be classified into the following two types:

 Implicit Type Conversion

 Explicit Type Conversion

31
Implicit Type Conversion

 When the type of conversion is performed automatically by the compiler without the programmer’s
intervention, such type of conversion is known as implicit type conversion or type promotion.
 It is the concept of converting lower data type values into higher data types. Implicit type casting is
under the control of the compiler. So a programmer no need to be considered about the implicit
type casting process.
Explicit Type Conversion

 The type conversion performed by the programmer by posing the data type of the expression of a
specific type is known as explicit type conversion. The explicit type conversion is also known as
typecasting.
 It is a process of converting a higher data type value into a lower data type. Whenever the explicit
type casting is occurred mandatory handling or else data overflow will occur.

Logical Errors in Compilation:


On compilation and execution of a program, desired output is not obtained when certain input
values are given. These types of errors which provide incorrect output but appears to be error
free are called logical errors. These are one of the most common errors done by beginners of
programming.
Object and Executable code:
Object code is the output of a compiler after it processes the source code. The object code is
usually a machine code, also called a machine language, which can be understood directly by a
specific type of CPU
Executable (also called the Binary) is the output of a linker after it processes the object code. A
machine code file can be immediately executable (i.e., runnable as a program), or it might
require linking with other object code files (e.g. libraries) to produce a complete executable
program.

32
Question Bank

1. Differentiate compiler and interpreter.


2. Draw a flow chart to find the roots of quadratic equation.
3. Explain about computer components in detail.
4. What are variables and constants? Give examples.
5. Convert 110101 to decimal.
6. Write the binary equivalent for i)56 ii)71 iii)49
7. Discuss about type conversion with suitable examples.
8. What are the data types in C programming write a program by using them.
9. Write an algorithm for finding minimum and maximum number from the given
list.
10. Write about structure of C program .
11. What is a token? Explain them all with syntax and example.
12. Distinguish between executable code and object code.
13. What are the advantages and disadvantages of structured programming.
14. Illustrate memory hierarchy in computer.
15. Differentiate RAM and ROM.
16. Explain in detail about primary and secondary memory.
17. Define the terms algorithm, flow chart, program.

33

You might also like