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

Programming in C

Bca assignment

Uploaded by

nitin.82singh22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Programming in C

Bca assignment

Uploaded by

nitin.82singh22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CHAPTER 1: INTRODUCTION

1.1 PROGRAMMING LANGUAGES 1.2 GENERATION OF PROGRAMMING LANGUAGE

A programming language is a language which is The generation of programming languages is


designed to express computations that can be connected to advances in technology that brought
performed by the computer. Programming languages about computer generations. There are following
are used to create programs that control the generations of programming languages which are
behavior of a system or to express algorithms.
1. First generation
Every programming language have syntax and
semantics through which computer performs various Machine language is the first generation of
task. Programming languages usually refers high programming languages. This is the lowest level of
level languages such as C, C++, Java etc. These programming languages. It is the only language
languages have unique set of keywords and a special which is understand by the computer. It represents
syntax for organizing program instructions. all the data in form of 0’s and 1’s, corresponding to
be on and off states in a circuit.
While high level programming languages are easy for
the humans to read and understand, the computer In machine language, all the instructions, memory
actually understands the machine language that locations, numbers and characters are represented
consists of numbers only. Each different type of CPU by group of 0’s and 1’s. Machine language programs
has its own unique machine language. There is a are also displayed with octal or hexadecimal. The
language between machine language and high level main advantage of machine language is that the
called assembly language. code can run very fast and efficiently, so it is directly
executed by CPU. But machine language is difficult
NOTE: to learn and more difficult to edit errors. It is not
portable across systems so, architectural
Syntax consideration made portability a tough issue to
In a programming language, Syntax defines the rules resolve.
that govern the structure and arrangement of
keywords, symbols, and other elements. Syntax 2. Second generation
doesn't have any relationship with the meaning of
the statement; it is only associated with the The second generation of programming languages
grammar and structure of the programming includes the assembly language. Assembly language
language. are symbolic programming languages that use
A line of code is syntactically valid and correct if it symbolic notation called mnemonics, to represent
follows all the rules of syntax. Syntax does not have machine language instructions. These languages
to do anything with the meaning of the statement. are closely connected to machine language and
Syntax errors are encountered after the program has internal architecture of computer system. It is also
been executed. Some examples of syntax errors called low level language.
include missing semicolons, undeclared variables,
although such errors are easy to catch. Assembler: Computers can execute only codes
written in machine language. A special program
Semantics which is used to convert assembly language into
Semantics refers to the meaning of the associated machine language is called Assembler.
line of code and how they are executed in a
3. Third generation
programming language. Hence, semantics helps
interpret what function the line of code/program is Third generation language is refinement of second
performing. generation programming language. The second
generation focus on logical structure but third
Semantic errors are encountered and handled
generation make the languages more programmer
during runtime of the program execution. If there is
friendly.
any semantic error and even when the statement
has correct syntax, it wouldn't perform the function In these languages the program structures are not
that was intended for it to do. Thus, such errors are closely related to the internal architecture of
difficult to catch. computer, so it is also called high level language. A
statement written in a high-level language will
To conclude, syntax deals with the grammar and
execute several machines. High level language is act
structure of a code, while semantics tells the system
like a bridge between natural languages and
about the meaning of the code and how it is
machine languages.
supposed to be executed in a programming
language. In high level languages programs were written in
English like manner, so they provide more

Notes are written by: Dr. Anil Kumar


CHAPTER 1: INTRODUCTION

convenient to use and giving the programmer more III Linker: Usually in structural programming we
time to address a client problem. But they do not use modular approach. In this approach, a program
provide the flexibility available in low level is divided into various modules. When a module is
languages. Some high-level languages include compiled, an object file of that module is generated.
BASIC, FORTRAN, PASCAL, COBOL, C, C++, JAVA A linker is an important utility program that takes
and soon. the object files of different modules, produced by the
assembler and compiler, and other code to join them
High level languages are not directly understood by into a single executable file. Usually, compiler
computers so we have required translator which automatically invokes the inker as the last step in
converts high level languages into machine compiling a program.
languages. There are following types of translators:
IV Loader: A loader is a special type of program that
I. Compiler: A compiler is a special type of program copies programs from a storage device to the main
that transform the source code written in high level memory, where they can be executed. The
languages into machine languages. The resultant functionality and complexity of most loaders are
code in 0’s and 1’s is called object code. Object code hidden form the users.
is used to create an executable program.
We can easily understand the compilation of a
A compiler is more intelligent than an assembler it source code in following diagram:
checks all kinds of limits, ranges, errors, etc. But its
program run time is more and occupies a larger part
of memory. It has a slow speed because a compiler
goes through the entire program and then translates
the entire program into machine codes.

If the source code contains errors, then the compiler


will not convert the source code in machine code.

II Interpreter: An Interpreter is a program that


translates a programming language into a 1.3 TYPES OF ERROR
comprehensible language. The interpreter converts
high-level language to an intermediate language. It An error in the C language is an issue that arises in
contains pre-compiled code, source code, etc. a program, making the program not work in the way
it was supposed to work or may stop it from
It translates only one statement of the program at a compiling as well. If an error appears in a program,
time. Interpreters, more often than not are smaller the program can do one of the following three things:
than compilers. the code will not compile, the program will stop
working during execution, or the program will
Difference between Compiler and Interpreter generate garbage values or incorrect output. There
are following types of error:
Compiler Interpreter
i. Syntax error: Syntax errors occur when a
It translates the entire It interprets and
programmer does not follow the set of rules defined
program in one go. executes one statement
for the syntax of in the programming language.
at a time
Syntax error are spelling mistakes, typing mistakes,
It generates errors after It stops translation after
illegal characters, and soon. It is also called compile
translating the entire getting the first error
time error because they are always detected by the
program
compiler. Generally, these errors can be easily
Execution of code is Execution of code is
identified and rectified by programmers.
faster slower
An object file is No object file is ii. Logical error: Errors which occurs when the
generated generated program does not function accurately called logical
It does not require It requires source code error. Logical errors are those errors in which we
source code for later for later execution. think that our code is correct, the code compiles
execution. without any error and gives no error while it is
It requires more memory It requires less memory running, but the output we get is different from the
space space output we expected. Logical errors are harder to find
CPU utilization is more CPU utilization is less in and correct than syntax error. It is also called run
in the case of a the case of a Interpreter. time error.
Compiler.
iii. Semantic error: Errors that occur because the
compiler is unable to understand the written code

Notes are written by: Dr. Anil Kumar


CHAPTER 1: INTRODUCTION

are called Semantic Errors. A semantic error will be that take input from input devices and display
generated if the code makes no sense to the output on output devices are indicated with
compiler, even though it is syntactically correct. It is parallelogram in a flowchart.
like using the wrong word in the wrong place in the
English language. For example, adding a string to an
integer will generate a semantic error. Semantic
errors are different from syntax errors, as syntax
errors signify that the structure of a program is
incorrect without considering its meaning. On the
other hand, semantic errors signify the incorrect 3. Processing: A box represents arithmetic
implementation of a program by considering the instructions. All arithmetic processes such as
meaning of the program. adding, subtracting, multiplication and division are
indicated by action or process symbol.
The most commonly occurring semantic errors are:
use of un-initialized variables, type compatibility,
and array index out of bounds.

iv. Linker Error


4. Decision: Diamond symbol represents a decision
Linker is a program that takes the object files point. Decision based operations such as yes/no
generated by the compiler and combines them into a question or true/false are indicated by diamond in
single executable file. Linker errors are the errors flowchart.
encountered when the executable file of the code
cannot be generated even though the code gets
compiled successfully. This error is generated when
a different object file is unable to link with the main
object file. We can run into a linked error if we have
imported an incorrect header file in the code, we 5. Connectors: Whenever flowchart becomes
have a wrong function declaration, etc. complex or it spreads over more than one page, it is
useful to use connectors to avoid any confusions. It
1.4 FLOW CHART is represented by a circle.

Before we start coding a program it is necessary to


plan the step-by-step solution to the task our
program will carry out. Such a plan can be 6. Flow lines: Flow lines indicate the exact sequence
symbolically developed using a diagram. This in which instructions are executed. Arrows represent
diagram is then called a flowchart. Hence a the direction of flow of control and relationship
flowchart is a symbolic representation of a solution among different symbols of flowchart.
to a given task. A flowchart can be developed for
practically any job. Flowcharting is a tool that can
help us to develop and represent graphically
program logic sequence. It also enables us to trace
and detect any logical or other errors before the
programs are written.

Flowcharts are essential and most popular tools


when learning a programming language. 1.6 RULES FOR CREATING FLOWCHART
1.5 SYMBOLS IN FLOW CHART A flowchart is a graphical representation of an
algorithm. It should follow some rules while creating
1. Terminal: The oval symbol indicates Start, Stop
a flowchart
and Halt in a program’s logic flow. A pause/halt is
Rule 1: Flowchart opening statement must be ‘start’
generally used in a program logic under some error
keyword.
conditions. Terminal is the first and last symbols in
Rule 2: Flowchart ending statement must be ‘end’
the flowchart.
keyword.
Rule 3: All symbols in the flowchart must be
connected with an arrow line.
Rule 4: The decision symbol in the flowchart is
associated with the arrow line.
2. Input/Output: A parallelogram denotes any
function of input/output type. Program instructions

Notes are written by: Dr. Anil Kumar


CHAPTER 1: INTRODUCTION

Advantages of Flowchart involves several calculations. The general format of


the flowcharting steps for computations is
▪ Flowcharts are a better way of communicating
the logic of the system. a) Create variables used in calculations and read
operation.
▪ Flowcharts act as a guide for blueprint during b) Get required data input using variables.
program designed. c) Perform the necessary calculations.
d) Print the result.
▪ Flowcharts help in debugging process.
Example 1: Draw a flow chart to find sum of two
▪ With the help of flowcharts programs can be numbers.
easily analysed.

▪ It provides better documentation.

▪ Flowcharts serve as a good proper


documentation.

▪ Easy to trace errors in the software.

▪ Easy to understand.

▪ The flowchart can be reused for inconvenience in


the future.

▪ It helps to provide correct logic.


Example 2: Draw a flow chart to convert
temperature from Celsius to Fahrenheit.
Disadvantages of Flowchart:

▪ It is difficult to draw flowcharts for large and


complex programs.

▪ There is no standard to determine the amount of


detail.

▪ Difficult to reproduce the flowcharts.

▪ It is very difficult to modify the Flowchart.

▪ Making a flowchart is costly.

▪ Some developer thinks that it is waste of time.


2. Flowcharts for decision making (Conditional
▪ It makes software processes low. flow)

▪ If changes are done in software, then the Computers are used extensively for performing
various types of analysis. The decision symbol is
flowchart must be redrawn.
used in flowcharts to indicate it. The general format
1.7 TECHNIQUES OF FLOW CHART of steps for flowcharting is as follows:

We can draw flow chart using following techniques: a) Perform the test of the condition.
b) If condition evaluates true branch to Yes steps.
1. Flowcharts for computations c) If condition evaluates false branch to No steps.

2. Flowcharts for decision making In decision making there are following types of flow
chart is defined
3. Flowcharts for loops
a) If-else condition:
1. Flowcharts for computations (Sequential flow)

Computers are used to perform many calculations at


high speed. When we develop a program, it also

Notes are written by: Dr. Anil Kumar


CHAPTER 1: INTRODUCTION

Example 3: Draw a flow chart to find maximum


number among two given numbers.

Example 5: Flowchart to get marks for 3 subjects


and declare the result. If the marks >= 35 in all the
subjects the student passes else fails.

b) Nested if condition

3. Flowcharts for loops (Iterative flow)

Looping refers to the repeated use of one or more


steps. i.e., the statement or block of statements
within the loop are executed repeatedly. There are
two types of loops. One is known as the fixed loop
where the operations are repeated a fixed number of
Example 4: Draw a flow chart to find maximum times. In this case, the values of the variables within
number among three given numbers. the loop have no effect

on the number of times the loop is to be executed. In


the other type which is known as the variable loop,
the operations are repeated until a specific condition
is met. Here, the number of times the loop is
repeated can vary. The loop process in general
includes

a) initialising a counter
b) execution of operations
c) testing the completion of operations

Notes are written by: Dr. Anil Kumar


CHAPTER 1: INTRODUCTION

d) incrementing the counter

The test could either be to determine whether the


loop has executed the specified number of times, or
whether a specified condition has been met.

We can understand flow chart for looping by


following flow chart:

Example 8: Draw a flow chart to find reverse of a


given number.
Example 6: Draw a flow chart to find sum of first N
natural numbers.

Example 7: Draw a flow chart for finding factorial of


a given number N.

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

2.1 HISTROY OF C start learning programming languages. It’s fast


because statically typed languages are faster than
The C language was developed in 1972 by Dennis dynamically typed languages.
Ritchie at Bell Laboratories. C language is used by
Dennis Ritchie to develop UNIX operating system. C 3. Modularity
was designed for implementing system software, it
was later widely used for developing portable The concept of storing C programming language
application software. code in the form of libraries for further future uses is
known as modularity. This programming language
Before C many languages were developed. ALGOLs can do very little on its own most of its power is held
introduced in 1960’s for the development of by its libraries. C language has its own library to
structured programming languages. In 1967 Martin solve common problems.
Richards developed a language called BCPL (Basic
Combined Programming Language) which is used for 4. Statically Type
direct access of memory. BCPL was basically a type-
less programming i.e., it had no concept of data C programming language is a statically typed
types. Then in 1970, Ken Thompson developed a language. Meaning the type of variable is checked at
language called B language, which is used to develop the time of compilation but not at run time. This
the first version of UNIX. C took concepts from means each time a programmer types a program
ALGOL, BCPL and B. In addition, C also supports they have to mention the type of variables used.
the concept of data types.
5. General-Purpose Language

From system programming to photo editing software,


the C programming language is used in various
applications. Some of the common applications
where it’s used are as follows:

• Operating systems: Windows, Linux,


iOS, Android,

• Databases: PostgreSQL, Oracle, MySQL, MS SQL

6. Rich set of built-in Operators

It is a diversified language with a rich set of built-


in operators which are used in writing complex or
simplified C programs.
2.2 FEATURES OF C
7. Libraries with Rich Functions
1. Procedural Language
Robust libraries and functions in C help even a
In a procedural language like C step by step, beginner coder to code with ease.
predefined instructions are carried out. C program
may contain more than one function to perform a 8. Middle-Level Language
particular task. New people to programming will
think that this is the only way a particular As it is a middle-level language so it has the
programming language works. There are other combined form of both capabilities of assembly
programming paradigms as well in the programming language and features of the high-level language.
world. Most of the commonly used paradigm is an
9. Portability
object-oriented programming language.
C language is lavishly portable as programs that are
2. Fast and Efficient
written in C language can run and compile on any
Newer languages like Java, python offer more system with either no or small changes.
features than c programming language but due to
10. Easy to Extend
additional processing in these languages, their
performance rate gets down effectively. C
Programs written in C language can be extended
programming language as the middle-level language
means when a program is already written in it then
provides programmers access to direct manipulation
some more features and operations can be added to
with the computer hardware but higher-level
it.
languages do not allow this. That’s one of the
reasons C languages is considered the first choice to
Notes are written by: Dr. Anil Kumar
CHAPTER 2 : INTRODUCTION TO C

2.3 STRUCTURE OF C PROGRAM ii. Multi line comment.

The basic structure of a C program is divided into 6 A comment which does not fit in one line. It presents
parts which makes it easy to read, modify, in multiple lines, then it is called multi line
document, and understand in a particular format. comment. it is also called as block comment. It
always enclosed with in /* ………………… */
Example:

/*This is example to

Multi line comment.

It won’t execute*/

2. Preprocessor Section

All the header files of the program will be declared in


the preprocessor section of the program. Header files
help us to access other’s improved code into our
code. A copy of these multiple files is inserted into
our program before the process of compilation.

These are always beginning with # symbol. It will


Sections are mentioned below: execute at compile time. These gives direction to
compiler. It copies the content of header file into our
1. Documentation program.

2. Preprocessor Section Example:

3. Definition #include<stdio.h>

4. Global Declaration #include<math.h>

5. Main() Function 3. Definition

6. Sub Programs Preprocessors are the programs that process our


source code before the process of compilation. There
1. Documentation are multiple steps which are involved in the writing
and execution of the program. The #define
This section consists of the description of the preprocessor is used to create a constant throughout
program, the name of the program, and the creation the program. Whenever this name is encountered by
date and time of the program. It is specified at the the compiler, it is replaced by the actual piece of
start of the program in the form of comments. defined code.
Anything written as comments will be treated as
documentation of the program. Example:

• Comment is a message. #define Pi 3.14


• It improves the clarity of program.
• It gives extra meaning to program. 4. Global Declaration
• Comments do not compile.
The global declaration section contains global
• Comments do not convert to machine language.
variables, function declaration, and static variables.
• Comments do not execute.
Variables and functions which are declared in this
i. Single line comment. scope can be used anywhere in the program.

A comment which fit in one line, then it is called Example:


single line comment. It is also called as line
int num = 18;
comment. it always begins with “//”.
Example: 5. Main() Function
//This is single line comment. Every C program must have a main function. The
main () function of the program is written in this
section. Operations like declaration and execution

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

are performed inside the curly braces of the main 3. Object files
program.
Object files are generated by compiler as a result of
• It is first executable statement. processing the source code file. Object files contain
• It is entry point. compact binary code of the function definitions.
• It is mandatory. Object files have a ‘.o’ or ‘.obj’ extension.
• It cannot be duplicated.
4. Executable file
• It is user defined function.
The executable file is generated by linker. The linker
We can write main() function in following ways
links the various object files to produce a binary file
i. void main() {} that can be directly executed. In windows executable
files have ‘.exe’ extension.
ii. void main(void){}
2.5 TOKENS IN C
iii. int main(){}
C language has some basic elements and
iv. int main(void){} grammatical rules. These basic elements are:
1. Character set,
6. Sub Programs 2. Variables
3. Data types,
User-defined functions are called in this section of 4. Constants,
the program. The control of the program is shifted to 5. keywords,
the called function whenever they are called from the 6. variable declaration etc.
main or outside the main() function. These are
1. C Character Set
specified as per the requirements of the
The characters that are used in C programs are
programmer.
given below
Example:
1.1 Alphabets
void fun(){} A, B, C …………………Z
a, b, c ………………….z

1.2 Digits
2.4 FILES USED IN C
0,1, 2, 3, 4, 5, 6, 7, 8, 9
Every C program has four types of files which are
1. Source file 1.3 Special characters
2. Header file
3. Object file All special characters are allowed.
4. Executable file
2. Escape Sequences
1. Source file Escape sequence is used for control the position of
cursor on output screen. C supports the
It contains the source code of the program. The file
combination of backslash (/) and some characters
extension of C source code is ‘.c’,
from the C character set to print these characters.
These character combinations are known as escape
2. Header file
sequences and are represented by two characters.
When working with large projects, it is often Escape Meaning Purpose
desirable to separate out certain sub routines from Sequence
the main() of the program. So, make subroutines \b backspace Moves the cursor to the
and store them in a different file called header file. If previous position of the
we miss the required header file in the C program current line
then compiler will generate an error. Some of the
\a bell (alter) Produces a beep sound
standard header files are:
for alert

• stdio.h.—functions for standardized I/O \r carriage Moves the cursor to


• conio.h—functions related with the screen return beginning of the
• string.h—functions for string handling current line.
• math.h—functions for mathematical calculations
\n newline Moves the cursor to the
beginning of the next
line
Notes are written by: Dr. Anil Kumar
CHAPTER 2 : INTRODUCTION TO C

unsigned for
\f from feed Moves the cursor to the sizeof while
initial position of the
next logical page. const do
volatile default
\0 null Used for terminate the
string.

\v vertical tab Moves the cursor to 5. Identifiers


next vertical tab
All the words that we’ll use in our C programs will
position
be either keywords or identifiers. Keywords are
\t Horizontal tab Moves the cursor to the predefined and can’t be changed by the user, while
next horizontal tab identifiers are user defined words and are used to
position. give names to entities like variables, arrays,
functions, structures etc.
\\ Backslash Character with
backslash (\) Rules for Naming identifiers

\’ Single quotes Single quotation (1) The name should consist of only alphabets (a-z
and A-Z), digits (0-9) and underscored sign (_)
\” Double Double quotation
(2) Identifier name should be unique.
quotes
(3) First character should be an alphabet or
\? Question Present question mark underscore.
mark
(4) The name should not be a reserved keyword.

Blank, horizontal tab, vertical tab, newline, carriage (4) Identifiers are case sensitive i.e.; uppercase and
return, from feed are known as whitespace in C lowercase letters are considered different.
language. (5) White spaces are not allowed.

3. Delimiters (6) Allowed length of identifier is only first 31


characters.
Delimiters are used for syntactic meaning in C.
These are as given below
6. Data Types
: colon used for label
; semicolon end of statement C supports different types of data. Storage
() parentheses used in expression representation of these data types is different in
[] square brackets used for array memory. There are four fundamental data types in
{} curly braces used for block of statements C, which are int, char, float and double. We can use
# hash preprocessor directive type qualifiers with these basic types to get some
, comma variable delimiter more types.

4. Reserved Words / Keywords There are two types of type qualifiers

There are certain words that are reserved for doing 1. Sign qualifiers: signed, unsigned
specific tasks. These words are known as keywords 2. Size qualifiers: short, long
and they have standard, predefined meaning in C.
They are always written in lowercase. There are 1. Sign qualifiers: When the qualifier unsigned is
only 32 keywords available in C which are given used the number is always positive, and when
below: signed is used number may be positive or negative.
Variable Control Storage User Function If the sign qualifier is not mentioned, then by
related Statement classes defined related default signed qualifier is assumed. The range of
related related data values for signed data types is less than that of
types
unsigned type. This is because is signed type, the
char if auto struct return leftmost bit is used to represent the sign, while in
int else extern union void unsigned type this bit is also used to represent the
value.
float switch register typedef
double case Static enum 2. Size quantifiers: The size and range of different
data types on a 16-bit machine is given in the
long break
following table. The size and range may vary on
short continue machines with different word sizes.
signed goto

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

suffixing it with 1 or L for long, u or U for


unsigned, ul or UL for unsigned long.

Example:

6453----->int
67238736UL or 67238736ul -->unsigned long
int
7655U or 7655u -->unsigned int

7.1.2 Real or floating-point Literal

Floating point constants are numeric constants


that contain decimal point.

For expressing very large or very small real


constants, exponential (scientific) form is used.
Here the number is written in the mantissa and
exponent form, which are separated by ‘e’ or ‘E’.
The mantissa can be an integer or a real number,
while the exponent can be only an integer (positive
or negative). For example, the number 280000 can
be written as 2.8e5, here 2.8 is mantissa and 5 is
the exponent.

By default, the type of a floating-point constant is


double. We can explicitly mention the type of
7. Literal
constant by suffixing it with f or F for float type, 1
Literal is a constant value that cannot be changed or L for long double.
during execution of the program. Constants is the
Example:
most fundamental and essential part of the C
programming language. There are three types of 4.5e8--->double
Literals 4.5e-10l or 4.5e-10L -->long double
(1) Numeric 8.5f or 8.5F-->float
(2) Character
(3) String 7.2 Character Constant

7.1 Numeric A character constant is a single character that is


enclosed within single quotes.
Numeric literal consists of numeric digits. There
are two types of numeric constants Every character constant has a unique integer
value associated with it. This integer is the numeric
7.1.1 Integer Literal value of the character in the machine’s character
Integer literals are integer numbers. There are code called ASCII values. Some ASCII values are
three types of integer literals based on different A – Z ----65 – 90
number systems.
a – z ----97–122
I. Decimal literal: Every integer literal is by 0 – 9----48 – 57
default decimal literal. it contains all digits from 0
; ----59
to 9
II. Octal literal: An integer literal which starts
with 0 is called octal literal. Allowed digits are from 7.3 String Constant
0 to 7.
A string constant has zero, one or more than one
III. Hexa decimal literal: In hexadecimal integer
character. A string constant is enclosed within
literal, first two characters should be 0x or 0X.
double quotes (“ ”). At the end of string, /0 is
automatically placed by the compiler.
NOTE:
By default, the type of an integer constant is int.
7.4 Symbolic Constant
But if the value of integer constant exceeds the
range of values represented by int type, the type is If we want to use a constant several times then we
taken to be unsigned int or long int. We can also can provide it a name. These types of constants are
explicitly mention the type of the constant by called symbolic constants or named constants.

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

A symbolic constant is a name that substitutes for Example:


a sequence of characters. The characters may
/* c is middle level programming */
represent a numeric constant, a character constant
(Single line comment)
or a string constant.
/* This is a C program to print Hello
These constants are generally defined at the C language*/
beginning of the program as (Multiple line comment)
#define name value
Note:
Here ‘name’ is the symbolic name for the constant, Comments can’t be nested i.e.; we can’t write a
and is generally written in uppercase letters. ‘value’ comment inside another comment.
can be numeric, character or string constant.

Example: 2.5 I/O functions


#define PI 3.14 Input means to feed some data into a program. An
input can be given in the form of a file or from the
8. Variables command line. C programming provides a set of
Variable is a name that can be used to store values. built-in functions to read the given input and feed it
Variables can take different values but one at a to the program as per requirement.
time. These values can be changed during Output means to display some data on screen,
execution of the program. A data type is associated printer, or in any file. C programming provides a set
with each variable. The data type of the variable of built-in functions to output the data on the
decides what values it can take. computer screen as well as to save it in text or
8.1 Declaration of Variables binary files. There are two type of input output
functions available in C:
It is must to declare a variable before it is used in
the program. Declaration of a variable specifies its 1. Formatted I/O functions
name and datatype. The type and range of values 2. Unformatted I/O functions
that a variable can store depends upon its
datatype. The syntax of declaration of a variable is 1. Formatted I/O functions

Datatype variable name; Formatted I/O functions are used to take various
inputs from the user and display multiple outputs
Here datatype may be char, int, float or double. to the user. These types of I/O functions can help
Example: int x; to display the output to the user in different
We can also declare more than one variable in a formats using the format specifiers. These functions
single declaration. are called formatted I/O functions because we can
use format specifiers in these functions and hence,
Example: int x, y, z; we can format these functions according to our
8.2 Initialization of Variables needs.

When a variable is declared it contains undefined These I/O supports all data types like int, float,
value commonly known as garbage value. If we char, and many more. We can use scanf() function
want, we can assign some initial value to the which takes input data from keyboard and printf()
variable during the declaration itself, this is called function which produce output. Both functions are
initialization of the variable. included in the header file stdio.h.

Example: 1.1. Conversion Specifications

int a = 10; The functions scanf() and printf() make use of


conversion specifications of specify the type and
float a = 1.5, b = 12.5; size of data. Each conversion specification must
begin with a percent sign (%). conversion
specifications are as follows:
9. Comments
%c - a single character
Comments are used for increasing readability of the
program. They explain the purpose of the program %d - a decimal integer
and are helpful in understanding the program. %f - a floating point number
Comments are written inside /* and */. There can %e - a floating point number
be single line or multiple line comments. We can
%g - a floating point number
write comments anywhere in a program except
inside a string constant or a character constant. %lf - For double data type
%h - a short integer

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

%o - an octal integer main ( )


{
%x - a hexadecimal integer
int a;
%i - a decimal, octal or hexadecimal float b;
%s - a string …….. . .
scanf (“%d,%d”, &a, &b);
%u - an unsigned decimal integer …….. .
%p - for address in hexadecimal }
Here the delimiter is comma ( , ). The input data
can be entered as --->10, 20
Note:
The modifier h can be used before conversion
1.3. Writing Output Data
specifications d, i, o, u, x to specify short integer
and the modifier l can be used before them to Output data can be written from computer memory
specify a long integer. The modifier l can be used to the standard output device (monitor) using
before conversion specifications f, e, g to specify printf( ) library function. With this function all type
double while modifier L can be used before them to of values (numeric, character or string) can be
specify a long double. For example, %Id, %hd, %Lf, written as output. The printf( ) function can be
%hx are valid conversion specifications. written as
printf(“control string”, variable 1, variable 2,…);
1.2 Reading Input Data
In this function the control string contains
Input data can be entered into the memory from a conversion specification characters and text. It
standard input device (keyboard). C provides the should be enclosed within double quotes. The name
scanf( ) library function for entering input data. of variables should not be preceded by an
This function can take all types of values (numeric, ampersand (&) sign. If the control string does not
character, string) as input. The scanf( ) function contain any conversion specification, then the
can be written as variable names are not specified.
scanf(“control string”,address1, address2, ….); 1.4 Justification in Input And Output
This function should have at least two parameters. Formatted input and output means that data is
First parameter is a control string, which contains entered and displayed in a particular format.
conversion specification characters. It should be Through format specifications better presentation of
within double quotes. The conversion specification result can be obtained. Formats for different
characters may be one or more; it depends on the specifications are as-
number of variables we want to input. The other
parameters are addresses of variables. In scanf() 1.4.1 Format For Integer Input
function at least one address should be present. % wd
The address of a variable is found by preceding the
variable name by an ampersand (&) sign. This sign Here ‘d’ is the conversion specification character for
is called the address operator and it gives the integer value and ‘w’ is an integer number
starting address of the variable name in memory. A specifying the maximum field width of input data. If
string variable is not preceded by & sign to get the the length of input is more than this maximum field
address. width then the values are not stored correctly. For
example:
When more than one values are input by scanf(),
these values can be separated by whitespace scanf (“%2d%3d”, &a, &b);
character like space, tab or newline (default). A (i) When input data length is less than the given
specific character can also be placed between two field, width and then the input values are
conversion specification characters as a delimiter. unaltered and stored in given variables.
main() Input-
{
int a; 5 36
float b;
Result-
………
scanf (“% d:%f”, &a, &b); 5 is stored in a and 36 is stored in b.
……...
} (ii) When input data length is equal to the given
field width, then the input values are unaltered
Here the delimiter is colon ( : ). The input data can
and stored in given variables.
be entered as-->10:15.20
Input-
36 100

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

Result- 1.4.3 Format For Floating Point Numeric Input


36 is stored in a and 100 is stored in b. % wf

(iii) When input data length is more than the given Here ‘w’ is the integer number specifying the total
field width, then the input values are altered width of the input data (including the digits before
and stored in the variable as – and after decimal and the decimal itself). For
example:
Input-
123 1234 scanf(“%3f %4f “, &x, &y);

Result- (i) When input data length is less than the given
width, values are unaltered and stored in the
12 is stored in a and 3 is stored in b and the
variables.
rest of input is ignored.
Input
1.4.2 Format For Integer Output
2 2.3
% wd
Result
Here w is the integer number specifying the
2.0 is stored in x and 2.30 is stored in y.
minimum field width of the output data. If the
length of the variable is less than the specified field (ii) When input data length is equal to the given
width, then the variable is right justified with width, then the given values are unaltered and
leading blanks. stored in the given variables.

For example – Input

prinft(“a=%3d, b=%4d”, a, b); 2.0 2.30

(i) When the length of variable is less than the Result


width specifier. 2.0 is stored in x and 2.30 is stored in y

(iii) When input data length is more than the given


Value of variable -
width then the given values are altered and
35 6 stored in the given variables as -
Output : Input
a = 3 5 , b = 6 2.36 23.45

Result
The width specifier of first data is 3 while there are
2.3 is stored in x and 6.00 is stored in y.
only 2 digits in it, so there is one leading blank. The
width specifier of second data is 4 while there is
1.4.4 Format For Floating Point Numeric
only 1 digit, so there are 3 leading blanks.
Output
(ii) When the length of the variable is equal to the % w.nf
width specifier
Here w is the integer number specifying the total
Value of variables - width of the input data and n is the number of
123 4567 digits to be printed after decimal point. For example

Output: printf(“x = %4. 1f, y = %7.2f ”, x, y);

a = 1 2 3 , b = 4 5 6 7 If the total length of the variable is less than the


specified width ‘w’, then the value is right justified
with leading blanks. If the number of digits after
(iii) When length of variable is more than the width
decimal is more than ‘n’ then the digits are rounded
specifier, then also the output is printed
off.
correctly.
Value of variables
3 3.6
Value of variables -
1234 45678 Output :

Output : x = 3 . 0 , y = 3 . 6 0

a = 1 2 3 4 , b = 4 5 6 7 8
Value of variables
10.5 2345.67

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

Output :

x = 1 0 . 5 , y = 2 3 4 5 . 6 7

Value of variables
12.345 12.345678

Output :

x = 1 2 . 3 , y = 1 2 . 3 4

1.4.5 Format For String Input


% ws

Here w specifies the total number of characters that


will be stored in the string.

char str [15] ;


scanf (“%4s”, str);

If the input is

fluxeducare

Only first three characters of this input will be


stored in the string, so the characters in the string
will be –

‘f’, ‘l’, ‘u’, ’x’, ‘\0’

The null character (‘\0’) is automatically stored at


the end.

1.4.6 Format For String Output


%w.ns

Here w is the specified field width. Decimal point


and ‘n’ are optional. If present then ‘n’ specifies that
only first n characters of the string will be displayed
and (w – n) leading blanks are displayed before
string.

(i) printf(“%3s”, “fluxeducare” );

f l u x e d u c a r e

(ii) printf(“%10s”, “flux” );

f l u x

(iii) printf(“%.4s”, “fluxeducare “ );

f l u x

(iv) printf(“%8.4s”, “fluxeducare “);

f l u x

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

2. UNFORMATTED I/O FUNCTIONS characters is typed by the user and this function
reads one character at one time until and unless the
Unformatted I/O functions are used only for
enter key is pressed. This function is declared in
character data type or string and cannot be used
stdio.h.
for any other datatype. These functions are used to
read single input from the user at the console and Syntax:
it allows to display the value at the console.
Variable-name = getchar();
These functions are called unformatted I/O
#include <conio.h>
functions because we cannot use format specifiers #include <stdio.h>
in these functions and hence, cannot format these void main()
functions according to our needs. {
char ch;
There are following types of unformatted I/O printf("Enter the character: ");
functions: ch = getchar();
printf("%c", ch);
2.1 getch()
}
This function reads a single character from the
keyboard by the user but doesn’t display that 2.4 putchar()
character on the console screen and immediately
returned without pressing enter key. This function is The putchar() function is used to display a single
declared in conio.h. It is also used for hold the character at a time by passing that character
screen. directly to it or by passing a variable that has
already stored a character. This function is declared
Syntax: in stdio.h.
getch(); or variable-name = getch(); Syntax:
#include <conio.h> putchar(variable_name);
#include <stdio.h> #include <conio.h>
#include <stdio.h>
void main()
void main()
{ {
char ch;
printf("Enter any character: "); printf("Enter any character: ");
ch = getchar();
// Reads a character but not displays putchar(ch);
getch(); }

}
2.5 gets()
2.2 getche()
gets() function reads a group of characters or strings
getche() function reads a single character from the from the keyboard by the user and these characters
keyboard by the user and displays it on the console get stored in a character array. This function allows
screen and immediately returns without pressing the us to write space-separated texts or strings. This
enter key. This function is declared in conio.h. function is declared in stdio.h.

Syntax: Syntax:

getche(); or gets(string_name);

variable_name = getche(); #include <conio.h>


#include <stdio.h>
void main()
{
#include <conio.h>
char name[50];
#include <stdio.h>
printf(“Enter name: ");
void main()
gets(name);
{
printf("You have entered: %s", name);
printf("Enter any character: ");
}
// Reads a character and displays immediately
getche();
} 2.7 puts()

puts() function is used to display a group of


2.3 getchar() characters or strings which is already stored in a
The getchar() function is used to read only a first character array. This function is declared in stdio.h.
single character from the keyboard whether multiple
Notes are written by: Dr. Anil Kumar
CHAPTER 2 : INTRODUCTION TO C

Syntax:
functions. some examples of
puts(string_name ); these functions.
#include <stdio.h>
void main()
{
char name[50];
printf("Enter your name: ");
gets(name);
printf("Your name is: ");
puts(name);
}

2.8 putch()

putch() function is used to display a single character


which is given by the user and that character prints
at the current cursor location. This function is
declared in conio.h.

Syntax:

putch(variable_name);

#include <conio.h>
#include <stdio.h>
void main()
{
char ch;
printf("Enter any character:\n ");
ch = getch();
printf("\nEntered character is: ");
putch(ch);
}

Formatted I/O Unformatted I/O


functions functions

These functions do
These functions allow
not allow to take
us to take input or
1 input or display
display output in the
output in user
user’s desired format.
desired format.

These functions do
These functions support
2 not support format
format specifiers.
specifiers.

These are used for These functions are


3 storing data more user not more user-
friendly friendly.

Here, we can use


Here, we can use all
4 only character and
data types.
string data types.

printf(), scanf() are getch(), getche(),


5
examples of these gets() and puts(), are

Notes are written by: Dr. Anil Kumar


CHAPTER 2 : INTRODUCTION TO C

Notes are written by: Dr. Anil Kumar

You might also like